babylon.mesh.ts 50 KB

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