babylon.mesh.ts 46 KB

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