babylon.mesh.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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. // Consts
  9. public static _FRONTSIDE: number = 0;
  10. public static _BACKSIDE: number = 1;
  11. public static _DOUBLESIDE: number = 2;
  12. public static _DEFAULTSIDE: number = 0;
  13. public static get FRONTSIDE(): number {
  14. return Mesh._FRONTSIDE;
  15. }
  16. public static get BACKSIDE(): number {
  17. return Mesh._BACKSIDE;
  18. }
  19. public static get DOUBLESIDE(): number {
  20. return Mesh._DOUBLESIDE;
  21. }
  22. public static get DEFAULTSIDE(): number {
  23. return Mesh._DEFAULTSIDE;
  24. }
  25. // Members
  26. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  27. public instances = new Array<InstancedMesh>();
  28. public delayLoadingFile: string;
  29. public _binaryInfo: any;
  30. private _LODLevels = new Array<Internals.MeshLODLevel>();
  31. // Private
  32. public _geometry: Geometry;
  33. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  34. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  35. public _delayInfo; //ANY
  36. public _delayLoadingFunction: (any, Mesh) => void;
  37. public _visibleInstances: any = {};
  38. private _renderIdForInstances = new Array<number>();
  39. private _batchCache = new _InstancesBatch();
  40. private _worldMatricesInstancesBuffer: WebGLBuffer;
  41. private _worldMatricesInstancesArray: Float32Array;
  42. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  43. public _shouldGenerateFlatShading: boolean;
  44. private _preActivateId: number;
  45. /**
  46. * @constructor
  47. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  48. * @param {Scene} scene - The scene to add this mesh to.
  49. * @param {Node} parent - The parent of this mesh, if it has one
  50. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  51. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  52. * When false, achieved by calling a clone(), also passing False.
  53. * This will make creation of children, recursive.
  54. */
  55. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  56. super(name, scene);
  57. if (source) {
  58. // Geometry
  59. if (source._geometry) {
  60. source._geometry.applyToMesh(this);
  61. }
  62. // Deep copy
  63. Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  64. // Material
  65. this.material = source.material;
  66. if (!doNotCloneChildren) {
  67. // Children
  68. for (var index = 0; index < scene.meshes.length; index++) {
  69. var mesh = scene.meshes[index];
  70. if (mesh.parent === source) {
  71. // doNotCloneChildren is always going to be False
  72. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  73. }
  74. }
  75. }
  76. // Particles
  77. for (index = 0; index < scene.particleSystems.length; index++) {
  78. var system = scene.particleSystems[index];
  79. if (system.emitter === source) {
  80. system.clone(system.name, this);
  81. }
  82. }
  83. this.computeWorldMatrix(true);
  84. }
  85. // Parent
  86. if (parent !== null) {
  87. this.parent = parent;
  88. }
  89. }
  90. // Methods
  91. public get hasLODLevels(): boolean {
  92. return this._LODLevels.length > 0;
  93. }
  94. private _sortLODLevels(): void {
  95. this._LODLevels.sort((a, b) => {
  96. if (a.distance < b.distance) {
  97. return 1;
  98. }
  99. if (a.distance > b.distance) {
  100. return -1;
  101. }
  102. return 0;
  103. });
  104. }
  105. /**
  106. * Add a mesh as LOD level triggered at the given distance.
  107. * @param {number} distance - the distance from the center of the object to show this level
  108. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  109. * @return {BABYLON.Mesh} this mesh (for chaining)
  110. */
  111. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  112. if (mesh && mesh._masterMesh) {
  113. Tools.Warn("You cannot use a mesh as LOD level twice");
  114. return this;
  115. }
  116. var level = new Internals.MeshLODLevel(distance, mesh);
  117. this._LODLevels.push(level);
  118. if (mesh) {
  119. mesh._masterMesh = this;
  120. }
  121. this._sortLODLevels();
  122. return this;
  123. }
  124. public getLODLevelAtDistance(distance: number): Mesh {
  125. for (var index = 0; index < this._LODLevels.length; index++) {
  126. var level = this._LODLevels[index];
  127. if (level.distance === distance) {
  128. return level.mesh;
  129. }
  130. }
  131. return null;
  132. }
  133. /**
  134. * Remove a mesh from the LOD array
  135. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  136. * @return {BABYLON.Mesh} this mesh (for chaining)
  137. */
  138. public removeLODLevel(mesh: Mesh): Mesh {
  139. for (var index = 0; index < this._LODLevels.length; index++) {
  140. if (this._LODLevels[index].mesh === mesh) {
  141. this._LODLevels.splice(index, 1);
  142. if (mesh) {
  143. mesh._masterMesh = null;
  144. }
  145. }
  146. }
  147. this._sortLODLevels();
  148. return this;
  149. }
  150. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  151. if (!this._LODLevels || this._LODLevels.length === 0) {
  152. return this;
  153. }
  154. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  155. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  156. return this;
  157. }
  158. for (var index = 0; index < this._LODLevels.length; index++) {
  159. var level = this._LODLevels[index];
  160. if (level.distance < distanceToCamera) {
  161. if (level.mesh) {
  162. level.mesh._preActivate();
  163. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  164. }
  165. return level.mesh;
  166. }
  167. }
  168. return this;
  169. }
  170. public get geometry(): Geometry {
  171. return this._geometry;
  172. }
  173. public getTotalVertices(): number {
  174. if (!this._geometry) {
  175. return 0;
  176. }
  177. return this._geometry.getTotalVertices();
  178. }
  179. public getVerticesData(kind: string): number[] {
  180. if (!this._geometry) {
  181. return null;
  182. }
  183. return this._geometry.getVerticesData(kind);
  184. }
  185. public getVertexBuffer(kind): VertexBuffer {
  186. if (!this._geometry) {
  187. return undefined;
  188. }
  189. return this._geometry.getVertexBuffer(kind);
  190. }
  191. public isVerticesDataPresent(kind: string): boolean {
  192. if (!this._geometry) {
  193. if (this._delayInfo) {
  194. return this._delayInfo.indexOf(kind) !== -1;
  195. }
  196. return false;
  197. }
  198. return this._geometry.isVerticesDataPresent(kind);
  199. }
  200. public getVerticesDataKinds(): string[] {
  201. if (!this._geometry) {
  202. var result = [];
  203. if (this._delayInfo) {
  204. for (var kind in this._delayInfo) {
  205. result.push(kind);
  206. }
  207. }
  208. return result;
  209. }
  210. return this._geometry.getVerticesDataKinds();
  211. }
  212. public getTotalIndices(): number {
  213. if (!this._geometry) {
  214. return 0;
  215. }
  216. return this._geometry.getTotalIndices();
  217. }
  218. public getIndices(): number[] {
  219. if (!this._geometry) {
  220. return [];
  221. }
  222. return this._geometry.getIndices();
  223. }
  224. public get isBlocked(): boolean {
  225. return this._masterMesh !== null && this._masterMesh !== undefined;
  226. }
  227. public isReady(): boolean {
  228. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  229. return false;
  230. }
  231. return super.isReady();
  232. }
  233. public isDisposed(): boolean {
  234. return this._isDisposed;
  235. }
  236. // Methods
  237. public _preActivate(): void {
  238. var sceneRenderId = this.getScene().getRenderId();
  239. if (this._preActivateId === sceneRenderId) {
  240. return;
  241. }
  242. this._preActivateId = sceneRenderId;
  243. this._visibleInstances = null;
  244. }
  245. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  246. if (!this._visibleInstances) {
  247. this._visibleInstances = {};
  248. this._visibleInstances.defaultRenderId = renderId;
  249. this._visibleInstances.selfDefaultRenderId = this._renderId;
  250. }
  251. if (!this._visibleInstances[renderId]) {
  252. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  253. }
  254. this._visibleInstances[renderId].push(instance);
  255. }
  256. public refreshBoundingInfo(): void {
  257. var data = this.getVerticesData(VertexBuffer.PositionKind);
  258. if (data) {
  259. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  260. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  261. }
  262. if (this.subMeshes) {
  263. for (var index = 0; index < this.subMeshes.length; index++) {
  264. this.subMeshes[index].refreshBoundingInfo();
  265. }
  266. }
  267. this._updateBoundingInfo();
  268. }
  269. public _createGlobalSubMesh(): SubMesh {
  270. var totalVertices = this.getTotalVertices();
  271. if (!totalVertices || !this.getIndices()) {
  272. return null;
  273. }
  274. this.releaseSubMeshes();
  275. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  276. }
  277. public subdivide(count: number): void {
  278. if (count < 1) {
  279. return;
  280. }
  281. var totalIndices = this.getTotalIndices();
  282. var subdivisionSize = (totalIndices / count) | 0;
  283. var offset = 0;
  284. // Ensure that subdivisionSize is a multiple of 3
  285. while (subdivisionSize % 3 !== 0) {
  286. subdivisionSize++;
  287. }
  288. this.releaseSubMeshes();
  289. for (var index = 0; index < count; index++) {
  290. if (offset >= totalIndices) {
  291. break;
  292. }
  293. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  294. offset += subdivisionSize;
  295. }
  296. this.synchronizeInstances();
  297. }
  298. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  299. if (kind instanceof Array) {
  300. var temp = data;
  301. data = kind;
  302. kind = temp;
  303. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  304. }
  305. if (!this._geometry) {
  306. var vertexData = new VertexData();
  307. vertexData.set(data, kind);
  308. var scene = this.getScene();
  309. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  310. }
  311. else {
  312. this._geometry.setVerticesData(kind, data, updatable, stride);
  313. }
  314. }
  315. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  316. if (!this._geometry) {
  317. return;
  318. }
  319. if (!makeItUnique) {
  320. this._geometry.updateVerticesData(kind, data, updateExtends);
  321. }
  322. else {
  323. this.makeGeometryUnique();
  324. this.updateVerticesData(kind, data, updateExtends, false);
  325. }
  326. }
  327. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  328. if (!this._geometry) {
  329. return;
  330. }
  331. if (!makeItUnique) {
  332. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  333. }
  334. else {
  335. this.makeGeometryUnique();
  336. this.updateVerticesDataDirectly(kind, data, offset, false);
  337. }
  338. }
  339. public makeGeometryUnique() {
  340. if (!this._geometry) {
  341. return;
  342. }
  343. var geometry = this._geometry.copy(Geometry.RandomId());
  344. geometry.applyToMesh(this);
  345. }
  346. public setIndices(indices: number[], totalVertices?: number): void {
  347. if (!this._geometry) {
  348. var vertexData = new VertexData();
  349. vertexData.indices = indices;
  350. var scene = this.getScene();
  351. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  352. }
  353. else {
  354. this._geometry.setIndices(indices, totalVertices);
  355. }
  356. }
  357. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  358. var engine = this.getScene().getEngine();
  359. // Wireframe
  360. var indexToBind;
  361. switch (fillMode) {
  362. case Material.PointFillMode:
  363. indexToBind = null;
  364. break;
  365. case Material.WireFrameFillMode:
  366. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  367. break;
  368. default:
  369. case Material.TriangleFillMode:
  370. indexToBind = this._geometry.getIndexBuffer();
  371. break;
  372. }
  373. // VBOs
  374. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  375. }
  376. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  377. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  378. return;
  379. }
  380. var engine = this.getScene().getEngine();
  381. // Draw order
  382. switch (fillMode) {
  383. case Material.PointFillMode:
  384. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  385. break;
  386. case Material.WireFrameFillMode:
  387. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  388. break;
  389. default:
  390. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  391. }
  392. }
  393. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  394. this._onBeforeRenderCallbacks.push(func);
  395. }
  396. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  397. var index = this._onBeforeRenderCallbacks.indexOf(func);
  398. if (index > -1) {
  399. this._onBeforeRenderCallbacks.splice(index, 1);
  400. }
  401. }
  402. public registerAfterRender(func: () => void): void {
  403. this._onAfterRenderCallbacks.push(func);
  404. }
  405. public unregisterAfterRender(func: () => void): void {
  406. var index = this._onAfterRenderCallbacks.indexOf(func);
  407. if (index > -1) {
  408. this._onAfterRenderCallbacks.splice(index, 1);
  409. }
  410. }
  411. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  412. var scene = this.getScene();
  413. this._batchCache.mustReturn = false;
  414. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  415. this._batchCache.visibleInstances[subMeshId] = null;
  416. if (this._visibleInstances) {
  417. var currentRenderId = scene.getRenderId();
  418. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  419. var selfRenderId = this._renderId;
  420. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  421. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  422. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  423. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  424. }
  425. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  426. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  427. this._batchCache.mustReturn = true;
  428. return this._batchCache;
  429. }
  430. if (currentRenderId !== selfRenderId) {
  431. this._batchCache.renderSelf[subMeshId] = false;
  432. }
  433. }
  434. this._renderIdForInstances[subMeshId] = currentRenderId;
  435. }
  436. return this._batchCache;
  437. }
  438. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  439. var visibleInstances = batch.visibleInstances[subMesh._id];
  440. var matricesCount = visibleInstances.length + 1;
  441. var bufferSize = matricesCount * 16 * 4;
  442. while (this._instancesBufferSize < bufferSize) {
  443. this._instancesBufferSize *= 2;
  444. }
  445. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  446. if (this._worldMatricesInstancesBuffer) {
  447. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  448. }
  449. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  450. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  451. }
  452. var offset = 0;
  453. var instancesCount = 0;
  454. var world = this.getWorldMatrix();
  455. if (batch.renderSelf[subMesh._id]) {
  456. world.copyToArray(this._worldMatricesInstancesArray, offset);
  457. offset += 16;
  458. instancesCount++;
  459. }
  460. if (visibleInstances) {
  461. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  462. var instance = visibleInstances[instanceIndex];
  463. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  464. offset += 16;
  465. instancesCount++;
  466. }
  467. }
  468. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  469. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  470. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  471. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  472. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  473. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  474. this._draw(subMesh, fillMode, instancesCount);
  475. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  476. }
  477. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  478. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  479. var scene = this.getScene();
  480. var engine = scene.getEngine();
  481. if (hardwareInstancedRendering) {
  482. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  483. } else {
  484. if (batch.renderSelf[subMesh._id]) {
  485. // Draw
  486. if (onBeforeDraw) {
  487. onBeforeDraw(false, this.getWorldMatrix());
  488. }
  489. this._draw(subMesh, fillMode);
  490. }
  491. if (batch.visibleInstances[subMesh._id]) {
  492. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  493. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  494. // World
  495. var world = instance.getWorldMatrix();
  496. if (onBeforeDraw) {
  497. onBeforeDraw(true, world);
  498. }
  499. // Draw
  500. this._draw(subMesh, fillMode);
  501. }
  502. }
  503. }
  504. }
  505. public render(subMesh: SubMesh): void {
  506. var scene = this.getScene();
  507. // Managing instances
  508. var batch = this._getInstancesRenderList(subMesh._id);
  509. if (batch.mustReturn) {
  510. return;
  511. }
  512. // Checking geometry state
  513. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  514. return;
  515. }
  516. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  517. this._onBeforeRenderCallbacks[callbackIndex](this);
  518. }
  519. var engine = scene.getEngine();
  520. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  521. // Material
  522. var effectiveMaterial = subMesh.getMaterial();
  523. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  524. return;
  525. }
  526. // Outline - step 1
  527. var savedDepthWrite = engine.getDepthWrite();
  528. if (this.renderOutline) {
  529. engine.setDepthWrite(false);
  530. scene.getOutlineRenderer().render(subMesh, batch);
  531. engine.setDepthWrite(savedDepthWrite);
  532. }
  533. effectiveMaterial._preBind();
  534. var effect = effectiveMaterial.getEffect();
  535. // Bind
  536. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  537. this._bind(subMesh, effect, fillMode);
  538. var world = this.getWorldMatrix();
  539. effectiveMaterial.bind(world, this);
  540. // Draw
  541. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  542. (isInstance, world) => {
  543. if (isInstance) {
  544. effectiveMaterial.bindOnlyWorldMatrix(world);
  545. }
  546. });
  547. // Unbind
  548. effectiveMaterial.unbind();
  549. // Outline - step 2
  550. if (this.renderOutline && savedDepthWrite) {
  551. engine.setDepthWrite(true);
  552. engine.setColorWrite(false);
  553. scene.getOutlineRenderer().render(subMesh, batch);
  554. engine.setColorWrite(true);
  555. }
  556. // Overlay
  557. if (this.renderOverlay) {
  558. var currentMode = engine.getAlphaMode();
  559. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  560. scene.getOutlineRenderer().render(subMesh, batch, true);
  561. engine.setAlphaMode(currentMode);
  562. }
  563. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  564. this._onAfterRenderCallbacks[callbackIndex](this);
  565. }
  566. }
  567. public getEmittedParticleSystems(): ParticleSystem[] {
  568. var results = new Array<ParticleSystem>();
  569. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  570. var particleSystem = this.getScene().particleSystems[index];
  571. if (particleSystem.emitter === this) {
  572. results.push(particleSystem);
  573. }
  574. }
  575. return results;
  576. }
  577. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  578. var results = new Array<ParticleSystem>();
  579. var descendants = this.getDescendants();
  580. descendants.push(this);
  581. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  582. var particleSystem = this.getScene().particleSystems[index];
  583. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  584. results.push(particleSystem);
  585. }
  586. }
  587. return results;
  588. }
  589. public getChildren(): Node[] {
  590. var results = [];
  591. for (var index = 0; index < this.getScene().meshes.length; index++) {
  592. var mesh = this.getScene().meshes[index];
  593. if (mesh.parent === this) {
  594. results.push(mesh);
  595. }
  596. }
  597. return results;
  598. }
  599. public _checkDelayState(): void {
  600. var that = this;
  601. var scene = this.getScene();
  602. if (this._geometry) {
  603. this._geometry.load(scene);
  604. }
  605. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  606. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  607. scene._addPendingData(that);
  608. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  609. Tools.LoadFile(this.delayLoadingFile, data => {
  610. if (data instanceof ArrayBuffer) {
  611. this._delayLoadingFunction(data, this);
  612. }
  613. else {
  614. this._delayLoadingFunction(JSON.parse(data), this);
  615. }
  616. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  617. scene._removePendingData(this);
  618. },() => { }, scene.database, getBinaryData);
  619. }
  620. }
  621. public isInFrustum(frustumPlanes: Plane[]): boolean {
  622. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  623. return false;
  624. }
  625. if (!super.isInFrustum(frustumPlanes)) {
  626. return false;
  627. }
  628. this._checkDelayState();
  629. return true;
  630. }
  631. public setMaterialByID(id: string): void {
  632. var materials = this.getScene().materials;
  633. for (var index = 0; index < materials.length; index++) {
  634. if (materials[index].id === id) {
  635. this.material = materials[index];
  636. return;
  637. }
  638. }
  639. // Multi
  640. var multiMaterials = this.getScene().multiMaterials;
  641. for (index = 0; index < multiMaterials.length; index++) {
  642. if (multiMaterials[index].id === id) {
  643. this.material = multiMaterials[index];
  644. return;
  645. }
  646. }
  647. }
  648. public getAnimatables(): IAnimatable[] {
  649. var results = [];
  650. if (this.material) {
  651. results.push(this.material);
  652. }
  653. if (this.skeleton) {
  654. results.push(this.skeleton);
  655. }
  656. return results;
  657. }
  658. // Geometry
  659. public bakeTransformIntoVertices(transform: Matrix): void {
  660. // Position
  661. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  662. return;
  663. }
  664. this._resetPointsArrayCache();
  665. var data = this.getVerticesData(VertexBuffer.PositionKind);
  666. var temp = [];
  667. for (var index = 0; index < data.length; index += 3) {
  668. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  669. }
  670. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  671. // Normals
  672. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  673. return;
  674. }
  675. data = this.getVerticesData(VertexBuffer.NormalKind);
  676. for (index = 0; index < data.length; index += 3) {
  677. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  678. }
  679. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  680. }
  681. // Cache
  682. public _resetPointsArrayCache(): void {
  683. this._positions = null;
  684. }
  685. public _generatePointsArray(): boolean {
  686. if (this._positions)
  687. return true;
  688. this._positions = [];
  689. var data = this.getVerticesData(VertexBuffer.PositionKind);
  690. if (!data) {
  691. return false;
  692. }
  693. for (var index = 0; index < data.length; index += 3) {
  694. this._positions.push(Vector3.FromArray(data, index));
  695. }
  696. return true;
  697. }
  698. // Clone
  699. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  700. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  701. }
  702. // Dispose
  703. public dispose(doNotRecurse?: boolean): void {
  704. if (this._geometry) {
  705. this._geometry.releaseForMesh(this, true);
  706. }
  707. // Instances
  708. if (this._worldMatricesInstancesBuffer) {
  709. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  710. this._worldMatricesInstancesBuffer = null;
  711. }
  712. while (this.instances.length) {
  713. this.instances[0].dispose();
  714. }
  715. super.dispose(doNotRecurse);
  716. }
  717. // Geometric tools
  718. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  719. var scene = this.getScene();
  720. var onload = img => {
  721. // Getting height map data
  722. var canvas = document.createElement("canvas");
  723. var context = canvas.getContext("2d");
  724. var heightMapWidth = img.width;
  725. var heightMapHeight = img.height;
  726. canvas.width = heightMapWidth;
  727. canvas.height = heightMapHeight;
  728. context.drawImage(img, 0, 0);
  729. // Create VertexData from map data
  730. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  731. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  732. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  733. //execute success callback, if set
  734. if (onSuccess) {
  735. onSuccess(this);
  736. }
  737. };
  738. Tools.LoadImage(url, onload,() => { }, scene.database);
  739. }
  740. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  741. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  742. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  743. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  744. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  745. return;
  746. }
  747. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  748. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  749. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  750. var position = Vector3.Zero();
  751. var normal = Vector3.Zero();
  752. var uv = Vector2.Zero();
  753. for (var index = 0; index < positions.length; index += 3) {
  754. Vector3.FromArrayToRef(positions, index, position);
  755. Vector3.FromArrayToRef(normals, index, normal);
  756. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  757. // Compute height
  758. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  759. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  760. var pos = (u + v * heightMapWidth) * 4;
  761. var r = buffer[pos] / 255.0;
  762. var g = buffer[pos + 1] / 255.0;
  763. var b = buffer[pos + 2] / 255.0;
  764. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  765. normal.normalize();
  766. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  767. position = position.add(normal);
  768. position.toArray(positions, index);
  769. }
  770. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  771. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  772. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  773. }
  774. public convertToFlatShadedMesh(): void {
  775. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  776. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  777. var kinds = this.getVerticesDataKinds();
  778. var vbs = [];
  779. var data = [];
  780. var newdata = [];
  781. var updatableNormals = false;
  782. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  783. var kind = kinds[kindIndex];
  784. var vertexBuffer = this.getVertexBuffer(kind);
  785. if (kind === VertexBuffer.NormalKind) {
  786. updatableNormals = vertexBuffer.isUpdatable();
  787. kinds.splice(kindIndex, 1);
  788. kindIndex--;
  789. continue;
  790. }
  791. vbs[kind] = vertexBuffer;
  792. data[kind] = vbs[kind].getData();
  793. newdata[kind] = [];
  794. }
  795. // Save previous submeshes
  796. var previousSubmeshes = this.subMeshes.slice(0);
  797. var indices = this.getIndices();
  798. var totalIndices = this.getTotalIndices();
  799. // Generating unique vertices per face
  800. for (var index = 0; index < totalIndices; index++) {
  801. var vertexIndex = indices[index];
  802. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  803. kind = kinds[kindIndex];
  804. var stride = vbs[kind].getStrideSize();
  805. for (var offset = 0; offset < stride; offset++) {
  806. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  807. }
  808. }
  809. }
  810. // Updating faces & normal
  811. var normals = [];
  812. var positions = newdata[VertexBuffer.PositionKind];
  813. for (index = 0; index < totalIndices; index += 3) {
  814. indices[index] = index;
  815. indices[index + 1] = index + 1;
  816. indices[index + 2] = index + 2;
  817. var p1 = Vector3.FromArray(positions, index * 3);
  818. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  819. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  820. var p1p2 = p1.subtract(p2);
  821. var p3p2 = p3.subtract(p2);
  822. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  823. // Store same normals for every vertex
  824. for (var localIndex = 0; localIndex < 3; localIndex++) {
  825. normals.push(normal.x);
  826. normals.push(normal.y);
  827. normals.push(normal.z);
  828. }
  829. }
  830. this.setIndices(indices);
  831. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  832. // Updating vertex buffers
  833. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  834. kind = kinds[kindIndex];
  835. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  836. }
  837. // Updating submeshes
  838. this.releaseSubMeshes();
  839. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  840. var previousOne = previousSubmeshes[submeshIndex];
  841. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  842. }
  843. this.synchronizeInstances();
  844. }
  845. // Instances
  846. public createInstance(name: string): InstancedMesh {
  847. return new InstancedMesh(name, this);
  848. }
  849. public synchronizeInstances(): void {
  850. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  851. var instance = this.instances[instanceIndex];
  852. instance._syncSubMeshes();
  853. }
  854. }
  855. /**
  856. * Simplify the mesh according to the given array of settings.
  857. * Function will return immediately and will simplify async.
  858. * @param settings a collection of simplification settings.
  859. * @param parallelProcessing should all levels calculate parallel or one after the other.
  860. * @param type the type of simplification to run.
  861. * successCallback optional success callback to be called after the simplification finished processing all settings.
  862. */
  863. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  864. this.getScene().simplificationQueue.addTask({
  865. settings: settings,
  866. parallelProcessing: parallelProcessing,
  867. mesh: this,
  868. simplificationType: simplificationType,
  869. successCallback: successCallback
  870. });
  871. }
  872. // Statics
  873. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  874. var ribbon = new Mesh(name, scene);
  875. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  876. vertexData.applyToMesh(ribbon, updatable);
  877. return ribbon;
  878. }
  879. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  880. var box = new Mesh(name, scene);
  881. var vertexData = VertexData.CreateBox(size, sideOrientation);
  882. vertexData.applyToMesh(box, updatable);
  883. return box;
  884. }
  885. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  886. var sphere = new Mesh(name, scene);
  887. var vertexData = VertexData.CreateSphere(segments, diameter, sideOrientation);
  888. vertexData.applyToMesh(sphere, updatable);
  889. return sphere;
  890. }
  891. // Cylinder and cone (Code inspired by SharpDX.org)
  892. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  893. // subdivisions is a new parameter, we need to support old signature
  894. if (scene === undefined || !(scene instanceof Scene)) {
  895. if (scene !== undefined) {
  896. updatable = scene;
  897. }
  898. scene = <Scene>subdivisions;
  899. subdivisions = 1;
  900. }
  901. var cylinder = new Mesh(name, scene);
  902. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  903. vertexData.applyToMesh(cylinder, updatable);
  904. return cylinder;
  905. }
  906. // Torus (Code from SharpDX.org)
  907. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  908. var torus = new Mesh(name, scene);
  909. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  910. vertexData.applyToMesh(torus, updatable);
  911. return torus;
  912. }
  913. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  914. var torusKnot = new Mesh(name, scene);
  915. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  916. vertexData.applyToMesh(torusKnot, updatable);
  917. return torusKnot;
  918. }
  919. // Lines
  920. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  921. var lines = new LinesMesh(name, scene, updatable);
  922. var vertexData = VertexData.CreateLines(points);
  923. vertexData.applyToMesh(lines, updatable);
  924. return lines;
  925. }
  926. // Plane & ground
  927. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  928. var plane = new Mesh(name, scene);
  929. var vertexData = VertexData.CreatePlane(size, sideOrientation);
  930. vertexData.applyToMesh(plane, updatable);
  931. return plane;
  932. }
  933. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  934. var ground = new GroundMesh(name, scene);
  935. ground._setReady(false);
  936. ground._subdivisions = subdivisions;
  937. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  938. vertexData.applyToMesh(ground, updatable);
  939. ground._setReady(true);
  940. return ground;
  941. }
  942. 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 {
  943. var tiledGround = new Mesh(name, scene);
  944. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  945. vertexData.applyToMesh(tiledGround, updatable);
  946. return tiledGround;
  947. }
  948. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh {
  949. var ground = new GroundMesh(name, scene);
  950. ground._subdivisions = subdivisions;
  951. ground._setReady(false);
  952. var onload = img => {
  953. // Getting height map data
  954. var canvas = document.createElement("canvas");
  955. var context = canvas.getContext("2d");
  956. var heightMapWidth = img.width;
  957. var heightMapHeight = img.height;
  958. canvas.width = heightMapWidth;
  959. canvas.height = heightMapHeight;
  960. context.drawImage(img, 0, 0);
  961. // Create VertexData from map data
  962. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  963. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  964. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  965. vertexData.applyToMesh(ground, updatable);
  966. ground._setReady(true);
  967. //execute ready callback, if set
  968. if (onReady) {
  969. onReady(ground);
  970. }
  971. };
  972. Tools.LoadImage(url, onload,() => { }, scene.database);
  973. return ground;
  974. }
  975. public static CreateTube(name: string, path: Vector3[], radius: number, tesselation: number, radiusFunction: { (i: number, distance: number): number; }, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  976. var path3D: Path3D = new Path3D(path);
  977. var tangents: Vector3[] = path3D.getTangents();
  978. var normals: Vector3[] = path3D.getNormals();
  979. var distances: number[] = path3D.getDistances();
  980. var pi2: number = Math.PI * 2;
  981. var step: number = pi2 / tesselation;
  982. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  983. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  984. var circlePaths: Vector3[][] = [];
  985. var circlePath: Vector3[];
  986. var rad: number;
  987. var normal: Vector3;
  988. var rotated: Vector3;
  989. var rotationMatrix: Matrix;
  990. for (var i: number = 0; i < path.length; i++) {
  991. rad = radiusFunctionFinal(i, distances[i]); // current radius
  992. circlePath = []; // current circle array
  993. normal = normals[i]; // current normal
  994. for (var ang: number = 0; ang < pi2; ang += step) {
  995. rotationMatrix = Matrix.RotationAxis(tangents[i], ang);
  996. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  997. circlePath.push(rotated);
  998. }
  999. circlePaths.push(circlePath);
  1000. }
  1001. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  1002. return tube;
  1003. }
  1004. // Tools
  1005. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1006. var minVector: Vector3 = null;
  1007. var maxVector: Vector3 = null;
  1008. for (var i in meshes) {
  1009. var mesh = meshes[i];
  1010. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1011. if (!minVector) {
  1012. minVector = boundingBox.minimumWorld;
  1013. maxVector = boundingBox.maximumWorld;
  1014. continue;
  1015. }
  1016. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1017. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1018. }
  1019. return {
  1020. min: minVector,
  1021. max: maxVector
  1022. };
  1023. }
  1024. public static Center(meshesOrMinMaxVector): Vector3 {
  1025. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1026. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1027. }
  1028. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean): Mesh {
  1029. var source = meshes[0];
  1030. var material = source.material;
  1031. var scene = source.getScene();
  1032. if (!allow32BitsIndices) {
  1033. var totalVertices = 0;
  1034. // Counting vertices
  1035. for (var index = 0; index < meshes.length; index++) {
  1036. totalVertices += meshes[index].getTotalVertices();
  1037. if (totalVertices > 65536) {
  1038. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1039. return null;
  1040. }
  1041. }
  1042. }
  1043. // Merge
  1044. var vertexData = VertexData.ExtractFromMesh(source);
  1045. vertexData.transform(source.getWorldMatrix());
  1046. for (index = 1; index < meshes.length; index++) {
  1047. var otherVertexData = VertexData.ExtractFromMesh(meshes[index]);
  1048. otherVertexData.transform(meshes[index].getWorldMatrix());
  1049. vertexData.merge(otherVertexData);
  1050. }
  1051. var newMesh = new Mesh(source.name + "_merged", scene);
  1052. vertexData.applyToMesh(newMesh);
  1053. // Setting properties
  1054. newMesh.material = material;
  1055. newMesh.checkCollisions = source.checkCollisions;
  1056. // Cleaning
  1057. if (disposeSource) {
  1058. for (index = 0; index < meshes.length; index++) {
  1059. meshes[index].dispose();
  1060. }
  1061. }
  1062. return newMesh;
  1063. }
  1064. }
  1065. }