babylon.mesh.ts 48 KB

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