babylon.mesh.js 55 KB

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