babylon.mesh.ts 38 KB

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