babylon.abstractMesh.ts 36 KB

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