babylon.mesh.js 49 KB

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