babylon.abstractMesh.ts 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220
  1. module BABYLON {
  2. export class AbstractMesh extends Node implements IDisposable, ICullable, IGetSetVerticesData {
  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 (integer) 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 (float) 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 boolean : 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 = Vector3.Zero();
  104. private _rotation = Vector3.Zero();
  105. private _rotationQuaternion: Quaternion;
  106. private _scaling = Vector3.One();
  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. private _material: Material
  118. public get material(): Material {
  119. return this._material;
  120. }
  121. public set material(value: Material) {
  122. if (this._material === value) {
  123. return;
  124. }
  125. this._material = value;
  126. if (!this.subMeshes) {
  127. return;
  128. }
  129. for (var subMesh of this.subMeshes) {
  130. subMesh.setEffect(null);
  131. }
  132. }
  133. private _receiveShadows = false;
  134. public get receiveShadows(): boolean {
  135. return this._receiveShadows;
  136. }
  137. public set receiveShadows(value: boolean) {
  138. if (this._receiveShadows === value) {
  139. return;
  140. }
  141. this._receiveShadows = value;
  142. this._markSubMeshesAsLightDirty();
  143. }
  144. public renderOutline = false;
  145. public outlineColor = Color3.Red();
  146. public outlineWidth = 0.02;
  147. public renderOverlay = false;
  148. public overlayColor = Color3.Red();
  149. public overlayAlpha = 0.5;
  150. private _hasVertexAlpha = false;
  151. public get hasVertexAlpha(): boolean {
  152. return this._hasVertexAlpha;
  153. }
  154. public set hasVertexAlpha(value: boolean) {
  155. if (this._hasVertexAlpha === value) {
  156. return;
  157. }
  158. this._hasVertexAlpha = value;
  159. this._markSubMeshesAsAttributesDirty();
  160. }
  161. private _useVertexColors = true;
  162. public get useVertexColors(): boolean {
  163. return this._useVertexColors;
  164. }
  165. public set useVertexColors(value: boolean) {
  166. if (this._useVertexColors === value) {
  167. return;
  168. }
  169. this._useVertexColors = value;
  170. this._markSubMeshesAsAttributesDirty();
  171. }
  172. private _computeBonesUsingShaders = true;
  173. public get computeBonesUsingShaders(): boolean {
  174. return this._computeBonesUsingShaders;
  175. }
  176. public set computeBonesUsingShaders(value: boolean) {
  177. if (this._computeBonesUsingShaders === value) {
  178. return;
  179. }
  180. this._computeBonesUsingShaders = value;
  181. this._markSubMeshesAsAttributesDirty();
  182. }
  183. private _numBoneInfluencers = 4;
  184. public get numBoneInfluencers(): number {
  185. return this._numBoneInfluencers;
  186. }
  187. public set numBoneInfluencers(value: number) {
  188. if (this._numBoneInfluencers === value) {
  189. return;
  190. }
  191. this._numBoneInfluencers = value;
  192. this._markSubMeshesAsAttributesDirty();
  193. }
  194. private _applyFog = true;
  195. public get applyFog(): boolean {
  196. return this._applyFog;
  197. }
  198. public set applyFog(value: boolean) {
  199. if (this._applyFog === value) {
  200. return;
  201. }
  202. this._applyFog = value;
  203. this._markSubMeshesAsMiscDirty();
  204. }
  205. public scalingDeterminant = 1;
  206. public useOctreeForRenderingSelection = true;
  207. public useOctreeForPicking = true;
  208. public useOctreeForCollisions = true;
  209. public layerMask: number = 0x0FFFFFFF;
  210. /**
  211. * True if the mesh must be rendered in any case.
  212. */
  213. public alwaysSelectAsActiveMesh = false;
  214. /**
  215. * This scene's action manager
  216. * @type {BABYLON.ActionManager}
  217. */
  218. public actionManager: ActionManager;
  219. // Physics
  220. public physicsImpostor: BABYLON.PhysicsImpostor;
  221. // Collisions
  222. private _checkCollisions = false;
  223. private _collisionMask = -1;
  224. private _collisionGroup = -1;
  225. public ellipsoid = new Vector3(0.5, 1, 0.5);
  226. public ellipsoidOffset = new Vector3(0, 0, 0);
  227. private _collider: Collider;
  228. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  229. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  230. private _newPositionForCollisions = new Vector3(0, 0, 0);
  231. public get collisionMask(): number {
  232. return this._collisionMask;
  233. }
  234. public set collisionMask(mask: number) {
  235. this._collisionMask = !isNaN(mask) ? mask : -1;
  236. }
  237. public get collisionGroup(): number {
  238. return this._collisionGroup;
  239. }
  240. public set collisionGroup(mask: number) {
  241. this._collisionGroup = !isNaN(mask) ? mask : -1;
  242. }
  243. // Attach to bone
  244. private _meshToBoneReferal: AbstractMesh;
  245. // Edges
  246. public edgesWidth = 1;
  247. public edgesColor = new Color4(1, 0, 0, 1);
  248. public _edgesRenderer: EdgesRenderer;
  249. // Cache
  250. private _localWorld = Matrix.Zero();
  251. public _worldMatrix = Matrix.Zero();
  252. private _absolutePosition = Vector3.Zero();
  253. private _collisionsTransformMatrix = Matrix.Zero();
  254. private _collisionsScalingMatrix = Matrix.Zero();
  255. private _isDirty = false;
  256. public _masterMesh: AbstractMesh;
  257. public _boundingInfo: BoundingInfo;
  258. private _pivotMatrix = Matrix.Identity();
  259. public _isDisposed = false;
  260. public _renderId = 0;
  261. public subMeshes: SubMesh[];
  262. public _submeshesOctree: Octree<SubMesh>;
  263. public _intersectionsInProgress = new Array<AbstractMesh>();
  264. private _isWorldMatrixFrozen = false;
  265. public _unIndexed = false;
  266. public _poseMatrix: Matrix;
  267. public _lightSources = new Array<Light>();
  268. public get _positions(): Vector3[] {
  269. return null;
  270. }
  271. // Loading properties
  272. public _waitingActions: any;
  273. public _waitingFreezeWorldMatrix: boolean;
  274. // Skeleton
  275. private _skeleton: Skeleton;
  276. public _bonesTransformMatrices: Float32Array;
  277. public set skeleton(value: Skeleton) {
  278. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  279. this._skeleton._unregisterMeshWithPoseMatrix(this);
  280. }
  281. if (value && value.needInitialSkinMatrix) {
  282. value._registerMeshWithPoseMatrix(this);
  283. }
  284. this._skeleton = value;
  285. if (!this._skeleton) {
  286. this._bonesTransformMatrices = null;
  287. }
  288. this._markSubMeshesAsAttributesDirty();
  289. }
  290. public get skeleton(): Skeleton {
  291. return this._skeleton;
  292. }
  293. // Constructor
  294. constructor(name: string, scene: Scene) {
  295. super(name, scene);
  296. this.getScene().addMesh(this);
  297. this._resyncLightSources();
  298. }
  299. /**
  300. * Returns the string "AbstractMesh"
  301. */
  302. public getClassName(): string {
  303. return "AbstractMesh";
  304. }
  305. /**
  306. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  307. */
  308. public toString(fullDetails?: boolean): string {
  309. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof InstancedMesh ? "YES" : "NO");
  310. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  311. if (this._skeleton) {
  312. ret += ", skeleton: " + this._skeleton.name;
  313. }
  314. if (fullDetails) {
  315. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  316. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  317. }
  318. return ret;
  319. }
  320. public _resyncLightSources(): void {
  321. this._lightSources.length = 0;
  322. for (var light of this.getScene().lights) {
  323. if (!light.isEnabled()) {
  324. continue;
  325. }
  326. if (light.canAffectMesh(this)) {
  327. this._lightSources.push(light);
  328. }
  329. }
  330. this._markSubMeshesAsLightDirty();
  331. }
  332. public _resyncLighSource(light: Light): void {
  333. var isIn = light.isEnabled() && light.canAffectMesh(this);
  334. var index = this._lightSources.indexOf(light);
  335. if (index === -1) {
  336. if (!isIn) {
  337. return;
  338. }
  339. this._lightSources.push(light);
  340. } else {
  341. if (isIn) {
  342. return;
  343. }
  344. this._lightSources.splice(index, 1);
  345. }
  346. this._markSubMeshesAsLightDirty();
  347. }
  348. public _removeLightSource(light: Light): void {
  349. var index = this._lightSources.indexOf(light);
  350. if (index === -1) {
  351. return;
  352. }
  353. this._lightSources.splice(index, 1);
  354. }
  355. private _markSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  356. if (!this.subMeshes) {
  357. return;
  358. }
  359. for (var subMesh of this.subMeshes) {
  360. if (subMesh._materialDefines) {
  361. func(subMesh._materialDefines);
  362. }
  363. }
  364. }
  365. public _markSubMeshesAsLightDirty() {
  366. this._markSubMeshesAsDirty(defines => defines.markAsLightDirty());
  367. }
  368. public _markSubMeshesAsAttributesDirty() {
  369. this._markSubMeshesAsDirty(defines => defines.markAsAttributesDirty());
  370. }
  371. public _markSubMeshesAsMiscDirty() {
  372. if (!this.subMeshes) {
  373. return;
  374. }
  375. for (var subMesh of this.subMeshes) {
  376. var material = subMesh.getMaterial();
  377. if (material) {
  378. material.markAsDirty(Material.MiscDirtyFlag);
  379. }
  380. }
  381. }
  382. /**
  383. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  384. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  385. * Default : (0.0, 0.0, 0.0)
  386. */
  387. public get rotation(): Vector3 {
  388. return this._rotation;
  389. }
  390. public set rotation(newRotation: Vector3) {
  391. this._rotation = newRotation;
  392. }
  393. /**
  394. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  395. * Default : (1.0, 1.0, 1.0)
  396. */
  397. public get scaling(): Vector3 {
  398. return this._scaling;
  399. }
  400. public set scaling(newScaling: Vector3) {
  401. this._scaling = newScaling;
  402. if (this.physicsImpostor) {
  403. this.physicsImpostor.forceUpdate();
  404. }
  405. }
  406. /**
  407. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  408. * It's null by default.
  409. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  410. */
  411. public get rotationQuaternion() {
  412. return this._rotationQuaternion;
  413. }
  414. public set rotationQuaternion(quaternion: Quaternion) {
  415. this._rotationQuaternion = quaternion;
  416. //reset the rotation vector.
  417. if (quaternion && this.rotation.length()) {
  418. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  419. }
  420. }
  421. // Methods
  422. /**
  423. * Copies the paramater passed Matrix into the mesh Pose matrix.
  424. * Returns the AbstractMesh.
  425. */
  426. public updatePoseMatrix(matrix: Matrix): AbstractMesh {
  427. this._poseMatrix.copyFrom(matrix);
  428. return this;
  429. }
  430. /**
  431. * Returns the mesh Pose matrix.
  432. * Returned object : Matrix
  433. */
  434. public getPoseMatrix(): Matrix {
  435. return this._poseMatrix;
  436. }
  437. /**
  438. * Disables the mesh edger rendering mode.
  439. * Returns the AbstractMesh.
  440. */
  441. public disableEdgesRendering(): AbstractMesh {
  442. if (this._edgesRenderer !== undefined) {
  443. this._edgesRenderer.dispose();
  444. this._edgesRenderer = undefined;
  445. }
  446. return this;
  447. }
  448. /**
  449. * Enables the edge rendering mode on the mesh.
  450. * This mode makes the mesh edges visible.
  451. * Returns the AbstractMesh.
  452. */
  453. public enableEdgesRendering(epsilon = 0.95, checkVerticesInsteadOfIndices = false): AbstractMesh {
  454. this.disableEdgesRendering();
  455. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  456. return this;
  457. }
  458. /**
  459. * Returns true if the mesh is blocked. Used by the class Mesh.
  460. * Returns the boolean `false` by default.
  461. */
  462. public get isBlocked(): boolean {
  463. return false;
  464. }
  465. /**
  466. * Returns the mesh itself by default, used by the class Mesh.
  467. * Returned type : AbstractMesh
  468. */
  469. public getLOD(camera: Camera): AbstractMesh {
  470. return this;
  471. }
  472. /**
  473. * Returns 0 by default, used by the class Mesh.
  474. * Returns an integer.
  475. */
  476. public getTotalVertices(): number {
  477. return 0;
  478. }
  479. /**
  480. * Returns null by default, used by the class Mesh.
  481. * Returned type : integer array
  482. */
  483. public getIndices(): IndicesArray {
  484. return null;
  485. }
  486. /**
  487. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  488. * Returned type : float array or Float32Array
  489. */
  490. public getVerticesData(kind: string): number[] | Float32Array {
  491. return null;
  492. }
  493. /**
  494. * Sets the vertex data of the mesh geometry for the requested `kind`.
  495. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  496. * The `data` are either a numeric array either a Float32Array.
  497. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  498. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  499. * Note that a new underlying VertexBuffer object is created each call.
  500. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  501. *
  502. * Possible `kind` values :
  503. * - BABYLON.VertexBuffer.PositionKind
  504. * - BABYLON.VertexBuffer.UVKind
  505. * - BABYLON.VertexBuffer.UV2Kind
  506. * - BABYLON.VertexBuffer.UV3Kind
  507. * - BABYLON.VertexBuffer.UV4Kind
  508. * - BABYLON.VertexBuffer.UV5Kind
  509. * - BABYLON.VertexBuffer.UV6Kind
  510. * - BABYLON.VertexBuffer.ColorKind
  511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  515. *
  516. * Returns the Mesh.
  517. */
  518. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): Mesh {
  519. return null;
  520. }
  521. /**
  522. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  523. * If the mesh has no geometry, it is simply returned as it is.
  524. * The `data` are either a numeric array either a Float32Array.
  525. * No new underlying VertexBuffer object is created.
  526. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  527. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  528. *
  529. * Possible `kind` values :
  530. * - BABYLON.VertexBuffer.PositionKind
  531. * - BABYLON.VertexBuffer.UVKind
  532. * - BABYLON.VertexBuffer.UV2Kind
  533. * - BABYLON.VertexBuffer.UV3Kind
  534. * - BABYLON.VertexBuffer.UV4Kind
  535. * - BABYLON.VertexBuffer.UV5Kind
  536. * - BABYLON.VertexBuffer.UV6Kind
  537. * - BABYLON.VertexBuffer.ColorKind
  538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  542. *
  543. * Returns the Mesh.
  544. */
  545. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  546. return null;
  547. }
  548. /**
  549. * Sets the mesh indices.
  550. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  551. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  552. * This method creates a new index buffer each call.
  553. * Returns the Mesh.
  554. */
  555. public setIndices(indices: IndicesArray, totalVertices?: number): Mesh {
  556. return null;
  557. }
  558. /** Returns false by default, used by the class Mesh.
  559. * Returns a boolean
  560. */
  561. public isVerticesDataPresent(kind: string): boolean {
  562. return false;
  563. }
  564. /**
  565. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  566. * Returns a BoundingInfo
  567. */
  568. public getBoundingInfo(): BoundingInfo {
  569. if (this._masterMesh) {
  570. return this._masterMesh.getBoundingInfo();
  571. }
  572. if (!this._boundingInfo) {
  573. this._updateBoundingInfo();
  574. }
  575. return this._boundingInfo;
  576. }
  577. /**
  578. * Sets a mesh new object BoundingInfo.
  579. * Returns the AbstractMesh.
  580. */
  581. public setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh {
  582. this._boundingInfo = boundingInfo;
  583. return this;
  584. }
  585. public get useBones(): boolean {
  586. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind);
  587. }
  588. public _preActivate(): void {
  589. }
  590. public _preActivateForIntermediateRendering(renderId: number): void {
  591. }
  592. public _activate(renderId: number): void {
  593. this._renderId = renderId;
  594. }
  595. /**
  596. * Returns the last update of the World matrix
  597. * Returns a Matrix.
  598. */
  599. public getWorldMatrix(): Matrix {
  600. if (this._masterMesh) {
  601. return this._masterMesh.getWorldMatrix();
  602. }
  603. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  604. this.computeWorldMatrix();
  605. }
  606. return this._worldMatrix;
  607. }
  608. /**
  609. * Returns directly the last state of the mesh World matrix.
  610. * A Matrix is returned.
  611. */
  612. public get worldMatrixFromCache(): Matrix {
  613. return this._worldMatrix;
  614. }
  615. /**
  616. * Returns the current mesh absolute position.
  617. * Retuns a Vector3.
  618. */
  619. public get absolutePosition(): Vector3 {
  620. return this._absolutePosition;
  621. }
  622. /**
  623. * Prevents the World matrix to be computed any longer.
  624. * Returns the AbstractMesh.
  625. */
  626. public freezeWorldMatrix(): AbstractMesh {
  627. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  628. this.computeWorldMatrix(true);
  629. this._isWorldMatrixFrozen = true;
  630. return this;
  631. }
  632. /**
  633. * Allows back the World matrix computation.
  634. * Returns the AbstractMesh.
  635. */
  636. public unfreezeWorldMatrix() {
  637. this._isWorldMatrixFrozen = false;
  638. this.computeWorldMatrix(true);
  639. return this;
  640. }
  641. /**
  642. * True if the World matrix has been frozen.
  643. * Returns a boolean.
  644. */
  645. public get isWorldMatrixFrozen(): boolean {
  646. return this._isWorldMatrixFrozen;
  647. }
  648. private static _rotationAxisCache = new Quaternion();
  649. /**
  650. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  651. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  652. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  653. * The passed axis is also normalized.
  654. * Returns the AbstractMesh.
  655. */
  656. public rotate(axis: Vector3, amount: number, space?: Space): AbstractMesh {
  657. axis.normalize();
  658. if (!this.rotationQuaternion) {
  659. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  660. this.rotation = Vector3.Zero();
  661. }
  662. var rotationQuaternion: Quaternion;
  663. if (!space || (space as any) === Space.LOCAL) {
  664. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  665. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  666. }
  667. else {
  668. if (this.parent) {
  669. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  670. invertParentWorldMatrix.invert();
  671. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  672. }
  673. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  674. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  675. }
  676. return this;
  677. }
  678. /**
  679. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  680. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  681. * The passed axis is also normalized.
  682. * Returns the AbstractMesh.
  683. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  684. */
  685. public rotateAround(point: Vector3, axis: Vector3, amount: number): AbstractMesh {
  686. axis.normalize();
  687. if (!this.rotationQuaternion) {
  688. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  689. this.rotation.copyFromFloats(0, 0, 0);
  690. }
  691. point.subtractToRef(this.position, Tmp.Vector3[0]);
  692. Matrix.TranslationToRef(Tmp.Vector3[0].x, Tmp.Vector3[0].y, Tmp.Vector3[0].z, Tmp.Matrix[0]);
  693. Tmp.Matrix[0].invertToRef(Tmp.Matrix[2]);
  694. Matrix.RotationAxisToRef(axis, amount, Tmp.Matrix[1]);
  695. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[2]);
  696. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[2]);
  697. Tmp.Matrix[2].decompose(Tmp.Vector3[0], Tmp.Quaternion[0], Tmp.Vector3[1]);
  698. this.position.addInPlace(Tmp.Vector3[1]);
  699. this.rotationQuaternion.multiplyInPlace(Tmp.Quaternion[0]);
  700. return this;
  701. }
  702. /**
  703. * Translates the mesh along the axis vector for the passed distance in the given space.
  704. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  705. * Returns the AbstractMesh.
  706. */
  707. public translate(axis: Vector3, distance: number, space?: Space): AbstractMesh {
  708. var displacementVector = axis.scale(distance);
  709. if (!space || (space as any) === Space.LOCAL) {
  710. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  711. this.setPositionWithLocalVector(tempV3);
  712. }
  713. else {
  714. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  715. }
  716. return this;
  717. }
  718. /**
  719. * Adds a rotation step to the mesh current rotation.
  720. * x, y, z are Euler angles expressed in radians.
  721. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  722. * This means this rotation is made in the mesh local space only.
  723. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  724. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  725. * ```javascript
  726. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  727. * ```
  728. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  729. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  730. * Returns the AbstractMesh.
  731. */
  732. public addRotation(x: number, y: number, z: number): AbstractMesh {
  733. var rotationQuaternion;
  734. if (this.rotationQuaternion) {
  735. rotationQuaternion = this.rotationQuaternion;
  736. }
  737. else {
  738. rotationQuaternion = Tmp.Quaternion[1];
  739. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  740. }
  741. var accumulation = BABYLON.Tmp.Quaternion[0];
  742. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  743. rotationQuaternion.multiplyInPlace(accumulation);
  744. if (!this.rotationQuaternion) {
  745. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  746. }
  747. return this;
  748. }
  749. /**
  750. * Retuns the mesh absolute position in the World.
  751. * Returns a Vector3.
  752. */
  753. public getAbsolutePosition(): Vector3 {
  754. this.computeWorldMatrix();
  755. return this._absolutePosition;
  756. }
  757. /**
  758. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  759. * Returns the AbstractMesh.
  760. */
  761. public setAbsolutePosition(absolutePosition: Vector3): AbstractMesh {
  762. if (!absolutePosition) {
  763. return;
  764. }
  765. var absolutePositionX;
  766. var absolutePositionY;
  767. var absolutePositionZ;
  768. if (absolutePosition.x === undefined) {
  769. if (arguments.length < 3) {
  770. return;
  771. }
  772. absolutePositionX = arguments[0];
  773. absolutePositionY = arguments[1];
  774. absolutePositionZ = arguments[2];
  775. }
  776. else {
  777. absolutePositionX = absolutePosition.x;
  778. absolutePositionY = absolutePosition.y;
  779. absolutePositionZ = absolutePosition.z;
  780. }
  781. if (this.parent) {
  782. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  783. invertParentWorldMatrix.invert();
  784. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  785. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  786. } else {
  787. this.position.x = absolutePositionX;
  788. this.position.y = absolutePositionY;
  789. this.position.z = absolutePositionZ;
  790. }
  791. return this;
  792. }
  793. // ================================== Point of View Movement =================================
  794. /**
  795. * Perform relative position change from the point of view of behind the front of the mesh.
  796. * This is performed taking into account the meshes current rotation, so you do not have to care.
  797. * Supports definition of mesh facing forward or backward.
  798. * @param {number} amountRight
  799. * @param {number} amountUp
  800. * @param {number} amountForward
  801. *
  802. * Returns the AbstractMesh.
  803. */
  804. public movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh {
  805. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  806. return this;
  807. }
  808. /**
  809. * Calculate relative position change from the point of view of behind the front of the mesh.
  810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  811. * Supports definition of mesh facing forward or backward.
  812. * @param {number} amountRight
  813. * @param {number} amountUp
  814. * @param {number} amountForward
  815. *
  816. * Returns a new Vector3.
  817. */
  818. public calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3 {
  819. var rotMatrix = new Matrix();
  820. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  821. rotQuaternion.toRotationMatrix(rotMatrix);
  822. var translationDelta = Vector3.Zero();
  823. var defForwardMult = this.definedFacingForward ? -1 : 1;
  824. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  825. return translationDelta;
  826. }
  827. // ================================== Point of View Rotation =================================
  828. /**
  829. * Perform relative rotation change from the point of view of behind the front of the mesh.
  830. * Supports definition of mesh facing forward or backward.
  831. * @param {number} flipBack
  832. * @param {number} twirlClockwise
  833. * @param {number} tiltRight
  834. *
  835. * Returns the AbstractMesh.
  836. */
  837. public rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh {
  838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  839. return this;
  840. }
  841. /**
  842. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  843. * Supports definition of mesh facing forward or backward.
  844. * @param {number} flipBack
  845. * @param {number} twirlClockwise
  846. * @param {number} tiltRight
  847. *
  848. * Returns a new Vector3.
  849. */
  850. public calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3 {
  851. var defForwardMult = this.definedFacingForward ? 1 : -1;
  852. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  853. }
  854. /**
  855. * Sets a new pivot matrix to the mesh.
  856. * Returns the AbstractMesh.
  857. */
  858. public setPivotMatrix(matrix: Matrix): AbstractMesh {
  859. this._pivotMatrix = matrix;
  860. this._cache.pivotMatrixUpdated = true;
  861. return this;
  862. }
  863. /**
  864. * Returns the mesh pivot matrix.
  865. * Default : Identity.
  866. * A Matrix is returned.
  867. */
  868. public getPivotMatrix(): Matrix {
  869. return this._pivotMatrix;
  870. }
  871. public _isSynchronized(): boolean {
  872. if (this._isDirty) {
  873. return false;
  874. }
  875. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  876. return false;
  877. if (this._cache.pivotMatrixUpdated) {
  878. return false;
  879. }
  880. if (this.infiniteDistance) {
  881. return false;
  882. }
  883. if (!this._cache.position.equals(this.position))
  884. return false;
  885. if (this.rotationQuaternion) {
  886. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  887. return false;
  888. }
  889. if (!this._cache.rotation.equals(this.rotation))
  890. return false;
  891. if (!this._cache.scaling.equals(this.scaling))
  892. return false;
  893. return true;
  894. }
  895. public _initCache() {
  896. super._initCache();
  897. this._cache.localMatrixUpdated = false;
  898. this._cache.position = Vector3.Zero();
  899. this._cache.scaling = Vector3.Zero();
  900. this._cache.rotation = Vector3.Zero();
  901. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  902. this._cache.billboardMode = -1;
  903. }
  904. public markAsDirty(property: string): AbstractMesh {
  905. if (property === "rotation") {
  906. this.rotationQuaternion = null;
  907. }
  908. this._currentRenderId = Number.MAX_VALUE;
  909. this._isDirty = true;
  910. return this;
  911. }
  912. /**
  913. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  914. * Returns the AbstractMesh.
  915. */
  916. public _updateBoundingInfo(): AbstractMesh {
  917. this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
  918. this._boundingInfo.update(this.worldMatrixFromCache);
  919. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  920. return this;
  921. }
  922. /**
  923. * Update a mesh's children BoundingInfo objects only.
  924. * Returns the AbstractMesh.
  925. */
  926. public _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh {
  927. if (!this.subMeshes) {
  928. return;
  929. }
  930. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  931. var subMesh = this.subMeshes[subIndex];
  932. if (!subMesh.IsGlobal) {
  933. subMesh.updateBoundingInfo(matrix);
  934. }
  935. }
  936. return this;
  937. }
  938. /**
  939. * Computes the mesh World matrix and returns it.
  940. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  941. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  942. * If the parameter `force`is set to `true`, the actual computation is done.
  943. * Returns the mesh World Matrix.
  944. */
  945. public computeWorldMatrix(force?: boolean): Matrix {
  946. if (this._isWorldMatrixFrozen) {
  947. return this._worldMatrix;
  948. }
  949. if (!force && this.isSynchronized(true)) {
  950. this._currentRenderId = this.getScene().getRenderId();
  951. return this._worldMatrix;
  952. }
  953. this._cache.position.copyFrom(this.position);
  954. this._cache.scaling.copyFrom(this.scaling);
  955. this._cache.pivotMatrixUpdated = false;
  956. this._cache.billboardMode = this.billboardMode;
  957. this._currentRenderId = this.getScene().getRenderId();
  958. this._isDirty = false;
  959. // Scaling
  960. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  961. // Rotation
  962. //rotate, if quaternion is set and rotation was used
  963. if (this.rotationQuaternion) {
  964. var len = this.rotation.length();
  965. if (len) {
  966. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z))
  967. this.rotation.copyFromFloats(0, 0, 0);
  968. }
  969. }
  970. if (this.rotationQuaternion) {
  971. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  972. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  973. } else {
  974. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  975. this._cache.rotation.copyFrom(this.rotation);
  976. }
  977. // Translation
  978. if (this.infiniteDistance && !this.parent) {
  979. var camera = this.getScene().activeCamera;
  980. if (camera) {
  981. var cameraWorldMatrix = camera.getWorldMatrix();
  982. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  983. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  984. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  985. }
  986. } else {
  987. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  988. }
  989. // Composing transformations
  990. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  991. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  992. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  993. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  994. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  995. // Need to decompose each rotation here
  996. var currentPosition = Tmp.Vector3[3];
  997. if (this.parent && this.parent.getWorldMatrix) {
  998. if (this._meshToBoneReferal) {
  999. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  1000. Vector3.TransformCoordinatesToRef(this.position, Tmp.Matrix[6], currentPosition);
  1001. } else {
  1002. Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  1003. }
  1004. } else {
  1005. currentPosition.copyFrom(this.position);
  1006. }
  1007. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  1008. var finalEuler = Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  1009. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X)
  1010. {
  1011. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  1012. }
  1013. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y)
  1014. {
  1015. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  1016. }
  1017. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z)
  1018. {
  1019. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  1020. }
  1021. Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, Tmp.Matrix[0]);
  1022. } else {
  1023. Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  1024. Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  1025. Tmp.Matrix[1].invertToRef(Tmp.Matrix[0]);
  1026. }
  1027. Tmp.Matrix[1].copyFrom(Tmp.Matrix[5]);
  1028. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  1029. }
  1030. // Local world
  1031. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  1032. // Parent
  1033. if (this.parent && this.parent.getWorldMatrix) {
  1034. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  1035. if (this._meshToBoneReferal) {
  1036. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  1037. Tmp.Matrix[5].copyFrom(Tmp.Matrix[6]);
  1038. } else {
  1039. Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  1040. }
  1041. this._localWorld.getTranslationToRef(Tmp.Vector3[5]);
  1042. Vector3.TransformCoordinatesToRef(Tmp.Vector3[5], Tmp.Matrix[5], Tmp.Vector3[5]);
  1043. this._worldMatrix.copyFrom(this._localWorld);
  1044. this._worldMatrix.setTranslation(Tmp.Vector3[5]);
  1045. } else {
  1046. if (this._meshToBoneReferal) {
  1047. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  1048. Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  1049. } else {
  1050. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  1051. }
  1052. }
  1053. this._markSyncedWithParent();
  1054. } else {
  1055. this._worldMatrix.copyFrom(this._localWorld);
  1056. }
  1057. // Bounding info
  1058. this._updateBoundingInfo();
  1059. // Absolute position
  1060. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  1061. // Callbacks
  1062. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  1063. if (!this._poseMatrix) {
  1064. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  1065. }
  1066. return this._worldMatrix;
  1067. }
  1068. /**
  1069. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  1070. * @param func: callback function to add
  1071. *
  1072. * Returns the AbstractMesh.
  1073. */
  1074. public registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): AbstractMesh {
  1075. this.onAfterWorldMatrixUpdateObservable.add(func);
  1076. return this;
  1077. }
  1078. /**
  1079. * Removes a registered callback function.
  1080. * Returns the AbstractMesh.
  1081. */
  1082. public unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): AbstractMesh {
  1083. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  1084. return this;
  1085. }
  1086. /**
  1087. * Sets the mesh position in its local space.
  1088. * Returns the AbstractMesh.
  1089. */
  1090. public setPositionWithLocalVector(vector3: Vector3): AbstractMesh {
  1091. this.computeWorldMatrix();
  1092. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  1093. return this;
  1094. }
  1095. /**
  1096. * Returns the mesh position in the local space from the current World matrix values.
  1097. * Returns a new Vector3.
  1098. */
  1099. public getPositionExpressedInLocalSpace(): Vector3 {
  1100. this.computeWorldMatrix();
  1101. var invLocalWorldMatrix = this._localWorld.clone();
  1102. invLocalWorldMatrix.invert();
  1103. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  1104. }
  1105. /**
  1106. * Translates the mesh along the passed Vector3 in its local space.
  1107. * Returns the AbstractMesh.
  1108. */
  1109. public locallyTranslate(vector3: Vector3): AbstractMesh {
  1110. this.computeWorldMatrix(true);
  1111. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  1112. return this;
  1113. }
  1114. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  1115. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): AbstractMesh {
  1116. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  1117. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  1118. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  1119. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  1120. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  1121. /// <returns>Mesh oriented towards targetMesh</returns>
  1122. var dv = AbstractMesh._lookAtVectorCache;
  1123. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  1124. targetPoint.subtractToRef(pos, dv);
  1125. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  1126. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  1127. var pitch = Math.atan2(dv.y, len);
  1128. this.rotationQuaternion = this.rotationQuaternion || new Quaternion();
  1129. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  1130. return this;
  1131. }
  1132. public attachToBone(bone: Bone, affectedMesh: AbstractMesh): AbstractMesh {
  1133. this._meshToBoneReferal = affectedMesh;
  1134. this.parent = bone;
  1135. if (bone.getWorldMatrix().determinant() < 0) {
  1136. this.scalingDeterminant *= -1;
  1137. }
  1138. return this;
  1139. }
  1140. public detachFromBone(): AbstractMesh {
  1141. if (this.parent.getWorldMatrix().determinant() < 0) {
  1142. this.scalingDeterminant *= -1;
  1143. }
  1144. this._meshToBoneReferal = null;
  1145. this.parent = null;
  1146. return this;
  1147. }
  1148. /**
  1149. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  1150. * A mesh is in the frustum if its bounding box intersects the frustum.
  1151. * Boolean returned.
  1152. */
  1153. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1154. return this._boundingInfo.isInFrustum(frustumPlanes);
  1155. }
  1156. /**
  1157. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  1158. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  1159. * Boolean returned.
  1160. */
  1161. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  1162. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);;
  1163. }
  1164. /**
  1165. * True if the mesh intersects another mesh or a SolidParticle object.
  1166. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  1167. * Returns a boolean.
  1168. */
  1169. public intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean): boolean {
  1170. if (!this._boundingInfo || !mesh._boundingInfo) {
  1171. return false;
  1172. }
  1173. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  1174. }
  1175. /**
  1176. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  1177. * Returns a boolean.
  1178. */
  1179. public intersectsPoint(point: Vector3): boolean {
  1180. if (!this._boundingInfo) {
  1181. return false;
  1182. }
  1183. return this._boundingInfo.intersectsPoint(point);
  1184. }
  1185. public getPhysicsImpostor(): PhysicsImpostor {
  1186. return this.physicsImpostor;
  1187. }
  1188. public getPositionInCameraSpace(camera?: Camera): Vector3 {
  1189. if (!camera) {
  1190. camera = this.getScene().activeCamera;
  1191. }
  1192. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  1193. }
  1194. /**
  1195. * Returns the distance from the mesh to the active camera.
  1196. * Returns a float.
  1197. */
  1198. public getDistanceToCamera(camera?: Camera): number {
  1199. if (!camera) {
  1200. camera = this.getScene().activeCamera;
  1201. }
  1202. return this.absolutePosition.subtract(camera.position).length();
  1203. }
  1204. public applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh {
  1205. if (!this.physicsImpostor) {
  1206. return;
  1207. }
  1208. this.physicsImpostor.applyImpulse(force, contactPoint);
  1209. return this;
  1210. }
  1211. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh {
  1212. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  1213. return;
  1214. }
  1215. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {
  1216. mainPivot: pivot1,
  1217. connectedPivot: pivot2,
  1218. nativeParams: options
  1219. });
  1220. return this;
  1221. }
  1222. // Collisions
  1223. /**
  1224. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  1225. * Default `false`.
  1226. */
  1227. public get checkCollisions(): boolean {
  1228. return this._checkCollisions;
  1229. }
  1230. public set checkCollisions(collisionEnabled: boolean) {
  1231. this._checkCollisions = collisionEnabled;
  1232. if (this.getScene().workerCollisions) {
  1233. this.getScene().collisionCoordinator.onMeshUpdated(this);
  1234. }
  1235. }
  1236. public moveWithCollisions(velocity: Vector3): AbstractMesh {
  1237. var globalPosition = this.getAbsolutePosition();
  1238. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  1239. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  1240. if (!this._collider) {
  1241. this._collider = new Collider();
  1242. }
  1243. this._collider.radius = this.ellipsoid;
  1244. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  1245. return this;
  1246. }
  1247. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
  1248. //TODO move this to the collision coordinator!
  1249. if (this.getScene().workerCollisions)
  1250. newPosition.multiplyInPlace(this._collider.radius);
  1251. newPosition.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  1252. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  1253. this.position.addInPlace(this._diffPositionForCollisions);
  1254. }
  1255. if (collidedMesh) {
  1256. this.onCollideObservable.notifyObservers(collidedMesh);
  1257. }
  1258. this.onCollisionPositionChangeObservable.notifyObservers(this.position);
  1259. }
  1260. // Submeshes octree
  1261. /**
  1262. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  1263. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  1264. * Returns an Octree of submeshes.
  1265. */
  1266. public createOrUpdateSubmeshesOctree(maxCapacity = 64, maxDepth = 2): Octree<SubMesh> {
  1267. if (!this._submeshesOctree) {
  1268. this._submeshesOctree = new Octree<SubMesh>(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  1269. }
  1270. this.computeWorldMatrix(true);
  1271. // Update octree
  1272. var bbox = this.getBoundingInfo().boundingBox;
  1273. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  1274. return this._submeshesOctree;
  1275. }
  1276. // Collisions
  1277. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh {
  1278. this._generatePointsArray();
  1279. // Transformation
  1280. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  1281. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  1282. subMesh._lastColliderWorldVertices = [];
  1283. subMesh._trianglePlanes = [];
  1284. var start = subMesh.verticesStart;
  1285. var end = (subMesh.verticesStart + subMesh.verticesCount);
  1286. for (var i = start; i < end; i++) {
  1287. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  1288. }
  1289. }
  1290. // Collide
  1291. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  1292. if (collider.collisionFound) {
  1293. collider.collidedMesh = this;
  1294. }
  1295. return this;
  1296. }
  1297. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh {
  1298. var subMeshes: SubMesh[];
  1299. var len: number;
  1300. // Octrees
  1301. if (this._submeshesOctree && this.useOctreeForCollisions) {
  1302. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  1303. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  1304. len = intersections.length;
  1305. subMeshes = intersections.data;
  1306. } else {
  1307. subMeshes = this.subMeshes;
  1308. len = subMeshes.length;
  1309. }
  1310. for (var index = 0; index < len; index++) {
  1311. var subMesh = subMeshes[index];
  1312. // Bounding test
  1313. if (len > 1 && !subMesh._checkCollision(collider))
  1314. continue;
  1315. this._collideForSubMesh(subMesh, transformMatrix, collider);
  1316. }
  1317. return this;
  1318. }
  1319. public _checkCollision(collider: Collider): AbstractMesh {
  1320. // Bounding box test
  1321. if (!this._boundingInfo._checkCollision(collider))
  1322. return this;
  1323. // Transformation matrix
  1324. Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  1325. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  1326. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  1327. return this;
  1328. }
  1329. // Picking
  1330. public _generatePointsArray(): boolean {
  1331. return false;
  1332. }
  1333. /**
  1334. * Checks if the passed Ray intersects with the mesh.
  1335. * Returns an object PickingInfo.
  1336. */
  1337. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  1338. var pickingInfo = new PickingInfo();
  1339. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  1340. return pickingInfo;
  1341. }
  1342. if (!this._generatePointsArray()) {
  1343. return pickingInfo;
  1344. }
  1345. var intersectInfo: IntersectionInfo = null;
  1346. // Octrees
  1347. var subMeshes: SubMesh[];
  1348. var len: number;
  1349. if (this._submeshesOctree && this.useOctreeForPicking) {
  1350. var worldRay = Ray.Transform(ray, this.getWorldMatrix());
  1351. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  1352. len = intersections.length;
  1353. subMeshes = intersections.data;
  1354. } else {
  1355. subMeshes = this.subMeshes;
  1356. len = subMeshes.length;
  1357. }
  1358. for (var index = 0; index < len; index++) {
  1359. var subMesh = subMeshes[index];
  1360. // Bounding test
  1361. if (len > 1 && !subMesh.canIntersects(ray))
  1362. continue;
  1363. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  1364. if (currentIntersectInfo) {
  1365. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  1366. intersectInfo = currentIntersectInfo;
  1367. intersectInfo.subMeshId = index;
  1368. if (fastCheck) {
  1369. break;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. if (intersectInfo) {
  1375. // Get picked point
  1376. var world = this.getWorldMatrix();
  1377. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  1378. var direction = ray.direction.clone();
  1379. direction = direction.scale(intersectInfo.distance);
  1380. var worldDirection = Vector3.TransformNormal(direction, world);
  1381. var pickedPoint = worldOrigin.add(worldDirection);
  1382. // Return result
  1383. pickingInfo.hit = true;
  1384. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  1385. pickingInfo.pickedPoint = pickedPoint;
  1386. pickingInfo.pickedMesh = this;
  1387. pickingInfo.bu = intersectInfo.bu;
  1388. pickingInfo.bv = intersectInfo.bv;
  1389. pickingInfo.faceId = intersectInfo.faceId;
  1390. pickingInfo.subMeshId = intersectInfo.subMeshId;
  1391. return pickingInfo;
  1392. }
  1393. return pickingInfo;
  1394. }
  1395. /**
  1396. * Clones the mesh, used by the class Mesh.
  1397. * Just returns `null` for an AbstractMesh.
  1398. */
  1399. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh {
  1400. return null;
  1401. }
  1402. /**
  1403. * Disposes all the mesh submeshes.
  1404. * Returns the AbstractMesh.
  1405. */
  1406. public releaseSubMeshes(): AbstractMesh {
  1407. if (this.subMeshes) {
  1408. while (this.subMeshes.length) {
  1409. this.subMeshes[0].dispose();
  1410. }
  1411. } else {
  1412. this.subMeshes = new Array<SubMesh>();
  1413. }
  1414. return this;
  1415. }
  1416. /**
  1417. * Disposes the AbstractMesh.
  1418. * Some internal references are kept for further use.
  1419. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  1420. * Returns nothing.
  1421. */
  1422. public dispose(doNotRecurse?: boolean): void {
  1423. var index: number;
  1424. // Action manager
  1425. if (this.actionManager) {
  1426. this.actionManager.dispose();
  1427. this.actionManager = null;
  1428. }
  1429. // Skeleton
  1430. this.skeleton = null;
  1431. // Animations
  1432. this.getScene().stopAnimation(this);
  1433. // Physics
  1434. if (this.physicsImpostor) {
  1435. this.physicsImpostor.dispose(/*!doNotRecurse*/);
  1436. }
  1437. // Intersections in progress
  1438. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  1439. var other = this._intersectionsInProgress[index];
  1440. var pos = other._intersectionsInProgress.indexOf(this);
  1441. other._intersectionsInProgress.splice(pos, 1);
  1442. }
  1443. this._intersectionsInProgress = [];
  1444. // Lights
  1445. var lights = this.getScene().lights;
  1446. lights.forEach((light: Light) => {
  1447. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  1448. if (meshIndex !== -1) {
  1449. light.includedOnlyMeshes.splice(meshIndex, 1);
  1450. }
  1451. meshIndex = light.excludedMeshes.indexOf(this);
  1452. if (meshIndex !== -1) {
  1453. light.excludedMeshes.splice(meshIndex, 1);
  1454. }
  1455. // Shadow generators
  1456. var generator = light.getShadowGenerator();
  1457. if (generator) {
  1458. var shadowMap = generator.getShadowMap();
  1459. meshIndex = shadowMap.renderList.indexOf(this);
  1460. if (meshIndex !== -1) {
  1461. shadowMap.renderList.splice(meshIndex, 1);
  1462. }
  1463. }
  1464. });
  1465. // Edges
  1466. if (this._edgesRenderer) {
  1467. this._edgesRenderer.dispose();
  1468. this._edgesRenderer = null;
  1469. }
  1470. // SubMeshes
  1471. if (this.getClassName() !== "InstancedMesh"){
  1472. this.releaseSubMeshes();
  1473. }
  1474. // Octree
  1475. var sceneOctree = this.getScene().selectionOctree;
  1476. if (sceneOctree) {
  1477. var index = sceneOctree.dynamicContent.indexOf(this);
  1478. if (index !== -1) {
  1479. sceneOctree.dynamicContent.splice(index, 1);
  1480. }
  1481. }
  1482. // Engine
  1483. this.getScene().getEngine().wipeCaches();
  1484. // Remove from scene
  1485. this.getScene().removeMesh(this);
  1486. if (!doNotRecurse) {
  1487. // Particles
  1488. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1489. if (this.getScene().particleSystems[index].emitter === this) {
  1490. this.getScene().particleSystems[index].dispose();
  1491. index--;
  1492. }
  1493. }
  1494. // Children
  1495. var objects = this.getDescendants(true);
  1496. for (index = 0; index < objects.length; index++) {
  1497. objects[index].dispose();
  1498. }
  1499. } else {
  1500. var childMeshes = this.getChildMeshes(true);
  1501. for (index = 0; index < childMeshes.length; index++) {
  1502. var child = childMeshes[index];
  1503. child.parent = null;
  1504. child.computeWorldMatrix(true);
  1505. }
  1506. }
  1507. // facet data
  1508. if (this._facetDataEnabled) {
  1509. this.disableFacetData();
  1510. }
  1511. this.onAfterWorldMatrixUpdateObservable.clear();
  1512. this.onCollideObservable.clear();
  1513. this.onCollisionPositionChangeObservable.clear();
  1514. this._isDisposed = true;
  1515. super.dispose();
  1516. }
  1517. /**
  1518. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  1519. * This Vector3 is expressed in the World space.
  1520. */
  1521. public getDirection(localAxis:Vector3): Vector3 {
  1522. var result = Vector3.Zero();
  1523. this.getDirectionToRef(localAxis, result);
  1524. return result;
  1525. }
  1526. /**
  1527. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  1528. * localAxis is expressed in the mesh local space.
  1529. * result is computed in the Wordl space from the mesh World matrix.
  1530. * Returns the AbstractMesh.
  1531. */
  1532. public getDirectionToRef(localAxis:Vector3, result:Vector3): AbstractMesh {
  1533. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  1534. return this;
  1535. }
  1536. public setPivotPoint(point:Vector3, space:Space = Space.LOCAL): AbstractMesh {
  1537. if(this.getScene().getRenderId() == 0){
  1538. this.computeWorldMatrix(true);
  1539. }
  1540. var wm = this.getWorldMatrix();
  1541. if (space == Space.WORLD) {
  1542. var tmat = Tmp.Matrix[0];
  1543. wm.invertToRef(tmat);
  1544. point = Vector3.TransformCoordinates(point, tmat);
  1545. }
  1546. Vector3.TransformCoordinatesToRef(point, wm, this.position);
  1547. this._pivotMatrix.m[12] = -point.x;
  1548. this._pivotMatrix.m[13] = -point.y;
  1549. this._pivotMatrix.m[14] = -point.z;
  1550. this._cache.pivotMatrixUpdated = true;
  1551. return this;
  1552. }
  1553. /**
  1554. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  1555. */
  1556. public getPivotPoint(): Vector3 {
  1557. var point = Vector3.Zero();
  1558. this.getPivotPointToRef(point);
  1559. return point;
  1560. }
  1561. /**
  1562. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  1563. * Returns the AbstractMesh.
  1564. */
  1565. public getPivotPointToRef(result:Vector3): AbstractMesh{
  1566. result.x = -this._pivotMatrix.m[12];
  1567. result.y = -this._pivotMatrix.m[13];
  1568. result.z = -this._pivotMatrix.m[14];
  1569. return this;
  1570. }
  1571. /**
  1572. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  1573. */
  1574. public getAbsolutePivotPoint(): Vector3 {
  1575. var point = Vector3.Zero();
  1576. this.getAbsolutePivotPointToRef(point);
  1577. return point;
  1578. }
  1579. /**
  1580. * Defines the passed mesh as the parent of the current mesh.
  1581. * Returns the AbstractMesh.
  1582. */
  1583. public setParent(mesh:AbstractMesh): AbstractMesh {
  1584. var child = this;
  1585. var parent = mesh;
  1586. if(mesh == null){
  1587. var rotation = Tmp.Quaternion[0];
  1588. var position = Tmp.Vector3[0];
  1589. var scale = Tmp.Vector3[1];
  1590. child.getWorldMatrix().decompose(scale, rotation, position);
  1591. if (child.rotationQuaternion) {
  1592. child.rotationQuaternion.copyFrom(rotation);
  1593. } else {
  1594. rotation.toEulerAnglesToRef(child.rotation);
  1595. }
  1596. child.position.x = position.x;
  1597. child.position.y = position.y;
  1598. child.position.z = position.z;
  1599. } else {
  1600. var rotation = Tmp.Quaternion[0];
  1601. var position = Tmp.Vector3[0];
  1602. var scale = Tmp.Vector3[1];
  1603. var m1 = Tmp.Matrix[0];
  1604. var m2 = Tmp.Matrix[1];
  1605. parent.getWorldMatrix().decompose(scale, rotation, position);
  1606. rotation.toRotationMatrix(m1);
  1607. m2.setTranslation(position);
  1608. m2.multiplyToRef(m1, m1);
  1609. var invParentMatrix = Matrix.Invert(m1);
  1610. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1611. m.decompose(scale, rotation, position);
  1612. if (child.rotationQuaternion) {
  1613. child.rotationQuaternion.copyFrom(rotation);
  1614. } else {
  1615. rotation.toEulerAnglesToRef(child.rotation);
  1616. }
  1617. invParentMatrix = Matrix.Invert(parent.getWorldMatrix());
  1618. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1619. m.decompose(scale, rotation, position);
  1620. child.position.x = position.x;
  1621. child.position.y = position.y;
  1622. child.position.z = position.z;
  1623. }
  1624. child.parent = parent;
  1625. return this;
  1626. }
  1627. /**
  1628. * Adds the passed mesh as a child to the current mesh.
  1629. * Returns the AbstractMesh.
  1630. */
  1631. public addChild(mesh:AbstractMesh): AbstractMesh {
  1632. mesh.setParent(this);
  1633. return this;
  1634. }
  1635. /**
  1636. * Removes the passed mesh from the current mesh children list.
  1637. * Returns the AbstractMesh.
  1638. */
  1639. public removeChild(mesh:AbstractMesh): AbstractMesh {
  1640. mesh.setParent(null);
  1641. return this;
  1642. }
  1643. /**
  1644. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  1645. * Returns the AbstractMesh.
  1646. */
  1647. public getAbsolutePivotPointToRef(result:Vector3): AbstractMesh {
  1648. result.x = this._pivotMatrix.m[12];
  1649. result.y = this._pivotMatrix.m[13];
  1650. result.z = this._pivotMatrix.m[14];
  1651. this.getPivotPointToRef(result);
  1652. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  1653. return this;
  1654. }
  1655. // Facet data
  1656. /**
  1657. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  1658. * Returns the AbstractMesh.
  1659. */
  1660. private _initFacetData(): AbstractMesh {
  1661. if (!this._facetNormals) {
  1662. this._facetNormals = new Array<Vector3>();
  1663. }
  1664. if (!this._facetPositions) {
  1665. this._facetPositions = new Array<Vector3>();
  1666. }
  1667. if (!this._facetPartitioning) {
  1668. this._facetPartitioning = new Array<number[]>();
  1669. }
  1670. this._facetNb = this.getIndices().length / 3;
  1671. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1672. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1673. for (var f = 0; f < this._facetNb; f++) {
  1674. this._facetNormals[f] = Vector3.Zero();
  1675. this._facetPositions[f] = Vector3.Zero();
  1676. }
  1677. this._facetDataEnabled = true;
  1678. return this;
  1679. }
  1680. /**
  1681. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1682. * This method can be called within the render loop.
  1683. * 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.
  1684. * Returns the AbstractMesh.
  1685. */
  1686. public updateFacetData(): AbstractMesh {
  1687. if (!this._facetDataEnabled) {
  1688. this._initFacetData();
  1689. }
  1690. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1691. var indices = this.getIndices();
  1692. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1693. var bInfo = this.getBoundingInfo();
  1694. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1695. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1696. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1697. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  1698. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  1699. this._subDiv.max = this._partitioningSubdivisions;
  1700. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1701. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  1702. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  1703. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  1704. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  1705. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  1706. // set the parameters for ComputeNormals()
  1707. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  1708. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  1709. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1710. this._facetParameters.bInfo = bInfo;
  1711. this._facetParameters.bbSize = this._bbSize;
  1712. this._facetParameters.subDiv = this._subDiv;
  1713. this._facetParameters.ratio = this.partitioningBBoxRatio;
  1714. VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  1715. return this;
  1716. }
  1717. /**
  1718. * Returns the facetLocalNormals array.
  1719. * The normals are expressed in the mesh local space.
  1720. */
  1721. public getFacetLocalNormals(): Vector3[] {
  1722. if (!this._facetNormals) {
  1723. this.updateFacetData();
  1724. }
  1725. return this._facetNormals;
  1726. }
  1727. /**
  1728. * Returns the facetLocalPositions array.
  1729. * The facet positions are expressed in the mesh local space.
  1730. */
  1731. public getFacetLocalPositions(): Vector3[] {
  1732. if (!this._facetPositions) {
  1733. this.updateFacetData();
  1734. }
  1735. return this._facetPositions;
  1736. }
  1737. /**
  1738. * Returns the facetLocalPartioning array.
  1739. */
  1740. public getFacetLocalPartitioning(): number[][] {
  1741. if (!this._facetPartitioning) {
  1742. this.updateFacetData();
  1743. }
  1744. return this._facetPartitioning;
  1745. }
  1746. /**
  1747. * Returns the i-th facet position in the world system.
  1748. * This method allocates a new Vector3 per call.
  1749. */
  1750. public getFacetPosition(i: number): Vector3 {
  1751. var pos = Vector3.Zero();
  1752. this.getFacetPositionToRef(i, pos);
  1753. return pos;
  1754. }
  1755. /**
  1756. * Sets the reference Vector3 with the i-th facet position in the world system.
  1757. * Returns the AbstractMesh.
  1758. */
  1759. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1760. var localPos = (this.getFacetLocalPositions())[i];
  1761. var world = this.getWorldMatrix();
  1762. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1763. return this;
  1764. }
  1765. /**
  1766. * Returns the i-th facet normal in the world system.
  1767. * This method allocates a new Vector3 per call.
  1768. */
  1769. public getFacetNormal(i: number): Vector3 {
  1770. var norm = Vector3.Zero();
  1771. this.getFacetNormalToRef(i, norm);
  1772. return norm;
  1773. }
  1774. /**
  1775. * Sets the reference Vector3 with the i-th facet normal in the world system.
  1776. * Returns the AbstractMesh.
  1777. */
  1778. public getFacetNormalToRef(i: number, ref: Vector3) {
  1779. var localNorm = (this.getFacetLocalNormals())[i];
  1780. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1781. return this;
  1782. }
  1783. /**
  1784. * 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).
  1785. */
  1786. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): number[] {
  1787. var bInfo = this.getBoundingInfo();
  1788. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  1789. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  1790. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  1791. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  1792. return null;
  1793. }
  1794. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  1795. }
  1796. /**
  1797. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  1798. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  1799. * 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.
  1800. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1801. * 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.
  1802. */
  1803. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1804. var world = this.getWorldMatrix();
  1805. var invMat = Tmp.Matrix[5];
  1806. world.invertToRef(invMat);
  1807. var invVect = Tmp.Vector3[8];
  1808. var closest = null;
  1809. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1810. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1811. if (projected) {
  1812. // tranform the local computed projected vector to world coordinates
  1813. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1814. }
  1815. return closest;
  1816. }
  1817. /**
  1818. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  1819. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  1820. * 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.
  1821. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1822. * 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.
  1823. */
  1824. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1825. var closest = null;
  1826. var tmpx = 0.0;
  1827. var tmpy = 0.0;
  1828. var tmpz = 0.0;
  1829. var d = 0.0; // tmp dot facet normal * facet position
  1830. var t0 = 0.0;
  1831. var projx = 0.0;
  1832. var projy = 0.0;
  1833. var projz = 0.0;
  1834. // Get all the facets in the same partitioning block than (x, y, z)
  1835. var facetPositions = this.getFacetLocalPositions();
  1836. var facetNormals = this.getFacetLocalNormals();
  1837. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1838. if (!facetsInBlock) {
  1839. return null;
  1840. }
  1841. // Get the closest facet to (x, y, z)
  1842. var shortest = Number.MAX_VALUE; // init distance vars
  1843. var tmpDistance = shortest;
  1844. var fib; // current facet in the block
  1845. var norm; // current facet normal
  1846. var p0; // current facet barycenter position
  1847. // loop on all the facets in the current partitioning block
  1848. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1849. fib = facetsInBlock[idx];
  1850. norm = facetNormals[fib];
  1851. p0 = facetPositions[fib];
  1852. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1853. if ( !checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0) ) {
  1854. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1855. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1856. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1857. projx = x + norm.x * t0;
  1858. projy = y + norm.y * t0;
  1859. projz = z + norm.z * t0;
  1860. tmpx = projx - x;
  1861. tmpy = projy - y;
  1862. tmpz = projz - z;
  1863. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1864. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1865. shortest = tmpDistance;
  1866. closest = fib;
  1867. if (projected) {
  1868. projected.x = projx;
  1869. projected.y = projy;
  1870. projected.z = projz;
  1871. }
  1872. }
  1873. }
  1874. }
  1875. return closest;
  1876. }
  1877. /**
  1878. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1879. */
  1880. public getFacetDataParameters(): any {
  1881. return this._facetParameters;
  1882. }
  1883. /**
  1884. * Disables the feature FacetData and frees the related memory.
  1885. * Returns the AbstractMesh.
  1886. */
  1887. public disableFacetData(): AbstractMesh {
  1888. if (this._facetDataEnabled) {
  1889. this._facetDataEnabled = false;
  1890. this._facetPositions = null;
  1891. this._facetNormals = null;
  1892. this._facetPartitioning = null;
  1893. this._facetParameters = null;
  1894. }
  1895. return this;
  1896. }
  1897. /**
  1898. * Creates new normals data for the mesh.
  1899. * @param updatable.
  1900. */
  1901. public createNormals(updatable: boolean) {
  1902. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1903. var indices = this.getIndices();
  1904. var normals: number[] | Float32Array;
  1905. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1906. normals = this.getVerticesData(VertexBuffer.NormalKind);
  1907. } else {
  1908. normals = [];
  1909. }
  1910. VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  1911. this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
  1912. }
  1913. }
  1914. }