babylon.mesh.js 45 KB

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