babylon.abstractMesh.ts 32 KB

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