babylon.abstractMesh.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. module BABYLON {
  2. export class AbstractMesh extends Node implements IDisposable {
  3. // Statics
  4. private static _BILLBOARDMODE_NONE = 0;
  5. private static _BILLBOARDMODE_X = 1;
  6. private static _BILLBOARDMODE_Y = 2;
  7. private static _BILLBOARDMODE_Z = 4;
  8. private static _BILLBOARDMODE_ALL = 7;
  9. public static get BILLBOARDMODE_NONE(): number {
  10. return AbstractMesh._BILLBOARDMODE_NONE;
  11. }
  12. public static get BILLBOARDMODE_X(): number {
  13. return AbstractMesh._BILLBOARDMODE_X;
  14. }
  15. public static get BILLBOARDMODE_Y(): number {
  16. return AbstractMesh._BILLBOARDMODE_Y;
  17. }
  18. public static get BILLBOARDMODE_Z(): number {
  19. return AbstractMesh._BILLBOARDMODE_Z;
  20. }
  21. public static get BILLBOARDMODE_ALL(): number {
  22. return AbstractMesh._BILLBOARDMODE_ALL;
  23. }
  24. // Properties
  25. public definedFacingForward = true; // orientation for POV movement & rotation
  26. public position = new Vector3(0, 0, 0);
  27. public rotation = new Vector3(0, 0, 0);
  28. public rotationQuaternion: Quaternion;
  29. public scaling = new Vector3(1, 1, 1);
  30. public billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  31. public visibility = 1.0;
  32. public alphaIndex = Number.MAX_VALUE;
  33. public infiniteDistance = false;
  34. public isVisible = true;
  35. public isPickable = true;
  36. public showBoundingBox = false;
  37. public showSubMeshesBoundingBox = false;
  38. public onDispose = null;
  39. public checkCollisions = false;
  40. public isBlocker = false;
  41. public skeleton: Skeleton;
  42. public renderingGroupId = 0;
  43. public material: Material;
  44. public receiveShadows = false;
  45. public actionManager: ActionManager;
  46. public renderOutline = false;
  47. public outlineColor = Color3.Red();
  48. public outlineWidth = 0.02;
  49. public renderOverlay = false;
  50. public overlayColor = Color3.Red();
  51. public overlayAlpha = 0.5;
  52. public hasVertexAlpha = false;
  53. public useVertexColors = true;
  54. public applyFog = true;
  55. public useOctreeForRenderingSelection = true;
  56. public useOctreeForPicking = true;
  57. public useOctreeForCollisions = true;
  58. public layerMask: number = 0x0FFFFFFF;
  59. // Physics
  60. public _physicImpostor = PhysicsEngine.NoImpostor;
  61. public _physicsMass: number;
  62. public _physicsFriction: number;
  63. public _physicRestitution: number;
  64. // Collisions
  65. public ellipsoid = new Vector3(0.5, 1, 0.5);
  66. public ellipsoidOffset = new Vector3(0, 0, 0);
  67. private _collider = new Collider();
  68. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  69. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  70. private _newPositionForCollisions = new Vector3(0, 0, 0);
  71. // Cache
  72. private _localScaling = Matrix.Zero();
  73. private _localRotation = Matrix.Zero();
  74. private _localTranslation = Matrix.Zero();
  75. private _localBillboard = Matrix.Zero();
  76. private _localPivotScaling = Matrix.Zero();
  77. private _localPivotScalingRotation = Matrix.Zero();
  78. private _localWorld = Matrix.Zero();
  79. public _worldMatrix = Matrix.Zero();
  80. private _rotateYByPI = Matrix.RotationY(Math.PI);
  81. private _absolutePosition = Vector3.Zero();
  82. private _collisionsTransformMatrix = Matrix.Zero();
  83. private _collisionsScalingMatrix = Matrix.Zero();
  84. public _positions: Vector3[];
  85. private _isDirty = false;
  86. public _masterMesh: AbstractMesh;
  87. public _boundingInfo: BoundingInfo;
  88. private _pivotMatrix = Matrix.Identity();
  89. public _isDisposed = false;
  90. public _renderId = 0;
  91. public subMeshes: SubMesh[];
  92. public _submeshesOctree: Octree<SubMesh>;
  93. public _intersectionsInProgress = new Array<AbstractMesh>();
  94. private _onAfterWorldMatrixUpdate = new Array<(mesh: AbstractMesh) => void>();
  95. // Loading properties
  96. public _waitingActions: any;
  97. constructor(name: string, scene: Scene) {
  98. super(name, scene);
  99. scene.addMesh(this);
  100. }
  101. // Methods
  102. public get isBlocked(): boolean {
  103. return false;
  104. }
  105. public getLOD(camera: Camera): AbstractMesh {
  106. return this;
  107. }
  108. public getTotalVertices(): number {
  109. return 0;
  110. }
  111. public getIndices(): number[] {
  112. return null;
  113. }
  114. public getVerticesData(kind: string): number[] {
  115. return null;
  116. }
  117. public isVerticesDataPresent(kind: string): boolean {
  118. return false;
  119. }
  120. public getBoundingInfo(): BoundingInfo {
  121. if (this._masterMesh) {
  122. return this._masterMesh.getBoundingInfo();
  123. }
  124. if (!this._boundingInfo) {
  125. this._updateBoundingInfo();
  126. }
  127. return this._boundingInfo;
  128. }
  129. public get useBones(): boolean {
  130. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind);
  131. }
  132. public _preActivate(): void {
  133. }
  134. public _activate(renderId: number): void {
  135. this._renderId = renderId;
  136. }
  137. public getWorldMatrix(): Matrix {
  138. if (this._masterMesh) {
  139. return this._masterMesh.getWorldMatrix();
  140. }
  141. if (this._currentRenderId !== this.getScene().getRenderId()) {
  142. this.computeWorldMatrix();
  143. }
  144. return this._worldMatrix;
  145. }
  146. public get worldMatrixFromCache(): Matrix {
  147. return this._worldMatrix;
  148. }
  149. public get absolutePosition(): Vector3 {
  150. return this._absolutePosition;
  151. }
  152. public rotate(axis: Vector3, amount: number, space: Space): void {
  153. if (!this.rotationQuaternion) {
  154. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  155. this.rotation = Vector3.Zero();
  156. }
  157. if (!space || space === Space.LOCAL) {
  158. var rotationQuaternion = Quaternion.RotationAxis(axis, amount);
  159. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  160. }
  161. else {
  162. if (this.parent) {
  163. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  164. invertParentWorldMatrix.invert();
  165. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  166. }
  167. rotationQuaternion = Quaternion.RotationAxis(axis, amount);
  168. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  169. }
  170. }
  171. public translate(axis: Vector3, distance: number, space: Space): void {
  172. var displacementVector = axis.scale(distance);
  173. if (!space || space === Space.LOCAL) {
  174. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  175. this.setPositionWithLocalVector(tempV3);
  176. }
  177. else {
  178. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  179. }
  180. }
  181. public getAbsolutePosition(): Vector3 {
  182. this.computeWorldMatrix();
  183. return this._absolutePosition;
  184. }
  185. public setAbsolutePosition(absolutePosition: Vector3): void {
  186. if (!absolutePosition) {
  187. return;
  188. }
  189. var absolutePositionX;
  190. var absolutePositionY;
  191. var absolutePositionZ;
  192. if (absolutePosition.x === undefined) {
  193. if (arguments.length < 3) {
  194. return;
  195. }
  196. absolutePositionX = arguments[0];
  197. absolutePositionY = arguments[1];
  198. absolutePositionZ = arguments[2];
  199. }
  200. else {
  201. absolutePositionX = absolutePosition.x;
  202. absolutePositionY = absolutePosition.y;
  203. absolutePositionZ = absolutePosition.z;
  204. }
  205. if (this.parent) {
  206. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  207. invertParentWorldMatrix.invert();
  208. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  209. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  210. } else {
  211. this.position.x = absolutePositionX;
  212. this.position.y = absolutePositionY;
  213. this.position.z = absolutePositionZ;
  214. }
  215. }
  216. // ================================== Point of View Movement =================================
  217. /**
  218. * Perform relative position change from the point of view of behind the front of the mesh.
  219. * This is performed taking into account the meshes current rotation, so you do not have to care.
  220. * Supports definition of mesh facing forward or backward.
  221. * @param {number} amountRight
  222. * @param {number} amountUp
  223. * @param {number} amountForward
  224. */
  225. public movePOV(amountRight : number, amountUp : number, amountForward : number) : void {
  226. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  227. }
  228. /**
  229. * Calculate relative position change from the point of view of behind the front of the mesh.
  230. * This is performed taking into account the meshes current rotation, so you do not have to care.
  231. * Supports definition of mesh facing forward or backward.
  232. * @param {number} amountRight
  233. * @param {number} amountUp
  234. * @param {number} amountForward
  235. */
  236. public calcMovePOV(amountRight : number, amountUp : number, amountForward : number) : Vector3 {
  237. var rotMatrix = new Matrix();
  238. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  239. rotQuaternion.toRotationMatrix(rotMatrix);
  240. var translationDelta = Vector3.Zero();
  241. var defForwardMult = this.definedFacingForward ? -1 : 1;
  242. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  243. return translationDelta;
  244. }
  245. // ================================== Point of View Rotation =================================
  246. /**
  247. * Perform relative rotation change from the point of view of behind the front of the mesh.
  248. * Supports definition of mesh facing forward or backward.
  249. * @param {number} flipBack
  250. * @param {number} twirlClockwise
  251. * @param {number} tiltRight
  252. */
  253. public rotatePOV(flipBack : number, twirlClockwise : number, tiltRight : number) : void {
  254. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  255. }
  256. /**
  257. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  258. * Supports definition of mesh facing forward or backward.
  259. * @param {number} flipBack
  260. * @param {number} twirlClockwise
  261. * @param {number} tiltRight
  262. */
  263. public calcRotatePOV(flipBack : number, twirlClockwise : number, tiltRight : number) : Vector3 {
  264. var defForwardMult = this.definedFacingForward ? 1 : -1;
  265. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  266. }
  267. public setPivotMatrix(matrix: Matrix): void {
  268. this._pivotMatrix = matrix;
  269. this._cache.pivotMatrixUpdated = true;
  270. }
  271. public getPivotMatrix(): Matrix {
  272. return this._pivotMatrix;
  273. }
  274. public _isSynchronized(): boolean {
  275. if (this._isDirty) {
  276. return false;
  277. }
  278. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  279. return false;
  280. if (this._cache.pivotMatrixUpdated) {
  281. return false;
  282. }
  283. if (this.infiniteDistance) {
  284. return false;
  285. }
  286. if (!this._cache.position.equals(this.position))
  287. return false;
  288. if (this.rotationQuaternion) {
  289. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  290. return false;
  291. } else {
  292. if (!this._cache.rotation.equals(this.rotation))
  293. return false;
  294. }
  295. if (!this._cache.scaling.equals(this.scaling))
  296. return false;
  297. return true;
  298. }
  299. public _initCache() {
  300. super._initCache();
  301. this._cache.localMatrixUpdated = false;
  302. this._cache.position = Vector3.Zero();
  303. this._cache.scaling = Vector3.Zero();
  304. this._cache.rotation = Vector3.Zero();
  305. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  306. }
  307. public markAsDirty(property: string): void {
  308. if (property === "rotation") {
  309. this.rotationQuaternion = null;
  310. }
  311. this._currentRenderId = Number.MAX_VALUE;
  312. this._isDirty = true;
  313. }
  314. public _updateBoundingInfo(): void {
  315. this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
  316. this._boundingInfo._update(this.worldMatrixFromCache);
  317. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  318. }
  319. public _updateSubMeshesBoundingInfo(matrix: Matrix): void {
  320. if (!this.subMeshes) {
  321. return;
  322. }
  323. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  324. var subMesh = this.subMeshes[subIndex];
  325. subMesh.updateBoundingInfo(matrix);
  326. }
  327. }
  328. public computeWorldMatrix(force?: boolean): Matrix {
  329. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  330. return this._worldMatrix;
  331. }
  332. this._cache.position.copyFrom(this.position);
  333. this._cache.scaling.copyFrom(this.scaling);
  334. this._cache.pivotMatrixUpdated = false;
  335. this._currentRenderId = this.getScene().getRenderId();
  336. this._isDirty = false;
  337. // Scaling
  338. Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  339. // Rotation
  340. if (this.rotationQuaternion) {
  341. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  342. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  343. } else {
  344. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  345. this._cache.rotation.copyFrom(this.rotation);
  346. }
  347. // Translation
  348. if (this.infiniteDistance && !this.parent) {
  349. var camera = this.getScene().activeCamera;
  350. var cameraWorldMatrix = camera.getWorldMatrix();
  351. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  352. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  353. this.position.z + cameraGlobalPosition.z, this._localTranslation);
  354. } else {
  355. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  356. }
  357. // Composing transformations
  358. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  359. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  360. // Billboarding
  361. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  362. var localPosition = this.position.clone();
  363. var zero = this.getScene().activeCamera.position.clone();
  364. if (this.parent && (<any>this.parent).position) {
  365. localPosition.addInPlace((<any>this.parent).position);
  366. Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  367. }
  368. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  369. zero = this.getScene().activeCamera.position;
  370. } else {
  371. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  372. zero.x = localPosition.x + Engine.Epsilon;
  373. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  374. zero.y = localPosition.y + 0.001;
  375. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  376. zero.z = localPosition.z + 0.001;
  377. }
  378. Matrix.LookAtLHToRef(localPosition, zero, Vector3.Up(), this._localBillboard);
  379. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  380. this._localBillboard.invert();
  381. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  382. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  383. }
  384. // Local world
  385. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  386. // Parent
  387. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  388. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  389. } else {
  390. this._worldMatrix.copyFrom(this._localWorld);
  391. }
  392. // Bounding info
  393. this._updateBoundingInfo();
  394. // Absolute position
  395. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  396. // Callbacks
  397. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  398. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  399. }
  400. return this._worldMatrix;
  401. }
  402. /**
  403. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  404. * @param func: callback function to add
  405. */
  406. public registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void {
  407. this._onAfterWorldMatrixUpdate.push(func);
  408. }
  409. public unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void {
  410. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  411. if (index > -1) {
  412. this._onAfterWorldMatrixUpdate.splice(index, 1);
  413. }
  414. }
  415. public setPositionWithLocalVector(vector3: Vector3): void {
  416. this.computeWorldMatrix();
  417. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  418. }
  419. public getPositionExpressedInLocalSpace(): Vector3 {
  420. this.computeWorldMatrix();
  421. var invLocalWorldMatrix = this._localWorld.clone();
  422. invLocalWorldMatrix.invert();
  423. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  424. }
  425. public locallyTranslate(vector3: Vector3): void {
  426. this.computeWorldMatrix();
  427. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  428. }
  429. public lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void {
  430. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  431. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  432. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  433. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  434. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  435. /// <returns>Mesh oriented towards targetMesh</returns>
  436. yawCor = yawCor || 0; // default to zero if undefined
  437. pitchCor = pitchCor || 0;
  438. rollCor = rollCor || 0;
  439. var dv = targetPoint.subtract(this.position);
  440. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  441. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  442. var pitch = Math.atan2(dv.y, len);
  443. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  444. }
  445. public isInFrustum(frustumPlanes: Plane[]): boolean {
  446. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  447. return false;
  448. }
  449. return true;
  450. }
  451. public isCompletelyInFrustum(camera?: Camera): boolean {
  452. if (!camera) {
  453. camera = this.getScene().activeCamera;
  454. }
  455. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  456. if (!this._boundingInfo.isCompletelyInFrustum(Frustum.GetPlanes(transformMatrix))) {
  457. return false;
  458. }
  459. return true;
  460. }
  461. public intersectsMesh(mesh: AbstractMesh, precise?: boolean): boolean {
  462. if (!this._boundingInfo || !mesh._boundingInfo) {
  463. return false;
  464. }
  465. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  466. }
  467. public intersectsPoint(point: Vector3): boolean {
  468. if (!this._boundingInfo) {
  469. return false;
  470. }
  471. return this._boundingInfo.intersectsPoint(point);
  472. }
  473. // Physics
  474. public setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): any {
  475. var physicsEngine = this.getScene().getPhysicsEngine();
  476. if (!physicsEngine) {
  477. return;
  478. }
  479. impostor = impostor || PhysicsEngine.NoImpostor;
  480. if (impostor.impostor) {
  481. // Old API
  482. options = impostor;
  483. impostor = impostor.impostor;
  484. }
  485. if (impostor === PhysicsEngine.NoImpostor) {
  486. physicsEngine._unregisterMesh(this);
  487. return;
  488. }
  489. if (!options) {
  490. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  491. } else {
  492. if (!options.mass && options.mass !== 0) options.mass = 0;
  493. if (!options.friction && options.friction !== 0) options.friction = 0.2;
  494. if (!options.restitution && options.restitution !== 0) options.restitution = 0.2;
  495. }
  496. this._physicImpostor = impostor;
  497. this._physicsMass = options.mass;
  498. this._physicsFriction = options.friction;
  499. this._physicRestitution = options.restitution;
  500. return physicsEngine._registerMesh(this, impostor, options);
  501. }
  502. public getPhysicsImpostor(): number {
  503. if (!this._physicImpostor) {
  504. return PhysicsEngine.NoImpostor;
  505. }
  506. return this._physicImpostor;
  507. }
  508. public getPhysicsMass(): number {
  509. if (!this._physicsMass) {
  510. return 0;
  511. }
  512. return this._physicsMass;
  513. }
  514. public getPhysicsFriction(): number {
  515. if (!this._physicsFriction) {
  516. return 0;
  517. }
  518. return this._physicsFriction;
  519. }
  520. public getPhysicsRestitution(): number {
  521. if (!this._physicRestitution) {
  522. return 0;
  523. }
  524. return this._physicRestitution;
  525. }
  526. public getPositionInCameraSpace(camera?: Camera): Vector3 {
  527. if (!camera) {
  528. camera = this.getScene().activeCamera;
  529. }
  530. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  531. }
  532. public getDistanceToCamera(camera?: Camera): number {
  533. if (!camera) {
  534. camera = this.getScene().activeCamera;
  535. }
  536. return this.absolutePosition.subtract(camera.position).length();
  537. }
  538. public applyImpulse(force: Vector3, contactPoint: Vector3): void {
  539. if (!this._physicImpostor) {
  540. return;
  541. }
  542. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  543. }
  544. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): void {
  545. if (!this._physicImpostor) {
  546. return;
  547. }
  548. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  549. }
  550. public updatePhysicsBodyPosition(): void {
  551. if (!this._physicImpostor) {
  552. return;
  553. }
  554. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  555. }
  556. // Collisions
  557. public moveWithCollisions(velocity: Vector3): void {
  558. var globalPosition = this.getAbsolutePosition();
  559. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  560. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  561. this._collider.radius = this.ellipsoid;
  562. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  563. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  564. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  565. this.position.addInPlace(this._diffPositionForCollisions);
  566. }
  567. }
  568. // Submeshes octree
  569. /**
  570. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  571. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  572. */
  573. public createOrUpdateSubmeshesOctree(maxCapacity = 64, maxDepth = 2): Octree<SubMesh> {
  574. if (!this._submeshesOctree) {
  575. this._submeshesOctree = new Octree<SubMesh>(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  576. }
  577. this.computeWorldMatrix(true);
  578. // Update octree
  579. var bbox = this.getBoundingInfo().boundingBox;
  580. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  581. return this._submeshesOctree;
  582. }
  583. // Collisions
  584. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void {
  585. this._generatePointsArray();
  586. // Transformation
  587. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  588. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  589. subMesh._lastColliderWorldVertices = [];
  590. subMesh._trianglePlanes = [];
  591. var start = subMesh.verticesStart;
  592. var end = (subMesh.verticesStart + subMesh.verticesCount);
  593. for (var i = start; i < end; i++) {
  594. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  595. }
  596. }
  597. // Collide
  598. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  599. }
  600. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): void {
  601. var subMeshes: SubMesh[];
  602. var len: number;
  603. // Octrees
  604. if (this._submeshesOctree && this.useOctreeForCollisions) {
  605. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  606. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  607. len = intersections.length;
  608. subMeshes = intersections.data;
  609. } else {
  610. subMeshes = this.subMeshes;
  611. len = subMeshes.length;
  612. }
  613. for (var index = 0; index < len; index++) {
  614. var subMesh = subMeshes[index];
  615. // Bounding test
  616. if (len > 1 && !subMesh._checkCollision(collider))
  617. continue;
  618. this._collideForSubMesh(subMesh, transformMatrix, collider);
  619. }
  620. }
  621. public _checkCollision(collider: Collider): void {
  622. // Bounding box test
  623. if (!this._boundingInfo._checkCollision(collider))
  624. return;
  625. // Transformation matrix
  626. Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  627. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  628. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  629. }
  630. // Picking
  631. public _generatePointsArray(): boolean {
  632. return false;
  633. }
  634. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  635. var pickingInfo = new PickingInfo();
  636. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  637. return pickingInfo;
  638. }
  639. if (!this._generatePointsArray()) {
  640. return pickingInfo;
  641. }
  642. var intersectInfo: IntersectionInfo = null;
  643. // Octrees
  644. var subMeshes: SubMesh[];
  645. var len: number;
  646. if (this._submeshesOctree && this.useOctreeForPicking) {
  647. var worldRay = Ray.Transform(ray, this.getWorldMatrix());
  648. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  649. len = intersections.length;
  650. subMeshes = intersections.data;
  651. } else {
  652. subMeshes = this.subMeshes;
  653. len = subMeshes.length;
  654. }
  655. for (var index = 0; index < len; index++) {
  656. var subMesh = subMeshes[index];
  657. // Bounding test
  658. if (len > 1 && !subMesh.canIntersects(ray))
  659. continue;
  660. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  661. if (currentIntersectInfo) {
  662. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  663. intersectInfo = currentIntersectInfo;
  664. intersectInfo.subMeshId = index;
  665. if (fastCheck) {
  666. break;
  667. }
  668. }
  669. }
  670. }
  671. if (intersectInfo) {
  672. // Get picked point
  673. var world = this.getWorldMatrix();
  674. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  675. var direction = ray.direction.clone();
  676. direction = direction.scale(intersectInfo.distance);
  677. var worldDirection = Vector3.TransformNormal(direction, world);
  678. var pickedPoint = worldOrigin.add(worldDirection);
  679. // Return result
  680. pickingInfo.hit = true;
  681. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  682. pickingInfo.pickedPoint = pickedPoint;
  683. pickingInfo.pickedMesh = this;
  684. pickingInfo.bu = intersectInfo.bu;
  685. pickingInfo.bv = intersectInfo.bv;
  686. pickingInfo.faceId = intersectInfo.faceId;
  687. pickingInfo.subMeshId = intersectInfo.subMeshId;
  688. return pickingInfo;
  689. }
  690. return pickingInfo;
  691. }
  692. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh {
  693. return null;
  694. }
  695. public releaseSubMeshes(): void {
  696. if (this.subMeshes) {
  697. while (this.subMeshes.length) {
  698. this.subMeshes[0].dispose();
  699. }
  700. } else {
  701. this.subMeshes = new Array<SubMesh>();
  702. }
  703. }
  704. public dispose(doNotRecurse?: boolean): void {
  705. var index: number;
  706. // Physics
  707. if (this.getPhysicsImpostor() !== PhysicsEngine.NoImpostor) {
  708. this.setPhysicsState(PhysicsEngine.NoImpostor);
  709. }
  710. // Intersections in progress
  711. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  712. var other = this._intersectionsInProgress[index];
  713. var pos = other._intersectionsInProgress.indexOf(this);
  714. other._intersectionsInProgress.splice(pos, 1);
  715. }
  716. this._intersectionsInProgress = [];
  717. // SubMeshes
  718. this.releaseSubMeshes();
  719. // Remove from scene
  720. this.getScene().removeMesh(this);
  721. if (!doNotRecurse) {
  722. // Particles
  723. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  724. if (this.getScene().particleSystems[index].emitter === this) {
  725. this.getScene().particleSystems[index].dispose();
  726. index--;
  727. }
  728. }
  729. // Children
  730. var objects = this.getScene().meshes.slice(0);
  731. for (index = 0; index < objects.length; index++) {
  732. if (objects[index].parent === this) {
  733. objects[index].dispose();
  734. }
  735. }
  736. } else {
  737. for (index = 0; index < this.getScene().meshes.length; index++) {
  738. var obj = this.getScene().meshes[index];
  739. if (obj.parent === this) {
  740. obj.parent = null;
  741. obj.computeWorldMatrix(true);
  742. }
  743. }
  744. }
  745. this._onAfterWorldMatrixUpdate = [];
  746. this._isDisposed = true;
  747. // Callback
  748. if (this.onDispose) {
  749. this.onDispose();
  750. }
  751. }
  752. }
  753. }