babylon.mesh.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  718. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  719. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  720. //execute success callback, if set
  721. if (onSuccess) {
  722. onSuccess(_this);
  723. }
  724. };
  725. BABYLON.Tools.LoadImage(url, onload, function () {
  726. }, scene.database);
  727. };
  728. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  730. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  731. return;
  732. }
  733. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  734. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  735. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  736. var position = BABYLON.Vector3.Zero();
  737. var normal = BABYLON.Vector3.Zero();
  738. var uv = BABYLON.Vector2.Zero();
  739. for (var index = 0; index < positions.length; index += 3) {
  740. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  741. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  742. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  743. // Compute height
  744. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  745. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  746. var pos = (u + v * heightMapWidth) * 4;
  747. var r = buffer[pos] / 255.0;
  748. var g = buffer[pos + 1] / 255.0;
  749. var b = buffer[pos + 2] / 255.0;
  750. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  751. normal.normalize();
  752. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  753. position = position.add(normal);
  754. position.toArray(positions, index);
  755. }
  756. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  757. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  758. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  759. };
  760. Mesh.prototype.convertToFlatShadedMesh = function () {
  761. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  762. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  763. var kinds = this.getVerticesDataKinds();
  764. var vbs = [];
  765. var data = [];
  766. var newdata = [];
  767. var updatableNormals = false;
  768. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  769. var kind = kinds[kindIndex];
  770. var vertexBuffer = this.getVertexBuffer(kind);
  771. if (kind === BABYLON.VertexBuffer.NormalKind) {
  772. updatableNormals = vertexBuffer.isUpdatable();
  773. kinds.splice(kindIndex, 1);
  774. kindIndex--;
  775. continue;
  776. }
  777. vbs[kind] = vertexBuffer;
  778. data[kind] = vbs[kind].getData();
  779. newdata[kind] = [];
  780. }
  781. // Save previous submeshes
  782. var previousSubmeshes = this.subMeshes.slice(0);
  783. var indices = this.getIndices();
  784. var totalIndices = this.getTotalIndices();
  785. for (var index = 0; index < totalIndices; index++) {
  786. var vertexIndex = indices[index];
  787. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  788. kind = kinds[kindIndex];
  789. var stride = vbs[kind].getStrideSize();
  790. for (var offset = 0; offset < stride; offset++) {
  791. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  792. }
  793. }
  794. }
  795. // Updating faces & normal
  796. var normals = [];
  797. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  798. for (index = 0; index < totalIndices; index += 3) {
  799. indices[index] = index;
  800. indices[index + 1] = index + 1;
  801. indices[index + 2] = index + 2;
  802. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  803. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  804. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  805. var p1p2 = p1.subtract(p2);
  806. var p3p2 = p3.subtract(p2);
  807. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  808. for (var localIndex = 0; localIndex < 3; localIndex++) {
  809. normals.push(normal.x);
  810. normals.push(normal.y);
  811. normals.push(normal.z);
  812. }
  813. }
  814. this.setIndices(indices);
  815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  816. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  817. kind = kinds[kindIndex];
  818. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  819. }
  820. // Updating submeshes
  821. this.releaseSubMeshes();
  822. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  823. var previousOne = previousSubmeshes[submeshIndex];
  824. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  825. }
  826. this.synchronizeInstances();
  827. };
  828. // Instances
  829. Mesh.prototype.createInstance = function (name) {
  830. return new BABYLON.InstancedMesh(name, this);
  831. };
  832. Mesh.prototype.synchronizeInstances = function () {
  833. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  834. var instance = this.instances[instanceIndex];
  835. instance._syncSubMeshes();
  836. }
  837. };
  838. /**
  839. * Simplify the mesh according to the given array of settings.
  840. * Function will return immediately and will simplify async.
  841. * @param settings a collection of simplification settings.
  842. * @param parallelProcessing should all levels calculate parallel or one after the other.
  843. * @param type the type of simplification to run.
  844. * successCallback optional success callback to be called after the simplification finished processing all settings.
  845. */
  846. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  847. var _this = this;
  848. if (parallelProcessing === void 0) { parallelProcessing = true; }
  849. if (type === void 0) { type = 0 /* QUADRATIC */; }
  850. var getSimplifier = function () {
  851. switch (type) {
  852. case 0 /* QUADRATIC */:
  853. default:
  854. return new BABYLON.QuadraticErrorSimplification(_this);
  855. }
  856. };
  857. if (parallelProcessing) {
  858. //parallel simplifier
  859. settings.forEach(function (setting) {
  860. var simplifier = getSimplifier();
  861. simplifier.simplify(setting, function (newMesh) {
  862. _this.addLODLevel(setting.distance, newMesh);
  863. //check if it is the last
  864. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  865. //all done, run the success callback.
  866. successCallback();
  867. }
  868. });
  869. });
  870. }
  871. else {
  872. //single simplifier.
  873. var simplifier = getSimplifier();
  874. var runDecimation = function (setting, callback) {
  875. simplifier.simplify(setting, function (newMesh) {
  876. _this.addLODLevel(setting.distance, newMesh);
  877. //run the next quality level
  878. callback();
  879. });
  880. };
  881. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  882. runDecimation(settings[loop.index], function () {
  883. loop.executeNext();
  884. });
  885. }, function () {
  886. //execution ended, run the success callback.
  887. if (successCallback) {
  888. successCallback();
  889. }
  890. });
  891. }
  892. };
  893. // Statics
  894. Mesh.CreateBox = function (name, size, scene, updatable) {
  895. var box = new Mesh(name, scene);
  896. var vertexData = BABYLON.VertexData.CreateBox(size);
  897. vertexData.applyToMesh(box, updatable);
  898. return box;
  899. };
  900. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  901. var sphere = new Mesh(name, scene);
  902. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  903. vertexData.applyToMesh(sphere, updatable);
  904. return sphere;
  905. };
  906. // Cylinder and cone (Code inspired by SharpDX.org)
  907. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  908. // subdivisions is a new parameter, we need to support old signature
  909. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  910. if (scene !== undefined) {
  911. updatable = scene;
  912. }
  913. scene = subdivisions;
  914. subdivisions = 1;
  915. }
  916. var cylinder = new Mesh(name, scene);
  917. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  918. vertexData.applyToMesh(cylinder, updatable);
  919. return cylinder;
  920. };
  921. // Torus (Code from SharpDX.org)
  922. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  923. var torus = new Mesh(name, scene);
  924. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  925. vertexData.applyToMesh(torus, updatable);
  926. return torus;
  927. };
  928. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  929. var torusKnot = new Mesh(name, scene);
  930. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  931. vertexData.applyToMesh(torusKnot, updatable);
  932. return torusKnot;
  933. };
  934. // Lines
  935. Mesh.CreateLines = function (name, points, scene, updatable) {
  936. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  937. var vertexData = BABYLON.VertexData.CreateLines(points);
  938. vertexData.applyToMesh(lines, updatable);
  939. return lines;
  940. };
  941. // Plane & ground
  942. Mesh.CreatePlane = function (name, size, scene, updatable) {
  943. var plane = new Mesh(name, scene);
  944. var vertexData = BABYLON.VertexData.CreatePlane(size);
  945. vertexData.applyToMesh(plane, updatable);
  946. return plane;
  947. };
  948. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  949. var ground = new BABYLON.GroundMesh(name, scene);
  950. ground._setReady(false);
  951. ground._subdivisions = subdivisions;
  952. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  953. vertexData.applyToMesh(ground, updatable);
  954. ground._setReady(true);
  955. return ground;
  956. };
  957. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  958. var tiledGround = new Mesh(name, scene);
  959. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  960. vertexData.applyToMesh(tiledGround, updatable);
  961. return tiledGround;
  962. };
  963. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  964. var ground = new BABYLON.GroundMesh(name, scene);
  965. ground._subdivisions = subdivisions;
  966. ground._setReady(false);
  967. var onload = function (img) {
  968. // Getting height map data
  969. var canvas = document.createElement("canvas");
  970. var context = canvas.getContext("2d");
  971. var heightMapWidth = img.width;
  972. var heightMapHeight = img.height;
  973. canvas.width = heightMapWidth;
  974. canvas.height = heightMapHeight;
  975. context.drawImage(img, 0, 0);
  976. // Create VertexData from map data
  977. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  978. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  979. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  980. vertexData.applyToMesh(ground, updatable);
  981. ground._setReady(true);
  982. //execute ready callback, if set
  983. if (onReady) {
  984. onReady(ground);
  985. }
  986. };
  987. BABYLON.Tools.LoadImage(url, onload, function () {
  988. }, scene.database);
  989. return ground;
  990. };
  991. // Tools
  992. Mesh.MinMax = function (meshes) {
  993. var minVector = null;
  994. var maxVector = null;
  995. for (var i in meshes) {
  996. var mesh = meshes[i];
  997. var boundingBox = mesh.getBoundingInfo().boundingBox;
  998. if (!minVector) {
  999. minVector = boundingBox.minimumWorld;
  1000. maxVector = boundingBox.maximumWorld;
  1001. continue;
  1002. }
  1003. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1004. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1005. }
  1006. return {
  1007. min: minVector,
  1008. max: maxVector
  1009. };
  1010. };
  1011. Mesh.Center = function (meshesOrMinMaxVector) {
  1012. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1013. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  1014. };
  1015. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  1016. if (disposeSource === void 0) { disposeSource = true; }
  1017. var source = meshes[0];
  1018. var material = source.material;
  1019. var scene = source.getScene();
  1020. if (!allow32BitsIndices) {
  1021. var totalVertices = 0;
  1022. for (var index = 0; index < meshes.length; index++) {
  1023. totalVertices += meshes[index].getTotalVertices();
  1024. if (totalVertices > 65536) {
  1025. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1026. return null;
  1027. }
  1028. }
  1029. }
  1030. // Merge
  1031. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  1032. vertexData.transform(source.getWorldMatrix());
  1033. for (index = 1; index < meshes.length; index++) {
  1034. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  1035. otherVertexData.transform(meshes[index].getWorldMatrix());
  1036. vertexData.merge(otherVertexData);
  1037. }
  1038. var newMesh = new Mesh(source.name + "_merged", scene);
  1039. vertexData.applyToMesh(newMesh);
  1040. // Setting properties
  1041. newMesh.material = material;
  1042. newMesh.checkCollisions = source.checkCollisions;
  1043. // Cleaning
  1044. if (disposeSource) {
  1045. for (index = 0; index < meshes.length; index++) {
  1046. meshes[index].dispose();
  1047. }
  1048. }
  1049. return newMesh;
  1050. };
  1051. return Mesh;
  1052. })(BABYLON.AbstractMesh);
  1053. BABYLON.Mesh = Mesh;
  1054. })(BABYLON || (BABYLON = {}));
  1055. //# sourceMappingURL=babylon.mesh.js.map