babylon.mesh.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. module BABYLON {
  2. export class Mesh extends Node implements IGetSetVerticesData {
  3. // Statics
  4. public static BILLBOARDMODE_NONE = 0;
  5. public static BILLBOARDMODE_X = 1;
  6. public static BILLBOARDMODE_Y = 2;
  7. public static BILLBOARDMODE_Z = 4;
  8. public static BILLBOARDMODE_ALL = 7;
  9. // Members
  10. public position = new BABYLON.Vector3(0, 0, 0);
  11. public rotation = new BABYLON.Vector3(0, 0, 0);
  12. public rotationQuaternion = null;
  13. public scaling = new BABYLON.Vector3(1, 1, 1);
  14. public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15. public material = null;
  16. public isVisible = true;
  17. public isPickable = true;
  18. public visibility = 1.0;
  19. public billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  20. public checkCollisions = false;
  21. public receiveShadows = false;
  22. public _isDisposed = false;
  23. public onDispose = null;
  24. public skeleton = null;
  25. public renderingGroupId = 0;
  26. public infiniteDistance = false;
  27. public showBoundingBox = false;
  28. public subMeshes: SubMesh[];
  29. public delayLoadingFile: string;
  30. public actionManager: ActionManager;
  31. // Cache
  32. private _positions = null;
  33. private _localScaling = BABYLON.Matrix.Zero();
  34. private _localRotation = BABYLON.Matrix.Zero();
  35. private _localTranslation = BABYLON.Matrix.Zero();
  36. private _localBillboard = BABYLON.Matrix.Zero();
  37. private _localPivotScaling = BABYLON.Matrix.Zero();
  38. private _localPivotScalingRotation = BABYLON.Matrix.Zero();
  39. private _localWorld = BABYLON.Matrix.Zero();
  40. private _worldMatrix = BABYLON.Matrix.Zero();
  41. private _rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  42. private _collisionsTransformMatrix = BABYLON.Matrix.Zero();
  43. private _collisionsScalingMatrix = BABYLON.Matrix.Zero();
  44. private _absolutePosition = BABYLON.Vector3.Zero();
  45. private _isDirty = false;
  46. // Physics
  47. public _physicImpostor = PhysicsEngine.NoImpostor;
  48. public _physicsMass: number;
  49. public _physicsFriction: number;
  50. public _physicRestitution: number;
  51. // Private
  52. public _geometry: Geometry;
  53. public _boundingInfo: BoundingInfo;
  54. private _pivotMatrix = BABYLON.Matrix.Identity();
  55. private _renderId = 0;
  56. private _onBeforeRenderCallbacks = [];
  57. private _delayInfo; //ANY
  58. private _animationStarted = false;
  59. private _delayLoadingFunction: (any, Mesh) => void;
  60. constructor(name: string, scene: Scene) {
  61. super(name, scene);
  62. scene.meshes.push(this);
  63. }
  64. public getBoundingInfo(): BoundingInfo {
  65. return this._boundingInfo;
  66. }
  67. public getWorldMatrix(): Matrix {
  68. if (this._currentRenderId !== this.getScene().getRenderId()) {
  69. this.computeWorldMatrix();
  70. }
  71. return this._worldMatrix;
  72. }
  73. public rotate(axis: Vector3, amount: number, space: Space): void {
  74. if (!this.rotationQuaternion) {
  75. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  76. this.rotation = BABYLON.Vector3.Zero();
  77. }
  78. if (!space || space == BABYLON.Space.LOCAL) {
  79. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  80. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  81. }
  82. else {
  83. if (this.parent) {
  84. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  85. invertParentWorldMatrix.invert();
  86. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  87. }
  88. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  89. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  90. }
  91. }
  92. public translate(axis: Vector3, distance: number, space: Space): void {
  93. var displacementVector = axis.scale(distance);
  94. if (!space || space == BABYLON.Space.LOCAL) {
  95. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  96. this.setPositionWithLocalVector(tempV3);
  97. }
  98. else {
  99. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  100. }
  101. }
  102. public getAbsolutePosition(): Vector3 {
  103. this.computeWorldMatrix();
  104. return this._absolutePosition;
  105. }
  106. public setAbsolutePosition(absolutePosition: Vector3): void {
  107. if (!absolutePosition) {
  108. return;
  109. }
  110. var absolutePositionX;
  111. var absolutePositionY;
  112. var absolutePositionZ;
  113. if (absolutePosition.x === undefined) {
  114. if (arguments.length < 3) {
  115. return;
  116. }
  117. absolutePositionX = arguments[0];
  118. absolutePositionY = arguments[1];
  119. absolutePositionZ = arguments[2];
  120. }
  121. else {
  122. absolutePositionX = absolutePosition.x;
  123. absolutePositionY = absolutePosition.y;
  124. absolutePositionZ = absolutePosition.z;
  125. }
  126. if (this.parent) {
  127. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  128. invertParentWorldMatrix.invert();
  129. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  130. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  131. } else {
  132. this.position.x = absolutePositionX;
  133. this.position.y = absolutePositionY;
  134. this.position.z = absolutePositionZ;
  135. }
  136. }
  137. public getTotalVertices(): number {
  138. if (!this._geometry) {
  139. return 0;
  140. }
  141. return this._geometry.getTotalVertices();
  142. }
  143. public getVerticesData(kind): number[] {
  144. if (!this._geometry) {
  145. return null;
  146. }
  147. return this._geometry.getVerticesData(kind);
  148. }
  149. public getVertexBuffer(kind): VertexBuffer {
  150. if (!this._geometry) {
  151. return undefined;
  152. }
  153. return this._geometry.getVertexBuffer(kind);
  154. }
  155. public isVerticesDataPresent(kind: string): boolean {
  156. if (!this._geometry) {
  157. if (this._delayInfo) {
  158. return this._delayInfo.indexOf(kind) !== -1;
  159. }
  160. return false;
  161. }
  162. return this._geometry.isVerticesDataPresent(kind);
  163. }
  164. public getVerticesDataKinds(): string[] {
  165. if (!this._geometry) {
  166. var result = [];
  167. if (this._delayInfo) {
  168. for (var kind in this._delayInfo) {
  169. result.push(kind);
  170. }
  171. }
  172. return result;
  173. }
  174. return this._geometry.getVerticesDataKinds();
  175. }
  176. public getTotalIndices(): number {
  177. if (!this._geometry) {
  178. return 0;
  179. }
  180. return this._geometry.getTotalIndices();
  181. }
  182. public getIndices(): number[] {
  183. if (!this._geometry) {
  184. return [];
  185. }
  186. return this._geometry.getIndices();
  187. }
  188. public setPivotMatrix(matrix: Matrix): void {
  189. this._pivotMatrix = matrix;
  190. this._cache.pivotMatrixUpdated = true;
  191. }
  192. public getPivotMatrix(): Matrix {
  193. return this._pivotMatrix;
  194. }
  195. public _isSynchronized(): boolean {
  196. if (this._isDirty) {
  197. return false;
  198. }
  199. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE)
  200. return false;
  201. if (this._cache.pivotMatrixUpdated) {
  202. return false;
  203. }
  204. if (this.infiniteDistance) {
  205. return false;
  206. }
  207. if (!this._cache.position.equals(this.position))
  208. return false;
  209. if (this.rotationQuaternion) {
  210. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  211. return false;
  212. } else {
  213. if (!this._cache.rotation.equals(this.rotation))
  214. return false;
  215. }
  216. if (!this._cache.scaling.equals(this.scaling))
  217. return false;
  218. return true;
  219. }
  220. public isReady(): boolean {
  221. return this._isReady;
  222. }
  223. public isAnimated(): boolean {
  224. return this._animationStarted;
  225. }
  226. public isDisposed(): boolean {
  227. return this._isDisposed;
  228. }
  229. // Methods
  230. public _initCache() {
  231. super._initCache();
  232. this._cache.localMatrixUpdated = false;
  233. this._cache.position = BABYLON.Vector3.Zero();
  234. this._cache.scaling = BABYLON.Vector3.Zero();
  235. this._cache.rotation = BABYLON.Vector3.Zero();
  236. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  237. }
  238. public markAsDirty(property: string): void {
  239. if (property === "rotation") {
  240. this.rotationQuaternion = null;
  241. }
  242. this._currentRenderId = Number.MAX_VALUE;
  243. this._isDirty = true;
  244. }
  245. public refreshBoundingInfo(): void {
  246. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  247. if (data) {
  248. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  249. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  250. }
  251. if (this.subMeshes) {
  252. for (var index = 0; index < this.subMeshes.length; index++) {
  253. this.subMeshes[index].refreshBoundingInfo();
  254. }
  255. }
  256. this._updateBoundingInfo();
  257. }
  258. public _updateBoundingInfo(): void {
  259. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
  260. this._boundingInfo._update(this._worldMatrix);
  261. if (!this.subMeshes) {
  262. return;
  263. }
  264. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  265. var subMesh = this.subMeshes[subIndex];
  266. subMesh.updateBoundingInfo(this._worldMatrix);
  267. }
  268. }
  269. public computeWorldMatrix(force?: boolean): Matrix {
  270. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  271. return this._worldMatrix;
  272. }
  273. this._cache.position.copyFrom(this.position);
  274. this._cache.scaling.copyFrom(this.scaling);
  275. this._cache.pivotMatrixUpdated = false;
  276. this._currentRenderId = this.getScene().getRenderId();
  277. this._isDirty = false;
  278. // Scaling
  279. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  280. // Rotation
  281. if (this.rotationQuaternion) {
  282. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  283. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  284. } else {
  285. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  286. this._cache.rotation.copyFrom(this.rotation);
  287. }
  288. // Translation
  289. if (this.infiniteDistance && !this.parent) {
  290. var camera = this.getScene().activeCamera;
  291. var cameraWorldMatrix = camera.getWorldMatrix();
  292. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  293. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  294. } else {
  295. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  296. }
  297. // Composing transformations
  298. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  299. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  300. // Billboarding
  301. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE) {
  302. var localPosition = this.position.clone();
  303. var zero = this.getScene().activeCamera.position.clone();
  304. if (this.parent && (<any>this.parent).position) {
  305. localPosition.addInPlace((<any>this.parent).position);
  306. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  307. }
  308. if ((this.billboardMode & Mesh.BILLBOARDMODE_ALL) === Mesh.BILLBOARDMODE_ALL) {
  309. zero = this.getScene().activeCamera.position;
  310. } else {
  311. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  312. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  313. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  314. zero.y = localPosition.y + 0.001;
  315. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  316. zero.z = localPosition.z + 0.001;
  317. }
  318. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  319. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  320. this._localBillboard.invert();
  321. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  322. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  323. }
  324. // Local world
  325. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  326. // Parent
  327. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  328. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  329. } else {
  330. this._worldMatrix.copyFrom(this._localWorld);
  331. }
  332. // Bounding info
  333. this._updateBoundingInfo();
  334. // Absolute position
  335. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  336. return this._worldMatrix;
  337. }
  338. public _createGlobalSubMesh(): SubMesh {
  339. var totalVertices = this.getTotalVertices();
  340. if (!totalVertices || !this.getIndices()) {
  341. return null;
  342. }
  343. this.subMeshes = [];
  344. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  345. }
  346. public subdivide(count: number): void {
  347. if (count < 1) {
  348. return;
  349. }
  350. var totalIndices = this.getTotalIndices();
  351. var subdivisionSize = totalIndices / count;
  352. var offset = 0;
  353. this.subMeshes = [];
  354. for (var index = 0; index < count; index++) {
  355. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  356. offset += subdivisionSize;
  357. }
  358. }
  359. public setVerticesData(data: number[], kind: string, updatable?: boolean): void {
  360. if (!this._geometry) {
  361. var vertexData = new BABYLON.VertexData();
  362. vertexData.set(data, kind);
  363. var scene = this.getScene();
  364. new BABYLON.Geometry(Geometry.RandomId(), scene.getEngine(), vertexData, updatable, this);
  365. }
  366. else {
  367. this._geometry.setVerticesData(data, kind, updatable);
  368. }
  369. }
  370. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  371. if (!this._geometry) {
  372. return;
  373. }
  374. if (!makeItUnique) {
  375. this._geometry.updateVerticesData(kind, data, updateExtends);
  376. }
  377. else {
  378. this.makeGeometryUnique();
  379. this.updateVerticesData(kind, data, updateExtends, false);
  380. }
  381. }
  382. public makeGeometryUnique() {
  383. if (!this._geometry) {
  384. return;
  385. }
  386. var geometry = this._geometry.copy(Geometry.RandomId());
  387. geometry.applyToMesh(this);
  388. }
  389. public setIndices(indices: number[]): void {
  390. if (!this._geometry) {
  391. var vertexData = new BABYLON.VertexData();
  392. vertexData.indices = indices;
  393. var scene = this.getScene();
  394. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene.getEngine(), vertexData, false, this);
  395. }
  396. else {
  397. this._geometry.setIndices(indices);
  398. }
  399. }
  400. // ANY
  401. public bindAndDraw(subMesh: SubMesh, effect, wireframe?: boolean): void {
  402. if (!this._geometry) {
  403. return;
  404. }
  405. var engine = this.getScene().getEngine();
  406. // Wireframe
  407. var indexToBind = this._geometry.getIndexBuffer();
  408. var useTriangles = true;
  409. if (wireframe) {
  410. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  411. useTriangles = false;
  412. }
  413. // VBOs
  414. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  415. // Draw order
  416. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  417. }
  418. public registerBeforeRender(func: () => void): void {
  419. this._onBeforeRenderCallbacks.push(func);
  420. }
  421. public unregisterBeforeRender(func: () => void): void {
  422. var index = this._onBeforeRenderCallbacks.indexOf(func);
  423. if (index > -1) {
  424. this._onBeforeRenderCallbacks.splice(index, 1);
  425. }
  426. }
  427. public render(subMesh: SubMesh): void {
  428. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  429. return;
  430. }
  431. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  432. this._onBeforeRenderCallbacks[callbackIndex]();
  433. }
  434. // World
  435. var world = this.getWorldMatrix();
  436. // Material
  437. var effectiveMaterial = subMesh.getMaterial();
  438. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  439. return;
  440. }
  441. effectiveMaterial._preBind();
  442. effectiveMaterial.bind(world, this);
  443. // Bind and draw
  444. var engine = this.getScene().getEngine();
  445. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  446. // Unbind
  447. effectiveMaterial.unbind();
  448. }
  449. public getEmittedParticleSystems(): ParticleSystem[] {
  450. var results = new Array<ParticleSystem>();
  451. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  452. var particleSystem = this.getScene().particleSystems[index];
  453. if (particleSystem.emitter === this) {
  454. results.push(particleSystem);
  455. }
  456. }
  457. return results;
  458. }
  459. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  460. var results = new Array<ParticleSystem>();
  461. var descendants = this.getDescendants();
  462. descendants.push(this);
  463. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  464. var particleSystem = this.getScene().particleSystems[index];
  465. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  466. results.push(particleSystem);
  467. }
  468. }
  469. return results;
  470. }
  471. public getChildren(): Node[] {
  472. var results = [];
  473. for (var index = 0; index < this.getScene().meshes.length; index++) {
  474. var mesh = this.getScene().meshes[index];
  475. if (mesh.parent == this) {
  476. results.push(mesh);
  477. }
  478. }
  479. return results;
  480. }
  481. public isInFrustum(frustumPlanes: Plane[]): boolean {
  482. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  483. return false;
  484. }
  485. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  486. return false;
  487. }
  488. var that = this;
  489. var scene = this.getScene();
  490. if (this._geometry) {
  491. this._geometry.load(scene);
  492. }
  493. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  494. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  495. scene._addPendingData(that);
  496. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  497. that._delayLoadingFunction(JSON.parse(data), that);
  498. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  499. scene._removePendingData(that);
  500. }, function () { }, scene.database);
  501. }
  502. return true;
  503. }
  504. public setMaterialByID(id: string): void {
  505. var materials = this.getScene().materials;
  506. for (var index = 0; index < materials.length; index++) {
  507. if (materials[index].id == id) {
  508. this.material = materials[index];
  509. return;
  510. }
  511. }
  512. // Multi
  513. var multiMaterials = this.getScene().multiMaterials;
  514. for (index = 0; index < multiMaterials.length; index++) {
  515. if (multiMaterials[index].id == id) {
  516. this.material = multiMaterials[index];
  517. return;
  518. }
  519. }
  520. }
  521. public getAnimatables(): IAnimatable[] {
  522. var results = [];
  523. if (this.material) {
  524. results.push(this.material);
  525. }
  526. return results;
  527. }
  528. // Geometry
  529. public setPositionWithLocalVector(vector3: Vector3): void {
  530. this.computeWorldMatrix();
  531. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  532. }
  533. public getPositionExpressedInLocalSpace(): Vector3 {
  534. this.computeWorldMatrix();
  535. var invLocalWorldMatrix = this._localWorld.clone();
  536. invLocalWorldMatrix.invert();
  537. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  538. }
  539. public locallyTranslate(vector3: Vector3): void {
  540. this.computeWorldMatrix();
  541. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  542. }
  543. public bakeTransformIntoVertices(transform: Matrix): void {
  544. // Position
  545. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  546. return;
  547. }
  548. this._resetPointsArrayCache();
  549. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  550. var temp = [];
  551. for (var index = 0; index < data.length; index += 3) {
  552. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  553. }
  554. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  555. // Normals
  556. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  557. return;
  558. }
  559. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  560. for (index = 0; index < data.length; index += 3) {
  561. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  562. }
  563. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  564. }
  565. public lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void {
  566. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  567. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  568. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  569. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  570. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  571. /// <returns>Mesh oriented towards targetMesh</returns>
  572. yawCor = yawCor || 0; // default to zero if undefined
  573. pitchCor = pitchCor || 0;
  574. rollCor = rollCor || 0;
  575. var dv = targetPoint.subtract(this.position);
  576. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  577. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  578. var pitch = Math.atan2(dv.y, len);
  579. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  580. }
  581. // Cache
  582. public _resetPointsArrayCache(): void {
  583. this._positions = null;
  584. }
  585. public _generatePointsArray(): void {
  586. if (this._positions)
  587. return;
  588. this._positions = [];
  589. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  590. for (var index = 0; index < data.length; index += 3) {
  591. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  592. }
  593. }
  594. // Collisions
  595. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void {
  596. this._generatePointsArray();
  597. // Transformation
  598. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  599. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  600. subMesh._lastColliderWorldVertices = [];
  601. subMesh._trianglePlanes = [];
  602. var start = subMesh.verticesStart;
  603. var end = (subMesh.verticesStart + subMesh.verticesCount);
  604. for (var i = start; i < end; i++) {
  605. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  606. }
  607. }
  608. // Collide
  609. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  610. }
  611. public _processCollisionsForSubModels(collider: Collider, transformMatrix: Matrix): void {
  612. for (var index = 0; index < this.subMeshes.length; index++) {
  613. var subMesh = this.subMeshes[index];
  614. // Bounding test
  615. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  616. continue;
  617. this._collideForSubMesh(subMesh, transformMatrix, collider);
  618. }
  619. }
  620. public _checkCollision(collider: Collider): void {
  621. // Bounding box test
  622. if (!this._boundingInfo._checkCollision(collider))
  623. return;
  624. // Transformation matrix
  625. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  626. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  627. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  628. }
  629. public intersectsMesh(mesh: Mesh, precise?: boolean): boolean {
  630. if (!this._boundingInfo || !mesh._boundingInfo) {
  631. return false;
  632. }
  633. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  634. }
  635. public intersectsPoint(point: Vector3): boolean {
  636. if (!this._boundingInfo) {
  637. return false;
  638. }
  639. return this._boundingInfo.intersectsPoint(point);
  640. }
  641. // Picking
  642. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  643. var pickingInfo = new BABYLON.PickingInfo();
  644. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  645. return pickingInfo;
  646. }
  647. this._generatePointsArray();
  648. var intersectInfo: IntersectionInfo = null;
  649. for (var index = 0; index < this.subMeshes.length; index++) {
  650. var subMesh = this.subMeshes[index];
  651. // Bounding test
  652. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  653. continue;
  654. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  655. if (currentIntersectInfo) {
  656. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  657. intersectInfo = currentIntersectInfo;
  658. if (fastCheck) {
  659. break;
  660. }
  661. }
  662. }
  663. }
  664. if (intersectInfo) {
  665. // Get picked point
  666. var world = this.getWorldMatrix();
  667. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  668. var direction = ray.direction.clone();
  669. direction.normalize();
  670. direction = direction.scale(intersectInfo.distance);
  671. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  672. var pickedPoint = worldOrigin.add(worldDirection);
  673. // Return result
  674. pickingInfo.hit = true;
  675. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  676. pickingInfo.pickedPoint = pickedPoint;
  677. pickingInfo.pickedMesh = this;
  678. pickingInfo.bu = intersectInfo.bu;
  679. pickingInfo.bv = intersectInfo.bv;
  680. pickingInfo.faceId = intersectInfo.faceId;
  681. return pickingInfo;
  682. }
  683. return pickingInfo;
  684. }
  685. // Clone
  686. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  687. var result = new BABYLON.Mesh(name, this.getScene());
  688. // Geometry
  689. this._geometry.applyToMesh(result);
  690. // Deep copy
  691. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  692. // Bounding info
  693. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  694. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  695. // Material
  696. result.material = this.material;
  697. // Parent
  698. if (newParent) {
  699. result.parent = newParent;
  700. }
  701. if (!doNotCloneChildren) {
  702. // Children
  703. for (var index = 0; index < this.getScene().meshes.length; index++) {
  704. var mesh = this.getScene().meshes[index];
  705. if (mesh.parent == this) {
  706. mesh.clone(mesh.name, result);
  707. }
  708. }
  709. }
  710. // Particles
  711. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  712. var system = this.getScene().particleSystems[index];
  713. if (system.emitter == this) {
  714. system.clone(system.name, result);
  715. }
  716. }
  717. result.computeWorldMatrix(true);
  718. return result;
  719. }
  720. // Dispose
  721. public dispose(doNotRecurse?: boolean): void {
  722. if (this._geometry) {
  723. this._geometry.releaseForMesh(this);
  724. }
  725. // Physics
  726. if (this.getPhysicsImpostor() != PhysicsEngine.NoImpostor) {
  727. this.setPhysicsState(PhysicsEngine.NoImpostor);
  728. }
  729. // Remove from scene
  730. var index = this.getScene().meshes.indexOf(this);
  731. this.getScene().meshes.splice(index, 1);
  732. if (!doNotRecurse) {
  733. // Particles
  734. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  735. if (this.getScene().particleSystems[index].emitter == this) {
  736. this.getScene().particleSystems[index].dispose();
  737. index--;
  738. }
  739. }
  740. // Children
  741. var objects = this.getScene().meshes.slice(0);
  742. for (index = 0; index < objects.length; index++) {
  743. if (objects[index].parent == this) {
  744. objects[index].dispose();
  745. }
  746. }
  747. } else {
  748. for (index = 0; index < this.getScene().meshes.length; index++) {
  749. var obj = this.getScene().meshes[index];
  750. if (obj.parent === this) {
  751. obj.parent = null;
  752. obj.computeWorldMatrix(true);
  753. }
  754. }
  755. }
  756. this._isDisposed = true;
  757. // Callback
  758. if (this.onDispose) {
  759. this.onDispose();
  760. }
  761. }
  762. // Physics
  763. public setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): void {
  764. var physicsEngine = this.getScene().getPhysicsEngine();
  765. if (!physicsEngine) {
  766. return;
  767. }
  768. if (impostor.impostor) {
  769. // Old API
  770. options = impostor;
  771. impostor = impostor.impostor;
  772. }
  773. impostor = impostor || PhysicsEngine.NoImpostor;
  774. options.mass = options.mass || 0;
  775. options.friction = options.friction || 0.2;
  776. options.restitution = options.restitution || 0.9;
  777. this._physicImpostor = impostor;
  778. this._physicsMass = options.mass;
  779. this._physicsFriction = options.friction;
  780. this._physicRestitution = options.restitution;
  781. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  782. physicsEngine._unregisterMesh(this);
  783. return;
  784. }
  785. physicsEngine._registerMesh(this, impostor, options);
  786. }
  787. public getPhysicsImpostor(): number {
  788. if (!this._physicImpostor) {
  789. return BABYLON.PhysicsEngine.NoImpostor;
  790. }
  791. return this._physicImpostor;
  792. }
  793. public getPhysicsMass(): number {
  794. if (!this._physicsMass) {
  795. return 0;
  796. }
  797. return this._physicsMass;
  798. }
  799. public getPhysicsFriction(): number {
  800. if (!this._physicsFriction) {
  801. return 0;
  802. }
  803. return this._physicsFriction;
  804. }
  805. public getPhysicsRestitution(): number {
  806. if (!this._physicRestitution) {
  807. return 0;
  808. }
  809. return this._physicRestitution;
  810. }
  811. public applyImpulse(force: Vector3, contactPoint: Vector3): void {
  812. if (!this._physicImpostor) {
  813. return;
  814. }
  815. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  816. }
  817. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3): void {
  818. if (!this._physicImpostor) {
  819. return;
  820. }
  821. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
  822. }
  823. // Geometric tools
  824. public convertToFlatShadedMesh(): void {
  825. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  826. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  827. var kinds = this.getVerticesDataKinds();
  828. var vbs = [];
  829. var data = [];
  830. var newdata = [];
  831. var updatableNormals = false;
  832. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  833. var kind = kinds[kindIndex];
  834. var vertexBuffer = this.getVertexBuffer(kind);
  835. if (kind === BABYLON.VertexBuffer.NormalKind) {
  836. updatableNormals = vertexBuffer.isUpdatable();
  837. kinds.splice(kindIndex, 1);
  838. kindIndex--;
  839. continue;
  840. }
  841. vbs[kind] = vertexBuffer;
  842. data[kind] = vbs[kind].getData();
  843. newdata[kind] = [];
  844. }
  845. // Save previous submeshes
  846. var previousSubmeshes = this.subMeshes.slice(0);
  847. var indices = this.getIndices();
  848. var totalIndices = this.getTotalIndices();
  849. // Generating unique vertices per face
  850. for (index = 0; index < totalIndices; index++) {
  851. var vertexIndex = indices[index];
  852. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  853. kind = kinds[kindIndex];
  854. var stride = vbs[kind].getStrideSize();
  855. for (var offset = 0; offset < stride; offset++) {
  856. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  857. }
  858. }
  859. }
  860. // Updating faces & normal
  861. var normals = [];
  862. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  863. for (var index = 0; index < totalIndices; index += 3) {
  864. indices[index] = index;
  865. indices[index + 1] = index + 1;
  866. indices[index + 2] = index + 2;
  867. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  868. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  869. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  870. var p1p2 = p1.subtract(p2);
  871. var p3p2 = p3.subtract(p2);
  872. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  873. // Store same normals for every vertex
  874. for (var localIndex = 0; localIndex < 3; localIndex++) {
  875. normals.push(normal.x);
  876. normals.push(normal.y);
  877. normals.push(normal.z);
  878. }
  879. }
  880. this.setIndices(indices);
  881. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  882. // Updating vertex buffers
  883. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  884. kind = kinds[kindIndex];
  885. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  886. }
  887. // Updating submeshes
  888. this.subMeshes = [];
  889. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  890. var previousOne = previousSubmeshes[submeshIndex];
  891. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  892. }
  893. }
  894. // Statics
  895. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  896. var box = new BABYLON.Mesh(name, scene);
  897. var vertexData = BABYLON.VertexData.CreateBox(size);
  898. vertexData.applyToMesh(box, updatable);
  899. return box;
  900. }
  901. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  902. var sphere = new BABYLON.Mesh(name, scene);
  903. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  904. vertexData.applyToMesh(sphere, updatable);
  905. return sphere;
  906. }
  907. // Cylinder and cone (Code inspired by SharpDX.org)
  908. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  909. var cylinder = new BABYLON.Mesh(name, scene);
  910. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  911. vertexData.applyToMesh(cylinder, updatable);
  912. return cylinder;
  913. }
  914. // Torus (Code from SharpDX.org)
  915. public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  916. var torus = new BABYLON.Mesh(name, scene);
  917. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  918. vertexData.applyToMesh(torus, updatable);
  919. return torus;
  920. }
  921. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  922. var torusKnot = new BABYLON.Mesh(name, scene);
  923. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  924. vertexData.applyToMesh(torusKnot, updatable);
  925. return torusKnot;
  926. }
  927. // Plane & ground
  928. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  929. var plane = new BABYLON.Mesh(name, scene);
  930. var vertexData = BABYLON.VertexData.CreatePlane(size);
  931. vertexData.applyToMesh(plane, updatable);
  932. return plane;
  933. }
  934. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  935. var ground = new BABYLON.Mesh(name, scene);
  936. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  937. vertexData.applyToMesh(ground, updatable);
  938. return ground;
  939. }
  940. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): Mesh {
  941. var ground = new BABYLON.Mesh(name, scene);
  942. var onload = img => {
  943. // Getting height map data
  944. var canvas = document.createElement("canvas");
  945. var context = canvas.getContext("2d");
  946. var heightMapWidth = img.width;
  947. var heightMapHeight = img.height;
  948. canvas.width = heightMapWidth;
  949. canvas.height = heightMapHeight;
  950. context.drawImage(img, 0, 0);
  951. // Create VertexData from map data
  952. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  953. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  954. vertexData.applyToMesh(ground, updatable);
  955. ground._isReady = true;
  956. };
  957. Tools.LoadImage(url, onload, () => {}, scene.database);
  958. ground._isReady = false;
  959. return ground;
  960. }
  961. // Tools
  962. public static MinMax(meshes: Mesh[]): {min: Vector3; max: Vector3} {
  963. var minVector = null;
  964. var maxVector = null;
  965. for (var i in meshes) {
  966. var mesh = meshes[i];
  967. var boundingBox = mesh.getBoundingInfo().boundingBox;
  968. if (!minVector) {
  969. minVector = boundingBox.minimumWorld;
  970. maxVector = boundingBox.maximumWorld;
  971. continue;
  972. }
  973. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  974. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  975. }
  976. return {
  977. min: minVector,
  978. max: maxVector
  979. };
  980. }
  981. public static Center(meshesOrMinMaxVector): Vector3 {
  982. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  983. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  984. }
  985. }
  986. }