babylon.mesh.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances = new Array<Array<InstancedMesh>>();
  5. public renderSelf = new Array<boolean>();
  6. }
  7. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  8. // Members
  9. public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10. public instances = new Array<InstancedMesh>();
  11. public delayLoadingFile: string;
  12. // Private
  13. public _geometry: Geometry;
  14. private _onBeforeRenderCallbacks = new Array<() => void>();
  15. private _onAfterRenderCallbacks = new Array<() => void>();
  16. public _delayInfo; //ANY
  17. public _delayLoadingFunction: (any, Mesh) => void;
  18. public _visibleInstances: any = {};
  19. private _renderIdForInstances = new Array<number>();
  20. private _batchCache = new _InstancesBatch();
  21. private _worldMatricesInstancesBuffer: WebGLBuffer;
  22. private _worldMatricesInstancesArray: Float32Array;
  23. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24. public _shouldGenerateFlatShading: boolean;
  25. private _preActivateId: number;
  26. constructor(name: string, scene: Scene) {
  27. super(name, scene);
  28. }
  29. public getTotalVertices(): number {
  30. if (!this._geometry) {
  31. return 0;
  32. }
  33. return this._geometry.getTotalVertices();
  34. }
  35. public getVerticesData(kind: string): number[] {
  36. if (!this._geometry) {
  37. return null;
  38. }
  39. return this._geometry.getVerticesData(kind);
  40. }
  41. public getVertexBuffer(kind): VertexBuffer {
  42. if (!this._geometry) {
  43. return undefined;
  44. }
  45. return this._geometry.getVertexBuffer(kind);
  46. }
  47. public isVerticesDataPresent(kind: string): boolean {
  48. if (!this._geometry) {
  49. if (this._delayInfo) {
  50. return this._delayInfo.indexOf(kind) !== -1;
  51. }
  52. return false;
  53. }
  54. return this._geometry.isVerticesDataPresent(kind);
  55. }
  56. public getVerticesDataKinds(): string[] {
  57. if (!this._geometry) {
  58. var result = [];
  59. if (this._delayInfo) {
  60. for (var kind in this._delayInfo) {
  61. result.push(kind);
  62. }
  63. }
  64. return result;
  65. }
  66. return this._geometry.getVerticesDataKinds();
  67. }
  68. public getTotalIndices(): number {
  69. if (!this._geometry) {
  70. return 0;
  71. }
  72. return this._geometry.getTotalIndices();
  73. }
  74. public getIndices(): number[] {
  75. if (!this._geometry) {
  76. return [];
  77. }
  78. return this._geometry.getIndices();
  79. }
  80. public isReady(): boolean {
  81. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  82. return false;
  83. }
  84. return super.isReady();
  85. }
  86. public isDisposed(): boolean {
  87. return this._isDisposed;
  88. }
  89. // Methods
  90. public _preActivate(): void {
  91. var sceneRenderId = this.getScene().getRenderId();
  92. if (this._preActivateId == sceneRenderId) {
  93. return;
  94. }
  95. this._preActivateId = sceneRenderId;
  96. this._visibleInstances = null;
  97. }
  98. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  99. if (!this._visibleInstances) {
  100. this._visibleInstances = {};
  101. this._visibleInstances.defaultRenderId = renderId;
  102. this._visibleInstances.selfDefaultRenderId = this._renderId;
  103. }
  104. if (!this._visibleInstances[renderId]) {
  105. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  106. }
  107. this._visibleInstances[renderId].push(instance);
  108. }
  109. public refreshBoundingInfo(): void {
  110. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  111. if (data) {
  112. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  114. }
  115. if (this.subMeshes) {
  116. for (var index = 0; index < this.subMeshes.length; index++) {
  117. this.subMeshes[index].refreshBoundingInfo();
  118. }
  119. }
  120. this._updateBoundingInfo();
  121. }
  122. public _createGlobalSubMesh(): SubMesh {
  123. var totalVertices = this.getTotalVertices();
  124. if (!totalVertices || !this.getIndices()) {
  125. return null;
  126. }
  127. this.releaseSubMeshes();
  128. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  129. }
  130. public subdivide(count: number): void {
  131. if (count < 1) {
  132. return;
  133. }
  134. var totalIndices = this.getTotalIndices();
  135. var subdivisionSize = (totalIndices / count) | 0;
  136. var offset = 0;
  137. // Ensure that subdivisionSize is a multiple of 3
  138. while (subdivisionSize % 3 != 0) {
  139. subdivisionSize++;
  140. }
  141. this.releaseSubMeshes();
  142. for (var index = 0; index < count; index++) {
  143. if (offset >= totalIndices) {
  144. break;
  145. }
  146. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  147. offset += subdivisionSize;
  148. }
  149. this.synchronizeInstances();
  150. }
  151. public setVerticesData(kind: any, data: any, updatable?: boolean): void {
  152. if (kind instanceof Array) {
  153. var temp = data;
  154. data = kind;
  155. kind = temp;
  156. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  157. }
  158. if (!this._geometry) {
  159. var vertexData = new BABYLON.VertexData();
  160. vertexData.set(data, kind);
  161. var scene = this.getScene();
  162. new BABYLON.Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  163. }
  164. else {
  165. this._geometry.setVerticesData(kind, data, updatable);
  166. }
  167. }
  168. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  169. if (!this._geometry) {
  170. return;
  171. }
  172. if (!makeItUnique) {
  173. this._geometry.updateVerticesData(kind, data, updateExtends);
  174. }
  175. else {
  176. this.makeGeometryUnique();
  177. this.updateVerticesData(kind, data, updateExtends, false);
  178. }
  179. }
  180. public makeGeometryUnique() {
  181. if (!this._geometry) {
  182. return;
  183. }
  184. var geometry = this._geometry.copy(Geometry.RandomId());
  185. geometry.applyToMesh(this);
  186. }
  187. public setIndices(indices: number[]): void {
  188. if (!this._geometry) {
  189. var vertexData = new BABYLON.VertexData();
  190. vertexData.indices = indices;
  191. var scene = this.getScene();
  192. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  193. }
  194. else {
  195. this._geometry.setIndices(indices);
  196. }
  197. }
  198. public _bind(subMesh: SubMesh, effect: Effect, wireframe?: boolean): void {
  199. var engine = this.getScene().getEngine();
  200. // Wireframe
  201. var indexToBind = this._geometry.getIndexBuffer();
  202. if (wireframe) {
  203. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  204. }
  205. // VBOs
  206. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  207. }
  208. public _draw(subMesh: SubMesh, useTriangles: boolean, instancesCount?: number): void {
  209. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  210. return;
  211. }
  212. var engine = this.getScene().getEngine();
  213. // Draw order
  214. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  215. }
  216. public _fullDraw(subMesh: SubMesh, useTriangles: boolean, instancesCount?: number): void {
  217. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  218. return;
  219. }
  220. var engine = this.getScene().getEngine();
  221. // Draw order
  222. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  223. }
  224. public registerBeforeRender(func: () => void): void {
  225. this._onBeforeRenderCallbacks.push(func);
  226. }
  227. public unregisterBeforeRender(func: () => void): void {
  228. var index = this._onBeforeRenderCallbacks.indexOf(func);
  229. if (index > -1) {
  230. this._onBeforeRenderCallbacks.splice(index, 1);
  231. }
  232. }
  233. public registerAfterRender(func: () => void): void {
  234. this._onAfterRenderCallbacks.push(func);
  235. }
  236. public unregisterAfterRender(func: () => void): void {
  237. var index = this._onAfterRenderCallbacks.indexOf(func);
  238. if (index > -1) {
  239. this._onAfterRenderCallbacks.splice(index, 1);
  240. }
  241. }
  242. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  243. var scene = this.getScene();
  244. this._batchCache.mustReturn = false;
  245. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  246. this._batchCache.visibleInstances[subMeshId] = null;
  247. if (this._visibleInstances) {
  248. var currentRenderId = scene.getRenderId();
  249. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  250. var selfRenderId = this._renderId;
  251. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  252. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  253. currentRenderId = this._visibleInstances.defaultRenderId;
  254. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  255. }
  256. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  257. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  258. this._batchCache.mustReturn = true;
  259. return this._batchCache;
  260. }
  261. if (currentRenderId !== selfRenderId) {
  262. this._batchCache.renderSelf[subMeshId] = false;
  263. }
  264. }
  265. this._renderIdForInstances[subMeshId] = currentRenderId;
  266. }
  267. return this._batchCache;
  268. }
  269. public _renderWithInstances(subMesh: SubMesh, wireFrame: boolean, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  270. var matricesCount = this.instances.length + 1;
  271. var bufferSize = matricesCount * 16 * 4;
  272. while (this._instancesBufferSize < bufferSize) {
  273. this._instancesBufferSize *= 2;
  274. }
  275. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  276. if (this._worldMatricesInstancesBuffer) {
  277. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  278. }
  279. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  280. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  281. }
  282. var offset = 0;
  283. var instancesCount = 0;
  284. var world = this.getWorldMatrix();
  285. if (batch.renderSelf[subMesh._id]) {
  286. world.copyToArray(this._worldMatricesInstancesArray, offset);
  287. offset += 16;
  288. instancesCount++;
  289. }
  290. var visibleInstances = batch.visibleInstances[subMesh._id];
  291. if (visibleInstances) {
  292. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  293. var instance = visibleInstances[instanceIndex];
  294. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  295. offset += 16;
  296. instancesCount++;
  297. }
  298. }
  299. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  300. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  301. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  302. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  303. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  304. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  305. this._draw(subMesh, !wireFrame, instancesCount);
  306. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  307. }
  308. public render(subMesh: SubMesh): void {
  309. var scene = this.getScene();
  310. // Managing instances
  311. var batch = this._getInstancesRenderList(subMesh._id);
  312. if (batch.mustReturn) {
  313. return;
  314. }
  315. // Checking geometry state
  316. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  317. return;
  318. }
  319. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  320. this._onBeforeRenderCallbacks[callbackIndex]();
  321. }
  322. var engine = scene.getEngine();
  323. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  324. // Material
  325. var effectiveMaterial = subMesh.getMaterial();
  326. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  327. return;
  328. }
  329. // Outline - step 1
  330. var savedDepthWrite = engine.getDepthWrite();
  331. if (this.renderOutline) {
  332. engine.setDepthWrite(false);
  333. scene.getOutlineRenderer().render(subMesh, batch);
  334. }
  335. effectiveMaterial._preBind();
  336. var effect = effectiveMaterial.getEffect();
  337. // Bind
  338. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  339. this._bind(subMesh, effect, wireFrame);
  340. var world = this.getWorldMatrix();
  341. effectiveMaterial.bind(world, this);
  342. // Instances rendering
  343. if (hardwareInstancedRendering) {
  344. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  345. } else {
  346. if (batch.renderSelf[subMesh._id]) {
  347. // Draw
  348. this._draw(subMesh, !wireFrame);
  349. }
  350. if (batch.visibleInstances[subMesh._id]) {
  351. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  352. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  353. // World
  354. world = instance.getWorldMatrix();
  355. effectiveMaterial.bindOnlyWorldMatrix(world);
  356. // Draw
  357. this._draw(subMesh, !wireFrame);
  358. }
  359. }
  360. }
  361. // Unbind
  362. effectiveMaterial.unbind();
  363. // Outline - step 2
  364. if (this.renderOutline && savedDepthWrite) {
  365. engine.setDepthWrite(true);
  366. engine.setColorWrite(false);
  367. scene.getOutlineRenderer().render(subMesh, batch);
  368. engine.setColorWrite(true);
  369. }
  370. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  371. this._onAfterRenderCallbacks[callbackIndex]();
  372. }
  373. }
  374. public getEmittedParticleSystems(): ParticleSystem[] {
  375. var results = new Array<ParticleSystem>();
  376. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  377. var particleSystem = this.getScene().particleSystems[index];
  378. if (particleSystem.emitter === this) {
  379. results.push(particleSystem);
  380. }
  381. }
  382. return results;
  383. }
  384. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  385. var results = new Array<ParticleSystem>();
  386. var descendants = this.getDescendants();
  387. descendants.push(this);
  388. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  389. var particleSystem = this.getScene().particleSystems[index];
  390. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  391. results.push(particleSystem);
  392. }
  393. }
  394. return results;
  395. }
  396. public getChildren(): Node[] {
  397. var results = [];
  398. for (var index = 0; index < this.getScene().meshes.length; index++) {
  399. var mesh = this.getScene().meshes[index];
  400. if (mesh.parent == this) {
  401. results.push(mesh);
  402. }
  403. }
  404. return results;
  405. }
  406. public _checkDelayState(): void {
  407. var that = this;
  408. var scene = this.getScene();
  409. if (this._geometry) {
  410. this._geometry.load(scene);
  411. }
  412. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  413. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  414. scene._addPendingData(that);
  415. BABYLON.Tools.LoadFile(this.delayLoadingFile, data => {
  416. this._delayLoadingFunction(JSON.parse(data), this);
  417. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  418. scene._removePendingData(this);
  419. }, () => { }, scene.database);
  420. }
  421. }
  422. public isInFrustum(frustumPlanes: Plane[]): boolean {
  423. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  424. return false;
  425. }
  426. if (!super.isInFrustum(frustumPlanes)) {
  427. return false;
  428. }
  429. this._checkDelayState();
  430. return true;
  431. }
  432. public setMaterialByID(id: string): void {
  433. var materials = this.getScene().materials;
  434. for (var index = 0; index < materials.length; index++) {
  435. if (materials[index].id == id) {
  436. this.material = materials[index];
  437. return;
  438. }
  439. }
  440. // Multi
  441. var multiMaterials = this.getScene().multiMaterials;
  442. for (index = 0; index < multiMaterials.length; index++) {
  443. if (multiMaterials[index].id == id) {
  444. this.material = multiMaterials[index];
  445. return;
  446. }
  447. }
  448. }
  449. public getAnimatables(): IAnimatable[] {
  450. var results = [];
  451. if (this.material) {
  452. results.push(this.material);
  453. }
  454. return results;
  455. }
  456. // Geometry
  457. public bakeTransformIntoVertices(transform: Matrix): void {
  458. // Position
  459. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  460. return;
  461. }
  462. this._resetPointsArrayCache();
  463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  464. var temp = [];
  465. for (var index = 0; index < data.length; index += 3) {
  466. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  467. }
  468. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  469. // Normals
  470. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  471. return;
  472. }
  473. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  474. for (index = 0; index < data.length; index += 3) {
  475. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  476. }
  477. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  478. }
  479. // Cache
  480. public _resetPointsArrayCache(): void {
  481. this._positions = null;
  482. }
  483. public _generatePointsArray(): boolean {
  484. if (this._positions)
  485. return true;
  486. this._positions = [];
  487. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  488. if (!data) {
  489. return false;
  490. }
  491. for (var index = 0; index < data.length; index += 3) {
  492. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  493. }
  494. return true;
  495. }
  496. // Clone
  497. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  498. var result = new BABYLON.Mesh(name, this.getScene());
  499. // Geometry
  500. this._geometry.applyToMesh(result);
  501. // Deep copy
  502. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  503. // Material
  504. result.material = this.material;
  505. // Parent
  506. if (newParent) {
  507. result.parent = newParent;
  508. }
  509. if (!doNotCloneChildren) {
  510. // Children
  511. for (var index = 0; index < this.getScene().meshes.length; index++) {
  512. var mesh = this.getScene().meshes[index];
  513. if (mesh.parent == this) {
  514. mesh.clone(mesh.name, result);
  515. }
  516. }
  517. }
  518. // Particles
  519. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  520. var system = this.getScene().particleSystems[index];
  521. if (system.emitter == this) {
  522. system.clone(system.name, result);
  523. }
  524. }
  525. result.computeWorldMatrix(true);
  526. return result;
  527. }
  528. // Dispose
  529. public dispose(doNotRecurse?: boolean): void {
  530. if (this._geometry) {
  531. this._geometry.releaseForMesh(this, true);
  532. }
  533. // Instances
  534. if (this._worldMatricesInstancesBuffer) {
  535. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  536. this._worldMatricesInstancesBuffer = null;
  537. }
  538. while (this.instances.length) {
  539. this.instances[0].dispose();
  540. }
  541. super.dispose(doNotRecurse);
  542. }
  543. // Geometric tools
  544. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number): void {
  545. var scene = this.getScene();
  546. var onload = img => {
  547. // Getting height map data
  548. var canvas = document.createElement("canvas");
  549. var context = canvas.getContext("2d");
  550. var heightMapWidth = img.width;
  551. var heightMapHeight = img.height;
  552. canvas.width = heightMapWidth;
  553. canvas.height = heightMapHeight;
  554. context.drawImage(img, 0, 0);
  555. // Create VertexData from map data
  556. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  557. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  558. };
  559. Tools.LoadImage(url, onload, () => { }, scene.database);
  560. }
  561. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  562. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  563. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  564. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  565. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  566. return;
  567. }
  568. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  569. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  570. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  571. var position = Vector3.Zero();
  572. var normal = Vector3.Zero();
  573. var uv = Vector2.Zero();
  574. for (var index = 0; index < positions.length; index += 3) {
  575. Vector3.FromArrayToRef(positions, index, position);
  576. Vector3.FromArrayToRef(normals, index, normal);
  577. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  578. // Compute height
  579. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  580. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  581. var pos = (u + v * heightMapWidth) * 4;
  582. var r = buffer[pos] / 255.0;
  583. var g = buffer[pos + 1] / 255.0;
  584. var b = buffer[pos + 2] / 255.0;
  585. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  586. normal.normalize();
  587. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  588. position = position.add(normal);
  589. position.toArray(positions, index);
  590. }
  591. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  592. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  593. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  594. }
  595. public convertToFlatShadedMesh(): void {
  596. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  597. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  598. var kinds = this.getVerticesDataKinds();
  599. var vbs = [];
  600. var data = [];
  601. var newdata = [];
  602. var updatableNormals = false;
  603. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  604. var kind = kinds[kindIndex];
  605. var vertexBuffer = this.getVertexBuffer(kind);
  606. if (kind === BABYLON.VertexBuffer.NormalKind) {
  607. updatableNormals = vertexBuffer.isUpdatable();
  608. kinds.splice(kindIndex, 1);
  609. kindIndex--;
  610. continue;
  611. }
  612. vbs[kind] = vertexBuffer;
  613. data[kind] = vbs[kind].getData();
  614. newdata[kind] = [];
  615. }
  616. // Save previous submeshes
  617. var previousSubmeshes = this.subMeshes.slice(0);
  618. var indices = this.getIndices();
  619. var totalIndices = this.getTotalIndices();
  620. // Generating unique vertices per face
  621. for (index = 0; index < totalIndices; index++) {
  622. var vertexIndex = indices[index];
  623. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  624. kind = kinds[kindIndex];
  625. var stride = vbs[kind].getStrideSize();
  626. for (var offset = 0; offset < stride; offset++) {
  627. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  628. }
  629. }
  630. }
  631. // Updating faces & normal
  632. var normals = [];
  633. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  634. for (var index = 0; index < totalIndices; index += 3) {
  635. indices[index] = index;
  636. indices[index + 1] = index + 1;
  637. indices[index + 2] = index + 2;
  638. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  639. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  640. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  641. var p1p2 = p1.subtract(p2);
  642. var p3p2 = p3.subtract(p2);
  643. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  644. // Store same normals for every vertex
  645. for (var localIndex = 0; localIndex < 3; localIndex++) {
  646. normals.push(normal.x);
  647. normals.push(normal.y);
  648. normals.push(normal.z);
  649. }
  650. }
  651. this.setIndices(indices);
  652. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  653. // Updating vertex buffers
  654. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  655. kind = kinds[kindIndex];
  656. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  657. }
  658. // Updating submeshes
  659. this.releaseSubMeshes();
  660. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  661. var previousOne = previousSubmeshes[submeshIndex];
  662. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  663. }
  664. this.synchronizeInstances();
  665. }
  666. // Instances
  667. public createInstance(name: string): InstancedMesh {
  668. return new InstancedMesh(name, this);
  669. }
  670. public synchronizeInstances(): void {
  671. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  672. var instance = this.instances[instanceIndex];
  673. instance._syncSubMeshes();
  674. }
  675. }
  676. // Statics
  677. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  678. var box = new BABYLON.Mesh(name, scene);
  679. var vertexData = BABYLON.VertexData.CreateBox(size);
  680. vertexData.applyToMesh(box, updatable);
  681. return box;
  682. }
  683. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  684. var sphere = new BABYLON.Mesh(name, scene);
  685. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  686. vertexData.applyToMesh(sphere, updatable);
  687. return sphere;
  688. }
  689. // Cylinder and cone (Code inspired by SharpDX.org)
  690. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any): Mesh {
  691. // subdivisions is a new parameter, we need to support old signature
  692. if (scene === undefined || !(scene instanceof Scene)) {
  693. if (scene !== undefined) {
  694. updatable = scene;
  695. }
  696. scene = <Scene>subdivisions;
  697. subdivisions = 1;
  698. }
  699. var cylinder = new BABYLON.Mesh(name, scene);
  700. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  701. vertexData.applyToMesh(cylinder, updatable);
  702. return cylinder;
  703. }
  704. // Torus (Code from SharpDX.org)
  705. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  706. var torus = new BABYLON.Mesh(name, scene);
  707. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  708. vertexData.applyToMesh(torus, updatable);
  709. return torus;
  710. }
  711. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  712. var torusKnot = new BABYLON.Mesh(name, scene);
  713. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  714. vertexData.applyToMesh(torusKnot, updatable);
  715. return torusKnot;
  716. }
  717. // Lines
  718. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  719. var lines = new LinesMesh(name, scene, updatable);
  720. var vertexData = BABYLON.VertexData.CreateLines(points);
  721. vertexData.applyToMesh(lines, updatable);
  722. return lines;
  723. }
  724. // Plane & ground
  725. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  726. var plane = new BABYLON.Mesh(name, scene);
  727. var vertexData = BABYLON.VertexData.CreatePlane(size);
  728. vertexData.applyToMesh(plane, updatable);
  729. return plane;
  730. }
  731. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  732. var ground = new BABYLON.GroundMesh(name, scene);
  733. ground._setReady(false);
  734. ground._subdivisions = subdivisions;
  735. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  736. vertexData.applyToMesh(ground, updatable);
  737. ground._setReady(true);
  738. return ground;
  739. }
  740. public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
  741. var tiledGround = new BABYLON.Mesh(name, scene);
  742. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  743. vertexData.applyToMesh(tiledGround, updatable);
  744. return tiledGround;
  745. }
  746. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): GroundMesh {
  747. var ground = new BABYLON.GroundMesh(name, scene);
  748. ground._subdivisions = subdivisions;
  749. ground._setReady(false);
  750. var onload = img => {
  751. // Getting height map data
  752. var canvas = document.createElement("canvas");
  753. var context = canvas.getContext("2d");
  754. var heightMapWidth = img.width;
  755. var heightMapHeight = img.height;
  756. canvas.width = heightMapWidth;
  757. canvas.height = heightMapHeight;
  758. context.drawImage(img, 0, 0);
  759. // Create VertexData from map data
  760. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  761. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  762. vertexData.applyToMesh(ground, updatable);
  763. ground._setReady(true);
  764. };
  765. Tools.LoadImage(url, onload, () => { }, scene.database);
  766. return ground;
  767. }
  768. // Tools
  769. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  770. var minVector = null;
  771. var maxVector = null;
  772. for (var i in meshes) {
  773. var mesh = meshes[i];
  774. var boundingBox = mesh.getBoundingInfo().boundingBox;
  775. if (!minVector) {
  776. minVector = boundingBox.minimumWorld;
  777. maxVector = boundingBox.maximumWorld;
  778. continue;
  779. }
  780. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  781. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  782. }
  783. return {
  784. min: minVector,
  785. max: maxVector
  786. };
  787. }
  788. public static Center(meshesOrMinMaxVector): Vector3 {
  789. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  790. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  791. }
  792. }
  793. }