babylon.abstractMesh.ts 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. module BABYLON {
  2. export class AbstractMesh extends Node implements IDisposable, ICullable {
  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. // facetData private properties
  25. private _facetPositions: Vector3[]; // facet local positions
  26. private _facetNormals: Vector3[]; // facet local normals
  27. private _facetPartitioning: number[][]; // partitioning array of facet index arrays
  28. private _facetNb: number = 0; // facet number
  29. private _partitioningSubdivisions: number = 10; // number of subdivisions per axis in the partioning space
  30. private _partitioningBBoxRatio: number = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  31. private _facetDataEnabled: boolean = false; // is the facet data feature enabled on this mesh ?
  32. private _facetParameters: any = {}; // keep a reference to the object parameters to avoid memory re-allocation
  33. private _bbSize: Vector3 = Vector3.Zero(); // bbox size approximated for facet data
  34. private _subDiv = { // actual number of subdivisions per axis for ComputeNormals()
  35. max: 1,
  36. X: 1,
  37. Y: 1,
  38. Z: 1
  39. };
  40. /**
  41. * Read-only : the number of facets in the mesh
  42. */
  43. public get facetNb(): number {
  44. return this._facetNb;
  45. }
  46. /**
  47. * The number of subdivisions per axis in the partioning space
  48. */
  49. public get partitioningSubdivisions(): number {
  50. return this._partitioningSubdivisions;
  51. }
  52. public set partitioningSubdivisions(nb: number) {
  53. this._partitioningSubdivisions = nb;
  54. }
  55. /**
  56. * The ratio to apply to the bouding box size to set to the partioning space.
  57. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  58. */
  59. public get partitioningBBoxRatio(): number {
  60. return this._partitioningBBoxRatio;
  61. }
  62. public set partitioningBBoxRatio(ratio: number) {
  63. this._partitioningBBoxRatio = ratio;
  64. }
  65. /**
  66. * Read-only : is the feature facetData enabled ?
  67. */
  68. public get isFacetDataEnabled(): boolean {
  69. return this._facetDataEnabled;
  70. }
  71. // Events
  72. /**
  73. * An event triggered when this mesh collides with another one
  74. * @type {BABYLON.Observable}
  75. */
  76. public onCollideObservable = new Observable<AbstractMesh>();
  77. private _onCollideObserver: Observer<AbstractMesh>;
  78. public set onCollide(callback: () => void) {
  79. if (this._onCollideObserver) {
  80. this.onCollideObservable.remove(this._onCollideObserver);
  81. }
  82. this._onCollideObserver = this.onCollideObservable.add(callback);
  83. }
  84. /**
  85. * An event triggered when the collision's position changes
  86. * @type {BABYLON.Observable}
  87. */
  88. public onCollisionPositionChangeObservable = new Observable<Vector3>();
  89. private _onCollisionPositionChangeObserver: Observer<Vector3>;
  90. public set onCollisionPositionChange(callback: () => void) {
  91. if (this._onCollisionPositionChangeObserver) {
  92. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  93. }
  94. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  95. }
  96. /**
  97. * An event triggered after the world matrix is updated
  98. * @type {BABYLON.Observable}
  99. */
  100. public onAfterWorldMatrixUpdateObservable = new Observable<AbstractMesh>();
  101. // Properties
  102. public definedFacingForward = true; // orientation for POV movement & rotation
  103. public position = new Vector3(0, 0, 0);
  104. private _rotation = new Vector3(0, 0, 0);
  105. public _rotationQuaternion: Quaternion;
  106. private _scaling = new Vector3(1, 1, 1);
  107. public billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  108. public visibility = 1.0;
  109. public alphaIndex = Number.MAX_VALUE;
  110. public infiniteDistance = false;
  111. public isVisible = true;
  112. public isPickable = true;
  113. public showBoundingBox = false;
  114. public showSubMeshesBoundingBox = false;
  115. public isBlocker = false;
  116. public renderingGroupId = 0;
  117. public material: Material;
  118. public receiveShadows = false;
  119. public renderOutline = false;
  120. public outlineColor = Color3.Red();
  121. public outlineWidth = 0.02;
  122. public renderOverlay = false;
  123. public overlayColor = Color3.Red();
  124. public overlayAlpha = 0.5;
  125. public hasVertexAlpha = false;
  126. public useVertexColors = true;
  127. public applyFog = true;
  128. public computeBonesUsingShaders = true;
  129. public scalingDeterminant = 1;
  130. public numBoneInfluencers = 4;
  131. public useOctreeForRenderingSelection = true;
  132. public useOctreeForPicking = true;
  133. public useOctreeForCollisions = true;
  134. public layerMask: number = 0x0FFFFFFF;
  135. public alwaysSelectAsActiveMesh = false;
  136. /**
  137. * This scene's action manager
  138. * @type {BABYLON.ActionManager}
  139. */
  140. public actionManager: ActionManager;
  141. // Physics
  142. public physicsImpostor: BABYLON.PhysicsImpostor;
  143. //Deprecated, Legacy support
  144. public onPhysicsCollide: (collidedMesh: AbstractMesh, contact: any) => void;
  145. // Collisions
  146. private _checkCollisions = false;
  147. public ellipsoid = new Vector3(0.5, 1, 0.5);
  148. public ellipsoidOffset = new Vector3(0, 0, 0);
  149. private _collider = new Collider();
  150. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  151. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  152. private _newPositionForCollisions = new Vector3(0, 0, 0);
  153. // Attach to bone
  154. private _meshToBoneReferal: AbstractMesh;
  155. // Edges
  156. public edgesWidth = 1;
  157. public edgesColor = new Color4(1, 0, 0, 1);
  158. public _edgesRenderer: EdgesRenderer;
  159. // Cache
  160. private _localWorld = Matrix.Zero();
  161. public _worldMatrix = Matrix.Zero();
  162. private _rotateYByPI = Matrix.RotationY(Math.PI);
  163. private _absolutePosition = Vector3.Zero();
  164. private _collisionsTransformMatrix = Matrix.Zero();
  165. private _collisionsScalingMatrix = Matrix.Zero();
  166. public _positions: Vector3[];
  167. private _isDirty = false;
  168. public _masterMesh: AbstractMesh;
  169. public _materialDefines: MaterialDefines;
  170. public _boundingInfo: BoundingInfo;
  171. private _pivotMatrix = Matrix.Identity();
  172. public _isDisposed = false;
  173. public _renderId = 0;
  174. public subMeshes: SubMesh[];
  175. public _submeshesOctree: Octree<SubMesh>;
  176. public _intersectionsInProgress = new Array<AbstractMesh>();
  177. private _isWorldMatrixFrozen = false;
  178. public _unIndexed = false;
  179. public _poseMatrix: Matrix;
  180. // Loading properties
  181. public _waitingActions: any;
  182. public _waitingFreezeWorldMatrix: boolean;
  183. // Skeleton
  184. private _skeleton: Skeleton;
  185. public _bonesTransformMatrices: Float32Array;
  186. public set skeleton(value: Skeleton) {
  187. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  188. this._skeleton._unregisterMeshWithPoseMatrix(this);
  189. }
  190. if (value && value.needInitialSkinMatrix) {
  191. value._registerMeshWithPoseMatrix(this);
  192. }
  193. this._skeleton = value;
  194. if (!this._skeleton) {
  195. this._bonesTransformMatrices = null;
  196. }
  197. }
  198. public get skeleton(): Skeleton {
  199. return this._skeleton;
  200. }
  201. // Constructor
  202. constructor(name: string, scene: Scene) {
  203. super(name, scene);
  204. scene.addMesh(this);
  205. }
  206. public getClassName(): string {
  207. return "AbstractMesh";
  208. }
  209. /**
  210. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  211. */
  212. public toString(fullDetails?: boolean): string {
  213. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof InstancedMesh ? "YES" : "NO");
  214. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  215. if (this._skeleton) {
  216. ret += ", skeleton: " + this._skeleton.name;
  217. }
  218. if (fullDetails) {
  219. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  220. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  221. }
  222. return ret;
  223. }
  224. /**
  225. * Getting the rotation object.
  226. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  227. */
  228. public get rotation(): Vector3 {
  229. return this._rotation;
  230. }
  231. public set rotation(newRotation: Vector3) {
  232. this._rotation = newRotation;
  233. }
  234. public get scaling(): Vector3 {
  235. return this._scaling;
  236. }
  237. public set scaling(newScaling: Vector3) {
  238. this._scaling = newScaling;
  239. if (this.physicsImpostor) {
  240. this.physicsImpostor.forceUpdate();
  241. }
  242. }
  243. public get rotationQuaternion() {
  244. return this._rotationQuaternion;
  245. }
  246. public set rotationQuaternion(quaternion: Quaternion) {
  247. this._rotationQuaternion = quaternion;
  248. //reset the rotation vector.
  249. if (quaternion && this.rotation.length()) {
  250. this.rotation.copyFromFloats(0, 0, 0);
  251. }
  252. }
  253. // Methods
  254. public updatePoseMatrix(matrix: Matrix) {
  255. this._poseMatrix.copyFrom(matrix);
  256. }
  257. public getPoseMatrix(): Matrix {
  258. return this._poseMatrix;
  259. }
  260. public disableEdgesRendering(): void {
  261. if (this._edgesRenderer !== undefined) {
  262. this._edgesRenderer.dispose();
  263. this._edgesRenderer = undefined;
  264. }
  265. }
  266. public enableEdgesRendering(epsilon = 0.95, checkVerticesInsteadOfIndices = false) {
  267. this.disableEdgesRendering();
  268. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  269. }
  270. public get isBlocked(): boolean {
  271. return false;
  272. }
  273. public getLOD(camera: Camera): AbstractMesh {
  274. return this;
  275. }
  276. public getTotalVertices(): number {
  277. return 0;
  278. }
  279. public getIndices(): number[] | Int32Array {
  280. return null;
  281. }
  282. public getVerticesData(kind: string): number[] | Float32Array {
  283. return null;
  284. }
  285. public isVerticesDataPresent(kind: string): boolean {
  286. return false;
  287. }
  288. public getBoundingInfo(): BoundingInfo {
  289. if (this._masterMesh) {
  290. return this._masterMesh.getBoundingInfo();
  291. }
  292. if (!this._boundingInfo) {
  293. this._updateBoundingInfo();
  294. }
  295. return this._boundingInfo;
  296. }
  297. public setBoundingInfo(boundingInfo: BoundingInfo): void {
  298. this._boundingInfo = boundingInfo;
  299. }
  300. public get useBones(): boolean {
  301. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind);
  302. }
  303. public _preActivate(): void {
  304. }
  305. public _preActivateForIntermediateRendering(renderId: number): void {
  306. }
  307. public _activate(renderId: number): void {
  308. this._renderId = renderId;
  309. }
  310. public getWorldMatrix(): Matrix {
  311. if (this._masterMesh) {
  312. return this._masterMesh.getWorldMatrix();
  313. }
  314. if (this._currentRenderId !== this.getScene().getRenderId()) {
  315. this.computeWorldMatrix();
  316. }
  317. return this._worldMatrix;
  318. }
  319. public get worldMatrixFromCache(): Matrix {
  320. return this._worldMatrix;
  321. }
  322. public get absolutePosition(): Vector3 {
  323. return this._absolutePosition;
  324. }
  325. public freezeWorldMatrix() {
  326. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  327. this.computeWorldMatrix(true);
  328. this._isWorldMatrixFrozen = true;
  329. }
  330. public unfreezeWorldMatrix() {
  331. this._isWorldMatrixFrozen = false;
  332. this.computeWorldMatrix(true);
  333. }
  334. public get isWorldMatrixFrozen(): boolean {
  335. return this._isWorldMatrixFrozen;
  336. }
  337. private static _rotationAxisCache = new Quaternion();
  338. public rotate(axis: Vector3, amount: number, space?: Space): void {
  339. axis.normalize();
  340. if (!this.rotationQuaternion) {
  341. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  342. this.rotation = Vector3.Zero();
  343. }
  344. var rotationQuaternion: Quaternion;
  345. if (!space || (space as any) === Space.LOCAL) {
  346. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  347. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  348. }
  349. else {
  350. if (this.parent) {
  351. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  352. invertParentWorldMatrix.invert();
  353. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  354. }
  355. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  356. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  357. }
  358. }
  359. public translate(axis: Vector3, distance: number, space?: Space): void {
  360. var displacementVector = axis.scale(distance);
  361. if (!space || (space as any) === Space.LOCAL) {
  362. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  363. this.setPositionWithLocalVector(tempV3);
  364. }
  365. else {
  366. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  367. }
  368. }
  369. public getAbsolutePosition(): Vector3 {
  370. this.computeWorldMatrix();
  371. return this._absolutePosition;
  372. }
  373. public setAbsolutePosition(absolutePosition: Vector3): void {
  374. if (!absolutePosition) {
  375. return;
  376. }
  377. var absolutePositionX;
  378. var absolutePositionY;
  379. var absolutePositionZ;
  380. if (absolutePosition.x === undefined) {
  381. if (arguments.length < 3) {
  382. return;
  383. }
  384. absolutePositionX = arguments[0];
  385. absolutePositionY = arguments[1];
  386. absolutePositionZ = arguments[2];
  387. }
  388. else {
  389. absolutePositionX = absolutePosition.x;
  390. absolutePositionY = absolutePosition.y;
  391. absolutePositionZ = absolutePosition.z;
  392. }
  393. if (this.parent) {
  394. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  395. invertParentWorldMatrix.invert();
  396. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  397. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  398. } else {
  399. this.position.x = absolutePositionX;
  400. this.position.y = absolutePositionY;
  401. this.position.z = absolutePositionZ;
  402. }
  403. }
  404. // ================================== Point of View Movement =================================
  405. /**
  406. * Perform relative position change from the point of view of behind the front of the mesh.
  407. * This is performed taking into account the meshes current rotation, so you do not have to care.
  408. * Supports definition of mesh facing forward or backward.
  409. * @param {number} amountRight
  410. * @param {number} amountUp
  411. * @param {number} amountForward
  412. */
  413. public movePOV(amountRight: number, amountUp: number, amountForward: number): void {
  414. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  415. }
  416. /**
  417. * Calculate relative position change from the point of view of behind the front of the mesh.
  418. * This is performed taking into account the meshes current rotation, so you do not have to care.
  419. * Supports definition of mesh facing forward or backward.
  420. * @param {number} amountRight
  421. * @param {number} amountUp
  422. * @param {number} amountForward
  423. */
  424. public calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3 {
  425. var rotMatrix = new Matrix();
  426. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  427. rotQuaternion.toRotationMatrix(rotMatrix);
  428. var translationDelta = Vector3.Zero();
  429. var defForwardMult = this.definedFacingForward ? -1 : 1;
  430. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  431. return translationDelta;
  432. }
  433. // ================================== Point of View Rotation =================================
  434. /**
  435. * Perform relative rotation change from the point of view of behind the front of the mesh.
  436. * Supports definition of mesh facing forward or backward.
  437. * @param {number} flipBack
  438. * @param {number} twirlClockwise
  439. * @param {number} tiltRight
  440. */
  441. public rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): void {
  442. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  443. }
  444. /**
  445. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  446. * Supports definition of mesh facing forward or backward.
  447. * @param {number} flipBack
  448. * @param {number} twirlClockwise
  449. * @param {number} tiltRight
  450. */
  451. public calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3 {
  452. var defForwardMult = this.definedFacingForward ? 1 : -1;
  453. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  454. }
  455. public setPivotMatrix(matrix: Matrix): void {
  456. this._pivotMatrix = matrix;
  457. this._cache.pivotMatrixUpdated = true;
  458. }
  459. public getPivotMatrix(): Matrix {
  460. return this._pivotMatrix;
  461. }
  462. public _isSynchronized(): boolean {
  463. if (this._isDirty) {
  464. return false;
  465. }
  466. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  467. return false;
  468. if (this._cache.pivotMatrixUpdated) {
  469. return false;
  470. }
  471. if (this.infiniteDistance) {
  472. return false;
  473. }
  474. if (!this._cache.position.equals(this.position))
  475. return false;
  476. if (this.rotationQuaternion) {
  477. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  478. return false;
  479. }
  480. if (!this._cache.rotation.equals(this.rotation))
  481. return false;
  482. if (!this._cache.scaling.equals(this.scaling))
  483. return false;
  484. return true;
  485. }
  486. public _initCache() {
  487. super._initCache();
  488. this._cache.localMatrixUpdated = false;
  489. this._cache.position = Vector3.Zero();
  490. this._cache.scaling = Vector3.Zero();
  491. this._cache.rotation = Vector3.Zero();
  492. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  493. this._cache.billboardMode = -1;
  494. }
  495. public markAsDirty(property: string): void {
  496. if (property === "rotation") {
  497. this.rotationQuaternion = null;
  498. }
  499. this._currentRenderId = Number.MAX_VALUE;
  500. this._isDirty = true;
  501. }
  502. public _updateBoundingInfo(): void {
  503. this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
  504. this._boundingInfo.update(this.worldMatrixFromCache);
  505. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  506. }
  507. public _updateSubMeshesBoundingInfo(matrix: Matrix): void {
  508. if (!this.subMeshes) {
  509. return;
  510. }
  511. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  512. var subMesh = this.subMeshes[subIndex];
  513. if (!subMesh.IsGlobal) {
  514. subMesh.updateBoundingInfo(matrix);
  515. }
  516. }
  517. }
  518. public computeWorldMatrix(force?: boolean): Matrix {
  519. if (this._isWorldMatrixFrozen) {
  520. return this._worldMatrix;
  521. }
  522. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  523. this._currentRenderId = this.getScene().getRenderId();
  524. return this._worldMatrix;
  525. }
  526. this._cache.position.copyFrom(this.position);
  527. this._cache.scaling.copyFrom(this.scaling);
  528. this._cache.pivotMatrixUpdated = false;
  529. this._cache.billboardMode = this.billboardMode;
  530. this._currentRenderId = this.getScene().getRenderId();
  531. this._isDirty = false;
  532. // Scaling
  533. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  534. // Rotation
  535. //rotate, if quaternion is set and rotation was used
  536. if (this.rotationQuaternion) {
  537. var len = this.rotation.length();
  538. if (len) {
  539. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z))
  540. this.rotation.copyFromFloats(0, 0, 0);
  541. }
  542. }
  543. if (this.rotationQuaternion) {
  544. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  545. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  546. } else {
  547. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  548. this._cache.rotation.copyFrom(this.rotation);
  549. }
  550. // Translation
  551. if (this.infiniteDistance && !this.parent) {
  552. var camera = this.getScene().activeCamera;
  553. if (camera) {
  554. var cameraWorldMatrix = camera.getWorldMatrix();
  555. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  556. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  557. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  558. }
  559. } else {
  560. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  561. }
  562. // Composing transformations
  563. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  564. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  565. // Billboarding
  566. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  567. Tmp.Vector3[0].copyFrom(this.position);
  568. var localPosition = Tmp.Vector3[0];
  569. if (this.parent && this.parent.getWorldMatrix) {
  570. this._markSyncedWithParent();
  571. var parentMatrix: Matrix;
  572. if (this._meshToBoneReferal) {
  573. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  574. parentMatrix = Tmp.Matrix[6];
  575. } else {
  576. parentMatrix = this.parent.getWorldMatrix();
  577. }
  578. Vector3.TransformNormalToRef(localPosition, parentMatrix, Tmp.Vector3[1]);
  579. localPosition = Tmp.Vector3[1];
  580. }
  581. var zero = this.getScene().activeCamera.globalPosition.clone();
  582. if (this.parent && (<any>this.parent).position) {
  583. localPosition.addInPlace((<any>this.parent).position);
  584. Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, Tmp.Matrix[2]);
  585. }
  586. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  587. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  588. zero.x = localPosition.x + Epsilon;
  589. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  590. zero.y = localPosition.y + Epsilon;
  591. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  592. zero.z = localPosition.z + Epsilon;
  593. }
  594. Matrix.LookAtLHToRef(localPosition, zero, Vector3.Up(), Tmp.Matrix[3]);
  595. Tmp.Matrix[3].m[12] = Tmp.Matrix[3].m[13] = Tmp.Matrix[3].m[14] = 0;
  596. Tmp.Matrix[3].invert();
  597. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[3], this._localWorld);
  598. this._rotateYByPI.multiplyToRef(this._localWorld, Tmp.Matrix[5]);
  599. }
  600. // Local world
  601. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  602. // Parent
  603. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  604. this._markSyncedWithParent();
  605. if (this._meshToBoneReferal) {
  606. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  607. Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  608. } else {
  609. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  610. }
  611. } else {
  612. this._worldMatrix.copyFrom(this._localWorld);
  613. }
  614. // Bounding info
  615. this._updateBoundingInfo();
  616. // Absolute position
  617. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  618. // Callbacks
  619. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  620. if (!this._poseMatrix) {
  621. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  622. }
  623. return this._worldMatrix;
  624. }
  625. /**
  626. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  627. * @param func: callback function to add
  628. */
  629. public registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void {
  630. this.onAfterWorldMatrixUpdateObservable.add(func);
  631. }
  632. public unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void {
  633. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  634. }
  635. public setPositionWithLocalVector(vector3: Vector3): void {
  636. this.computeWorldMatrix();
  637. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  638. }
  639. public getPositionExpressedInLocalSpace(): Vector3 {
  640. this.computeWorldMatrix();
  641. var invLocalWorldMatrix = this._localWorld.clone();
  642. invLocalWorldMatrix.invert();
  643. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  644. }
  645. public locallyTranslate(vector3: Vector3): void {
  646. this.computeWorldMatrix(true);
  647. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  648. }
  649. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  650. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): void {
  651. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  652. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  653. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  654. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  655. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  656. /// <returns>Mesh oriented towards targetMesh</returns>
  657. var dv = AbstractMesh._lookAtVectorCache;
  658. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  659. targetPoint.subtractToRef(pos, dv);
  660. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  661. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  662. var pitch = Math.atan2(dv.y, len);
  663. this.rotationQuaternion = this.rotationQuaternion || new Quaternion();
  664. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  665. }
  666. public attachToBone(bone: Bone, affectedMesh: AbstractMesh): void {
  667. this._meshToBoneReferal = affectedMesh;
  668. this.parent = bone;
  669. if (bone.getWorldMatrix().determinant() < 0) {
  670. this.scalingDeterminant *= -1;
  671. }
  672. }
  673. public detachFromBone(): void {
  674. if (this.parent.getWorldMatrix().determinant() < 0) {
  675. this.scalingDeterminant *= -1;
  676. }
  677. this._meshToBoneReferal = null;
  678. this.parent = null;
  679. }
  680. public isInFrustum(frustumPlanes: Plane[]): boolean {
  681. return this._boundingInfo.isInFrustum(frustumPlanes);
  682. }
  683. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  684. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);;
  685. }
  686. public intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean): boolean {
  687. if (!this._boundingInfo || !mesh._boundingInfo) {
  688. return false;
  689. }
  690. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  691. }
  692. public intersectsPoint(point: Vector3): boolean {
  693. if (!this._boundingInfo) {
  694. return false;
  695. }
  696. return this._boundingInfo.intersectsPoint(point);
  697. }
  698. // Physics
  699. /**
  700. * @Deprecated. Use new PhysicsImpostor instead.
  701. * */
  702. public setPhysicsState(impostor?: any, options?: PhysicsImpostorParameters): any {
  703. //legacy support
  704. if (impostor.impostor) {
  705. options = impostor;
  706. impostor = impostor.impostor;
  707. }
  708. this.physicsImpostor = new PhysicsImpostor(this, impostor, options, this.getScene());
  709. return this.physicsImpostor.physicsBody;
  710. }
  711. public getPhysicsImpostor(): PhysicsImpostor {
  712. return this.physicsImpostor;
  713. }
  714. /**
  715. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  716. */
  717. public getPhysicsMass(): number {
  718. return this.physicsImpostor.getParam("mass")
  719. }
  720. /**
  721. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  722. */
  723. public getPhysicsFriction(): number {
  724. return this.physicsImpostor.getParam("friction")
  725. }
  726. /**
  727. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  728. */
  729. public getPhysicsRestitution(): number {
  730. return this.physicsImpostor.getParam("restitution")
  731. }
  732. public getPositionInCameraSpace(camera?: Camera): Vector3 {
  733. if (!camera) {
  734. camera = this.getScene().activeCamera;
  735. }
  736. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  737. }
  738. public getDistanceToCamera(camera?: Camera): number {
  739. if (!camera) {
  740. camera = this.getScene().activeCamera;
  741. }
  742. return this.absolutePosition.subtract(camera.position).length();
  743. }
  744. public applyImpulse(force: Vector3, contactPoint: Vector3): void {
  745. if (!this.physicsImpostor) {
  746. return;
  747. }
  748. this.physicsImpostor.applyImpulse(force, contactPoint);
  749. }
  750. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): void {
  751. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  752. return;
  753. }
  754. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {
  755. mainPivot: pivot1,
  756. connectedPivot: pivot2,
  757. nativeParams: options
  758. })
  759. }
  760. /**
  761. * @Deprecated
  762. */
  763. public updatePhysicsBodyPosition(): void {
  764. Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  765. this.updatePhysicsBody();
  766. }
  767. /**
  768. * @Deprecated
  769. * Calling this function is not needed anymore.
  770. * The physics engine takes care of transofmration automatically.
  771. */
  772. public updatePhysicsBody(): void {
  773. //Unneeded
  774. }
  775. // Collisions
  776. public get checkCollisions(): boolean {
  777. return this._checkCollisions;
  778. }
  779. public set checkCollisions(collisionEnabled: boolean) {
  780. this._checkCollisions = collisionEnabled;
  781. if (this.getScene().workerCollisions) {
  782. this.getScene().collisionCoordinator.onMeshUpdated(this);
  783. }
  784. }
  785. public moveWithCollisions(velocity: Vector3): void {
  786. var globalPosition = this.getAbsolutePosition();
  787. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  788. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  789. this._collider.radius = this.ellipsoid;
  790. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  791. }
  792. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
  793. //TODO move this to the collision coordinator!
  794. if (this.getScene().workerCollisions)
  795. newPosition.multiplyInPlace(this._collider.radius);
  796. newPosition.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  797. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  798. this.position.addInPlace(this._diffPositionForCollisions);
  799. }
  800. if (collidedMesh) {
  801. this.onCollideObservable.notifyObservers(collidedMesh);
  802. }
  803. this.onCollisionPositionChangeObservable.notifyObservers(this.position);
  804. }
  805. // Submeshes octree
  806. /**
  807. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  808. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  809. */
  810. public createOrUpdateSubmeshesOctree(maxCapacity = 64, maxDepth = 2): Octree<SubMesh> {
  811. if (!this._submeshesOctree) {
  812. this._submeshesOctree = new Octree<SubMesh>(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  813. }
  814. this.computeWorldMatrix(true);
  815. // Update octree
  816. var bbox = this.getBoundingInfo().boundingBox;
  817. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  818. return this._submeshesOctree;
  819. }
  820. // Collisions
  821. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void {
  822. this._generatePointsArray();
  823. // Transformation
  824. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  825. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  826. subMesh._lastColliderWorldVertices = [];
  827. subMesh._trianglePlanes = [];
  828. var start = subMesh.verticesStart;
  829. var end = (subMesh.verticesStart + subMesh.verticesCount);
  830. for (var i = start; i < end; i++) {
  831. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  832. }
  833. }
  834. // Collide
  835. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  836. if (collider.collisionFound) {
  837. collider.collidedMesh = this;
  838. }
  839. }
  840. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): void {
  841. var subMeshes: SubMesh[];
  842. var len: number;
  843. // Octrees
  844. if (this._submeshesOctree && this.useOctreeForCollisions) {
  845. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  846. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  847. len = intersections.length;
  848. subMeshes = intersections.data;
  849. } else {
  850. subMeshes = this.subMeshes;
  851. len = subMeshes.length;
  852. }
  853. for (var index = 0; index < len; index++) {
  854. var subMesh = subMeshes[index];
  855. // Bounding test
  856. if (len > 1 && !subMesh._checkCollision(collider))
  857. continue;
  858. this._collideForSubMesh(subMesh, transformMatrix, collider);
  859. }
  860. }
  861. public _checkCollision(collider: Collider): void {
  862. // Bounding box test
  863. if (!this._boundingInfo._checkCollision(collider))
  864. return;
  865. // Transformation matrix
  866. Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  867. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  868. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  869. }
  870. // Picking
  871. public _generatePointsArray(): boolean {
  872. return false;
  873. }
  874. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  875. var pickingInfo = new PickingInfo();
  876. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  877. return pickingInfo;
  878. }
  879. if (!this._generatePointsArray()) {
  880. return pickingInfo;
  881. }
  882. var intersectInfo: IntersectionInfo = null;
  883. // Octrees
  884. var subMeshes: SubMesh[];
  885. var len: number;
  886. if (this._submeshesOctree && this.useOctreeForPicking) {
  887. var worldRay = Ray.Transform(ray, this.getWorldMatrix());
  888. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  889. len = intersections.length;
  890. subMeshes = intersections.data;
  891. } else {
  892. subMeshes = this.subMeshes;
  893. len = subMeshes.length;
  894. }
  895. for (var index = 0; index < len; index++) {
  896. var subMesh = subMeshes[index];
  897. // Bounding test
  898. if (len > 1 && !subMesh.canIntersects(ray))
  899. continue;
  900. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  901. if (currentIntersectInfo) {
  902. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  903. intersectInfo = currentIntersectInfo;
  904. intersectInfo.subMeshId = index;
  905. if (fastCheck) {
  906. break;
  907. }
  908. }
  909. }
  910. }
  911. if (intersectInfo) {
  912. // Get picked point
  913. var world = this.getWorldMatrix();
  914. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  915. var direction = ray.direction.clone();
  916. direction = direction.scale(intersectInfo.distance);
  917. var worldDirection = Vector3.TransformNormal(direction, world);
  918. var pickedPoint = worldOrigin.add(worldDirection);
  919. // Return result
  920. pickingInfo.hit = true;
  921. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  922. pickingInfo.pickedPoint = pickedPoint;
  923. pickingInfo.pickedMesh = this;
  924. pickingInfo.bu = intersectInfo.bu;
  925. pickingInfo.bv = intersectInfo.bv;
  926. pickingInfo.faceId = intersectInfo.faceId;
  927. pickingInfo.subMeshId = intersectInfo.subMeshId;
  928. return pickingInfo;
  929. }
  930. return pickingInfo;
  931. }
  932. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh {
  933. return null;
  934. }
  935. public releaseSubMeshes(): void {
  936. if (this.subMeshes) {
  937. while (this.subMeshes.length) {
  938. this.subMeshes[0].dispose();
  939. }
  940. } else {
  941. this.subMeshes = new Array<SubMesh>();
  942. }
  943. }
  944. public dispose(doNotRecurse?: boolean): void {
  945. var index: number;
  946. // Action manager
  947. if (this.actionManager) {
  948. this.actionManager.dispose();
  949. this.actionManager = null;
  950. }
  951. // Skeleton
  952. this.skeleton = null;
  953. // Animations
  954. this.getScene().stopAnimation(this);
  955. // Physics
  956. if (this.physicsImpostor) {
  957. this.physicsImpostor.dispose(/*!doNotRecurse*/);
  958. }
  959. // Intersections in progress
  960. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  961. var other = this._intersectionsInProgress[index];
  962. var pos = other._intersectionsInProgress.indexOf(this);
  963. other._intersectionsInProgress.splice(pos, 1);
  964. }
  965. this._intersectionsInProgress = [];
  966. // Lights
  967. var lights = this.getScene().lights;
  968. lights.forEach((light: Light) => {
  969. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  970. if (meshIndex !== -1) {
  971. light.includedOnlyMeshes.splice(meshIndex, 1);
  972. }
  973. meshIndex = light.excludedMeshes.indexOf(this);
  974. if (meshIndex !== -1) {
  975. light.excludedMeshes.splice(meshIndex, 1);
  976. }
  977. // Shadow generators
  978. var generator = light.getShadowGenerator();
  979. if (generator) {
  980. meshIndex = generator.getShadowMap().renderList.indexOf(this);
  981. if (meshIndex !== -1) {
  982. generator.getShadowMap().renderList.splice(meshIndex, 1);
  983. }
  984. }
  985. });
  986. // Edges
  987. if (this._edgesRenderer) {
  988. this._edgesRenderer.dispose();
  989. this._edgesRenderer = null;
  990. }
  991. // SubMeshes
  992. if (this.getClassName() !== "InstancedMesh"){
  993. this.releaseSubMeshes();
  994. }
  995. // Engine
  996. this.getScene().getEngine().wipeCaches();
  997. // Remove from scene
  998. this.getScene().removeMesh(this);
  999. if (!doNotRecurse) {
  1000. // Particles
  1001. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1002. if (this.getScene().particleSystems[index].emitter === this) {
  1003. this.getScene().particleSystems[index].dispose();
  1004. index--;
  1005. }
  1006. }
  1007. // Children
  1008. var objects = this.getDescendants(true);
  1009. for (index = 0; index < objects.length; index++) {
  1010. objects[index].dispose();
  1011. }
  1012. } else {
  1013. var childMeshes = this.getChildMeshes(true);
  1014. for (index = 0; index < childMeshes.length; index++) {
  1015. var child = childMeshes[index];
  1016. child.parent = null;
  1017. child.computeWorldMatrix(true);
  1018. }
  1019. }
  1020. // facet data
  1021. if (this._facetDataEnabled) {
  1022. this.disableFacetData();
  1023. }
  1024. this.onAfterWorldMatrixUpdateObservable.clear();
  1025. this.onCollideObservable.clear();
  1026. this.onCollisionPositionChangeObservable.clear();
  1027. this._isDisposed = true;
  1028. super.dispose();
  1029. }
  1030. public getDirection(localAxis:Vector3): Vector3 {
  1031. var result = Vector3.Zero();
  1032. this.getDirectionToRef(localAxis, result);
  1033. return result;
  1034. }
  1035. public getDirectionToRef(localAxis:Vector3, result:Vector3): void {
  1036. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  1037. }
  1038. public setPivotPoint(point:Vector3, space:Space = Space.LOCAL): void{
  1039. if(this.getScene().getRenderId() == 0){
  1040. this.computeWorldMatrix(true);
  1041. }
  1042. var wm = this.getWorldMatrix();
  1043. if (space == Space.WORLD) {
  1044. var tmat = Tmp.Matrix[0];
  1045. wm.invertToRef(tmat);
  1046. point = Vector3.TransformCoordinates(point, tmat);
  1047. }
  1048. Vector3.TransformCoordinatesToRef(point, wm, this.position);
  1049. this._pivotMatrix.m[12] = -point.x;
  1050. this._pivotMatrix.m[13] = -point.y;
  1051. this._pivotMatrix.m[14] = -point.z;
  1052. this._cache.pivotMatrixUpdated = true;
  1053. }
  1054. public getPivotPoint(): Vector3 {
  1055. var point = Vector3.Zero();
  1056. this.getPivotPointToRef(point);
  1057. return point;
  1058. }
  1059. public getPivotPointToRef(result:Vector3): void{
  1060. result.x = -this._pivotMatrix.m[12];
  1061. result.y = -this._pivotMatrix.m[13];
  1062. result.z = -this._pivotMatrix.m[14];
  1063. }
  1064. public getAbsolutePivotPoint(): Vector3 {
  1065. var point = Vector3.Zero();
  1066. this.getAbsolutePivotPointToRef(point);
  1067. return point;
  1068. }
  1069. public setParent(mesh:AbstractMesh, keepWorldPositionRotation = false): void{
  1070. var child = this;
  1071. var parent = mesh;
  1072. if(mesh == null){
  1073. if(child.parent && keepWorldPositionRotation){
  1074. var rotation = Tmp.Quaternion[0];
  1075. var position = Tmp.Vector3[0];
  1076. var scale = Tmp.Vector3[1];
  1077. child.getWorldMatrix().decompose(scale, rotation, position);
  1078. if (child.rotationQuaternion) {
  1079. child.rotationQuaternion.copyFrom(rotation);
  1080. } else {
  1081. rotation.toEulerAnglesToRef(child.rotation);
  1082. }
  1083. child.position.x = position.x;
  1084. child.position.y = position.y;
  1085. child.position.z = position.z;
  1086. }
  1087. } else {
  1088. if(keepWorldPositionRotation){
  1089. var rotation = Tmp.Quaternion[0];
  1090. var position = Tmp.Vector3[0];
  1091. var scale = Tmp.Vector3[1];
  1092. var m1 = Tmp.Matrix[0];
  1093. var m2 = Tmp.Matrix[1];
  1094. parent.getWorldMatrix().decompose(scale, rotation, position);
  1095. rotation.toRotationMatrix(m1);
  1096. m2.setTranslation(position);
  1097. m2.multiplyToRef(m1, m1);
  1098. var invParentMatrix = Matrix.Invert(m1);
  1099. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1100. m.decompose(scale, rotation, position);
  1101. if (child.rotationQuaternion) {
  1102. child.rotationQuaternion.copyFrom(rotation);
  1103. } else {
  1104. rotation.toEulerAnglesToRef(child.rotation);
  1105. }
  1106. invParentMatrix = Matrix.Invert(parent.getWorldMatrix());
  1107. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1108. m.decompose(scale, rotation, position);
  1109. child.position.x = position.x;
  1110. child.position.y = position.y;
  1111. child.position.z = position.z;
  1112. }
  1113. }
  1114. child.parent = parent;
  1115. }
  1116. public addChild(mesh:AbstractMesh, keepWorldPositionRotation = false): void{
  1117. mesh.setParent(this, keepWorldPositionRotation);
  1118. }
  1119. public removeChild(mesh:AbstractMesh, keepWorldPositionRotation = false): void{
  1120. mesh.setParent(null, keepWorldPositionRotation);
  1121. }
  1122. public getAbsolutePivotPointToRef(result:Vector3): void{
  1123. result.x = this._pivotMatrix.m[12];
  1124. result.y = this._pivotMatrix.m[13];
  1125. result.z = this._pivotMatrix.m[14];
  1126. this.getPivotPointToRef(result);
  1127. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  1128. }
  1129. // Facet data
  1130. /**
  1131. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  1132. */
  1133. private _initFacetData(): AbstractMesh {
  1134. if (!this._facetNormals) {
  1135. this._facetNormals = new Array<Vector3>();
  1136. }
  1137. if (!this._facetPositions) {
  1138. this._facetPositions = new Array<Vector3>();
  1139. }
  1140. if (!this._facetPartitioning) {
  1141. this._facetPartitioning = new Array<number[]>();
  1142. }
  1143. this._facetNb = this.getIndices().length / 3;
  1144. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1145. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1146. for (var f = 0; f < this._facetNb; f++) {
  1147. this._facetNormals[f] = Vector3.Zero();
  1148. this._facetPositions[f] = Vector3.Zero();
  1149. }
  1150. this._facetDataEnabled = true;
  1151. return this;
  1152. }
  1153. /**
  1154. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1155. * This method can be called within the render loop.
  1156. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  1157. */
  1158. public updateFacetData(): AbstractMesh {
  1159. if (!this._facetDataEnabled) {
  1160. this._initFacetData();
  1161. }
  1162. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1163. var indices = this.getIndices();
  1164. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1165. var bInfo = this.getBoundingInfo();
  1166. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1167. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1168. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1169. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  1170. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  1171. this._subDiv.max = this._partitioningSubdivisions;
  1172. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1173. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  1174. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  1175. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  1176. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  1177. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  1178. // set the parameters for ComputeNormals()
  1179. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  1180. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  1181. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1182. this._facetParameters.bInfo = bInfo;
  1183. this._facetParameters.bbSize = this._bbSize;
  1184. this._facetParameters.subDiv = this._subDiv;
  1185. this._facetParameters.ratio = this.partitioningBBoxRatio;
  1186. VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  1187. return this;
  1188. }
  1189. /**
  1190. * Returns the facetLocalNormals array.
  1191. * The normals are expressed in the mesh local space.
  1192. */
  1193. public getFacetLocalNormals(): Vector3[] {
  1194. if (!this._facetNormals) {
  1195. this.updateFacetData();
  1196. }
  1197. return this._facetNormals;
  1198. }
  1199. /**
  1200. * Returns the facetLocalPositions array.
  1201. * The facet positions are expressed in the mesh local space.
  1202. */
  1203. public getFacetLocalPositions(): Vector3[] {
  1204. if (!this._facetPositions) {
  1205. this.updateFacetData();
  1206. }
  1207. return this._facetPositions;
  1208. }
  1209. /**
  1210. * Returns the facetLocalPartioning array
  1211. */
  1212. public getFacetLocalPartitioning(): number[][] {
  1213. if (!this._facetPartitioning) {
  1214. this.updateFacetData();
  1215. }
  1216. return this._facetPartitioning;
  1217. }
  1218. /**
  1219. * Returns the i-th facet position in the world system.
  1220. * This method allocates a new Vector3 per call.
  1221. */
  1222. public getFacetPosition(i: number): Vector3 {
  1223. var pos = Vector3.Zero();
  1224. this.getFacetPositionToRef(i, pos);
  1225. return pos;
  1226. }
  1227. /**
  1228. * Sets the reference Vector3 with the i-th facet position in the world system.
  1229. * Returns the mesh.
  1230. */
  1231. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1232. var localPos = (this.getFacetLocalPositions())[i];
  1233. var world = this.getWorldMatrix();
  1234. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1235. return this;
  1236. }
  1237. /**
  1238. * Returns the i-th facet normal in the world system.
  1239. * This method allocates a new Vector3 per call.
  1240. */
  1241. public getFacetNormal(i: number): Vector3 {
  1242. var norm = Vector3.Zero();
  1243. this.getFacetNormalToRef(i, norm);
  1244. return norm;
  1245. }
  1246. /**
  1247. * Sets the reference Vector3 with the i-th facet normal in the world system.
  1248. * Returns the mesh.
  1249. */
  1250. public getFacetNormalToRef(i: number, ref: Vector3) {
  1251. var localNorm = (this.getFacetLocalNormals())[i];
  1252. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1253. return this;
  1254. }
  1255. /**
  1256. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  1257. */
  1258. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): number[] {
  1259. var bInfo = this.getBoundingInfo();
  1260. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  1261. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  1262. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  1263. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  1264. return null;
  1265. }
  1266. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  1267. }
  1268. /**
  1269. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  1270. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  1271. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1272. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1273. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1274. */
  1275. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1276. var world = this.getWorldMatrix();
  1277. var invMat = Tmp.Matrix[5];
  1278. world.invertToRef(invMat);
  1279. var invVect = Tmp.Vector3[8];
  1280. var closest = null;
  1281. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1282. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1283. if (projected) {
  1284. // tranform the local computed projected vector to world coordinates
  1285. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1286. }
  1287. return closest;
  1288. }
  1289. /**
  1290. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  1291. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  1292. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1293. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1294. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1295. */
  1296. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1297. var closest = null;
  1298. var tmpx = 0.0;
  1299. var tmpy = 0.0;
  1300. var tmpz = 0.0;
  1301. var d = 0.0; // tmp dot facet normal * facet position
  1302. var t0 = 0.0;
  1303. var projx = 0.0;
  1304. var projy = 0.0;
  1305. var projz = 0.0;
  1306. // Get all the facets in the same partitioning block than (x, y, z)
  1307. var facetPositions = this.getFacetLocalPositions();
  1308. var facetNormals = this.getFacetLocalNormals();
  1309. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1310. if (!facetsInBlock) {
  1311. return null;
  1312. }
  1313. // Get the closest facet to (x, y, z)
  1314. var shortest = Number.MAX_VALUE; // init distance vars
  1315. var tmpDistance = shortest;
  1316. var fib; // current facet in the block
  1317. var norm; // current facet normal
  1318. var p0; // current facet barycenter position
  1319. // loop on all the facets in the current partitioning block
  1320. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1321. fib = facetsInBlock[idx];
  1322. norm = facetNormals[fib];
  1323. p0 = facetPositions[fib];
  1324. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1325. if ( !checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0) ) {
  1326. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1327. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1328. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1329. projx = x + norm.x * t0;
  1330. projy = y + norm.y * t0;
  1331. projz = z + norm.z * t0;
  1332. tmpx = projx - x;
  1333. tmpy = projy - y;
  1334. tmpz = projz - z;
  1335. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1336. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1337. shortest = tmpDistance;
  1338. closest = fib;
  1339. if (projected) {
  1340. projected.x = projx;
  1341. projected.y = projy;
  1342. projected.z = projz;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. return closest;
  1348. }
  1349. /**
  1350. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1351. */
  1352. public getFacetDataParameters(): any {
  1353. return this._facetParameters;
  1354. }
  1355. /**
  1356. * Disables the feature FacetData and frees the related memory.
  1357. * Returns the mesh.
  1358. */
  1359. public disableFacetData(): AbstractMesh {
  1360. if (this._facetDataEnabled) {
  1361. this._facetDataEnabled = false;
  1362. this._facetPositions = null;
  1363. this._facetNormals = null;
  1364. this._facetPartitioning = null;
  1365. this._facetParameters = null;
  1366. }
  1367. return this;
  1368. }
  1369. }
  1370. }