babylon.mesh.js 48 KB

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