babylon.abstractMesh.ts 29 KB

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