babylon.mesh.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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. this._sideOrientation = Mesh._DEFAULTSIDE;
  44. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  45. if (source) {
  46. // Geometry
  47. if (source._geometry) {
  48. source._geometry.applyToMesh(this);
  49. }
  50. // Deep copy
  51. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  52. // Material
  53. this.material = source.material;
  54. if (!doNotCloneChildren) {
  55. for (var index = 0; index < scene.meshes.length; index++) {
  56. var mesh = scene.meshes[index];
  57. if (mesh.parent === source) {
  58. // doNotCloneChildren is always going to be False
  59. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  60. }
  61. }
  62. }
  63. for (index = 0; index < scene.particleSystems.length; index++) {
  64. var system = scene.particleSystems[index];
  65. if (system.emitter === source) {
  66. system.clone(system.name, this);
  67. }
  68. }
  69. this.computeWorldMatrix(true);
  70. }
  71. // Parent
  72. if (parent !== null) {
  73. this.parent = parent;
  74. }
  75. }
  76. Object.defineProperty(Mesh, "FRONTSIDE", {
  77. get: function () {
  78. return Mesh._FRONTSIDE;
  79. },
  80. enumerable: true,
  81. configurable: true
  82. });
  83. Object.defineProperty(Mesh, "BACKSIDE", {
  84. get: function () {
  85. return Mesh._BACKSIDE;
  86. },
  87. enumerable: true,
  88. configurable: true
  89. });
  90. Object.defineProperty(Mesh, "DOUBLESIDE", {
  91. get: function () {
  92. return Mesh._DOUBLESIDE;
  93. },
  94. enumerable: true,
  95. configurable: true
  96. });
  97. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  98. get: function () {
  99. return Mesh._DEFAULTSIDE;
  100. },
  101. enumerable: true,
  102. configurable: true
  103. });
  104. Object.defineProperty(Mesh, "NO_CAP", {
  105. get: function () {
  106. return Mesh._NO_CAP;
  107. },
  108. enumerable: true,
  109. configurable: true
  110. });
  111. Object.defineProperty(Mesh, "CAP_START", {
  112. get: function () {
  113. return Mesh._CAP_START;
  114. },
  115. enumerable: true,
  116. configurable: true
  117. });
  118. Object.defineProperty(Mesh, "CAP_END", {
  119. get: function () {
  120. return Mesh._CAP_END;
  121. },
  122. enumerable: true,
  123. configurable: true
  124. });
  125. Object.defineProperty(Mesh, "CAP_ALL", {
  126. get: function () {
  127. return Mesh._CAP_ALL;
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  133. // Methods
  134. get: function () {
  135. return this._LODLevels.length > 0;
  136. },
  137. enumerable: true,
  138. configurable: true
  139. });
  140. Mesh.prototype._sortLODLevels = function () {
  141. this._LODLevels.sort(function (a, b) {
  142. if (a.distance < b.distance) {
  143. return 1;
  144. }
  145. if (a.distance > b.distance) {
  146. return -1;
  147. }
  148. return 0;
  149. });
  150. };
  151. /**
  152. * Add a mesh as LOD level triggered at the given distance.
  153. * @param {number} distance - the distance from the center of the object to show this level
  154. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  155. * @return {BABYLON.Mesh} this mesh (for chaining)
  156. */
  157. Mesh.prototype.addLODLevel = function (distance, mesh) {
  158. if (mesh && mesh._masterMesh) {
  159. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  160. return this;
  161. }
  162. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  163. this._LODLevels.push(level);
  164. if (mesh) {
  165. mesh._masterMesh = this;
  166. }
  167. this._sortLODLevels();
  168. return this;
  169. };
  170. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  171. for (var index = 0; index < this._LODLevels.length; index++) {
  172. var level = this._LODLevels[index];
  173. if (level.distance === distance) {
  174. return level.mesh;
  175. }
  176. }
  177. return null;
  178. };
  179. /**
  180. * Remove a mesh from the LOD array
  181. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  182. * @return {BABYLON.Mesh} this mesh (for chaining)
  183. */
  184. Mesh.prototype.removeLODLevel = function (mesh) {
  185. for (var index = 0; index < this._LODLevels.length; index++) {
  186. if (this._LODLevels[index].mesh === mesh) {
  187. this._LODLevels.splice(index, 1);
  188. if (mesh) {
  189. mesh._masterMesh = null;
  190. }
  191. }
  192. }
  193. this._sortLODLevels();
  194. return this;
  195. };
  196. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  197. if (!this._LODLevels || this._LODLevels.length === 0) {
  198. return this;
  199. }
  200. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  201. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  202. if (this.onLODLevelSelection) {
  203. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  204. }
  205. return this;
  206. }
  207. for (var index = 0; index < this._LODLevels.length; index++) {
  208. var level = this._LODLevels[index];
  209. if (level.distance < distanceToCamera) {
  210. if (level.mesh) {
  211. level.mesh._preActivate();
  212. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  213. }
  214. if (this.onLODLevelSelection) {
  215. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  216. }
  217. return level.mesh;
  218. }
  219. }
  220. if (this.onLODLevelSelection) {
  221. this.onLODLevelSelection(distanceToCamera, this, this);
  222. }
  223. return this;
  224. };
  225. Object.defineProperty(Mesh.prototype, "geometry", {
  226. get: function () {
  227. return this._geometry;
  228. },
  229. enumerable: true,
  230. configurable: true
  231. });
  232. Mesh.prototype.getTotalVertices = function () {
  233. if (!this._geometry) {
  234. return 0;
  235. }
  236. return this._geometry.getTotalVertices();
  237. };
  238. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  239. if (!this._geometry) {
  240. return null;
  241. }
  242. return this._geometry.getVerticesData(kind, copyWhenShared);
  243. };
  244. Mesh.prototype.getVertexBuffer = function (kind) {
  245. if (!this._geometry) {
  246. return undefined;
  247. }
  248. return this._geometry.getVertexBuffer(kind);
  249. };
  250. Mesh.prototype.isVerticesDataPresent = function (kind) {
  251. if (!this._geometry) {
  252. if (this._delayInfo) {
  253. return this._delayInfo.indexOf(kind) !== -1;
  254. }
  255. return false;
  256. }
  257. return this._geometry.isVerticesDataPresent(kind);
  258. };
  259. Mesh.prototype.getVerticesDataKinds = function () {
  260. if (!this._geometry) {
  261. var result = [];
  262. if (this._delayInfo) {
  263. for (var kind in this._delayInfo) {
  264. result.push(kind);
  265. }
  266. }
  267. return result;
  268. }
  269. return this._geometry.getVerticesDataKinds();
  270. };
  271. Mesh.prototype.getTotalIndices = function () {
  272. if (!this._geometry) {
  273. return 0;
  274. }
  275. return this._geometry.getTotalIndices();
  276. };
  277. Mesh.prototype.getIndices = function (copyWhenShared) {
  278. if (!this._geometry) {
  279. return [];
  280. }
  281. return this._geometry.getIndices(copyWhenShared);
  282. };
  283. Object.defineProperty(Mesh.prototype, "isBlocked", {
  284. get: function () {
  285. return this._masterMesh !== null && this._masterMesh !== undefined;
  286. },
  287. enumerable: true,
  288. configurable: true
  289. });
  290. Mesh.prototype.isReady = function () {
  291. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  292. return false;
  293. }
  294. return _super.prototype.isReady.call(this);
  295. };
  296. Mesh.prototype.isDisposed = function () {
  297. return this._isDisposed;
  298. };
  299. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  300. get: function () {
  301. return this._sideOrientation;
  302. },
  303. set: function (sideO) {
  304. this._sideOrientation = sideO;
  305. },
  306. enumerable: true,
  307. configurable: true
  308. });
  309. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  310. get: function () {
  311. return this._areNormalsFrozen;
  312. },
  313. enumerable: true,
  314. configurable: true
  315. });
  316. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  317. Mesh.prototype.freezeNormals = function () {
  318. this._areNormalsFrozen = true;
  319. };
  320. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  321. Mesh.prototype.unfreezeNormals = function () {
  322. this._areNormalsFrozen = false;
  323. };
  324. // Methods
  325. Mesh.prototype._preActivate = function () {
  326. var sceneRenderId = this.getScene().getRenderId();
  327. if (this._preActivateId === sceneRenderId) {
  328. return;
  329. }
  330. this._preActivateId = sceneRenderId;
  331. this._visibleInstances = null;
  332. };
  333. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  334. if (!this._visibleInstances) {
  335. this._visibleInstances = {};
  336. this._visibleInstances.defaultRenderId = renderId;
  337. this._visibleInstances.selfDefaultRenderId = this._renderId;
  338. }
  339. if (!this._visibleInstances[renderId]) {
  340. this._visibleInstances[renderId] = new Array();
  341. }
  342. this._visibleInstances[renderId].push(instance);
  343. };
  344. Mesh.prototype.refreshBoundingInfo = function () {
  345. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  346. if (data) {
  347. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  348. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  349. }
  350. if (this.subMeshes) {
  351. for (var index = 0; index < this.subMeshes.length; index++) {
  352. this.subMeshes[index].refreshBoundingInfo();
  353. }
  354. }
  355. this._updateBoundingInfo();
  356. };
  357. Mesh.prototype._createGlobalSubMesh = function () {
  358. var totalVertices = this.getTotalVertices();
  359. if (!totalVertices || !this.getIndices()) {
  360. return null;
  361. }
  362. this.releaseSubMeshes();
  363. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  364. };
  365. Mesh.prototype.subdivide = function (count) {
  366. if (count < 1) {
  367. return;
  368. }
  369. var totalIndices = this.getTotalIndices();
  370. var subdivisionSize = (totalIndices / count) | 0;
  371. var offset = 0;
  372. while (subdivisionSize % 3 !== 0) {
  373. subdivisionSize++;
  374. }
  375. this.releaseSubMeshes();
  376. for (var index = 0; index < count; index++) {
  377. if (offset >= totalIndices) {
  378. break;
  379. }
  380. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  381. offset += subdivisionSize;
  382. }
  383. this.synchronizeInstances();
  384. };
  385. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  386. if (kind instanceof Array) {
  387. var temp = data;
  388. data = kind;
  389. kind = temp;
  390. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  391. }
  392. if (!this._geometry) {
  393. var vertexData = new BABYLON.VertexData();
  394. vertexData.set(data, kind);
  395. var scene = this.getScene();
  396. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  397. }
  398. else {
  399. this._geometry.setVerticesData(kind, data, updatable, stride);
  400. }
  401. };
  402. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  403. if (!this._geometry) {
  404. return;
  405. }
  406. if (!makeItUnique) {
  407. this._geometry.updateVerticesData(kind, data, updateExtends);
  408. }
  409. else {
  410. this.makeGeometryUnique();
  411. this.updateVerticesData(kind, data, updateExtends, false);
  412. }
  413. };
  414. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  415. if (!this._geometry) {
  416. return;
  417. }
  418. if (!makeItUnique) {
  419. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  420. }
  421. else {
  422. this.makeGeometryUnique();
  423. this.updateVerticesDataDirectly(kind, data, offset, false);
  424. }
  425. };
  426. // Mesh positions update function :
  427. // updates the mesh positions according to the positionFunction returned values.
  428. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  429. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  430. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  431. if (computeNormals === void 0) { computeNormals = true; }
  432. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  433. positionFunction(positions);
  434. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  435. if (computeNormals) {
  436. var indices = this.getIndices();
  437. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  438. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  439. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  440. }
  441. };
  442. Mesh.prototype.makeGeometryUnique = function () {
  443. if (!this._geometry) {
  444. return;
  445. }
  446. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  447. geometry.applyToMesh(this);
  448. };
  449. Mesh.prototype.setIndices = function (indices, totalVertices) {
  450. if (!this._geometry) {
  451. var vertexData = new BABYLON.VertexData();
  452. vertexData.indices = indices;
  453. var scene = this.getScene();
  454. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  455. }
  456. else {
  457. this._geometry.setIndices(indices, totalVertices);
  458. }
  459. };
  460. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  461. var engine = this.getScene().getEngine();
  462. // Wireframe
  463. var indexToBind;
  464. switch (fillMode) {
  465. case BABYLON.Material.PointFillMode:
  466. indexToBind = null;
  467. break;
  468. case BABYLON.Material.WireFrameFillMode:
  469. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  470. break;
  471. default:
  472. case BABYLON.Material.TriangleFillMode:
  473. indexToBind = this._geometry.getIndexBuffer();
  474. break;
  475. }
  476. // VBOs
  477. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  478. };
  479. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  480. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  481. return;
  482. }
  483. var engine = this.getScene().getEngine();
  484. switch (fillMode) {
  485. case BABYLON.Material.PointFillMode:
  486. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  487. break;
  488. case BABYLON.Material.WireFrameFillMode:
  489. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  490. break;
  491. default:
  492. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  493. }
  494. };
  495. Mesh.prototype.registerBeforeRender = function (func) {
  496. this._onBeforeRenderCallbacks.push(func);
  497. };
  498. Mesh.prototype.unregisterBeforeRender = function (func) {
  499. var index = this._onBeforeRenderCallbacks.indexOf(func);
  500. if (index > -1) {
  501. this._onBeforeRenderCallbacks.splice(index, 1);
  502. }
  503. };
  504. Mesh.prototype.registerAfterRender = function (func) {
  505. this._onAfterRenderCallbacks.push(func);
  506. };
  507. Mesh.prototype.unregisterAfterRender = function (func) {
  508. var index = this._onAfterRenderCallbacks.indexOf(func);
  509. if (index > -1) {
  510. this._onAfterRenderCallbacks.splice(index, 1);
  511. }
  512. };
  513. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  514. var scene = this.getScene();
  515. this._batchCache.mustReturn = false;
  516. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  517. this._batchCache.visibleInstances[subMeshId] = null;
  518. if (this._visibleInstances) {
  519. var currentRenderId = scene.getRenderId();
  520. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  521. var selfRenderId = this._renderId;
  522. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  523. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  524. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  525. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  526. }
  527. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  528. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  529. this._batchCache.mustReturn = true;
  530. return this._batchCache;
  531. }
  532. if (currentRenderId !== selfRenderId) {
  533. this._batchCache.renderSelf[subMeshId] = false;
  534. }
  535. }
  536. this._renderIdForInstances[subMeshId] = currentRenderId;
  537. }
  538. return this._batchCache;
  539. };
  540. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  541. var visibleInstances = batch.visibleInstances[subMesh._id];
  542. var matricesCount = visibleInstances.length + 1;
  543. var bufferSize = matricesCount * 16 * 4;
  544. while (this._instancesBufferSize < bufferSize) {
  545. this._instancesBufferSize *= 2;
  546. }
  547. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  548. if (this._worldMatricesInstancesBuffer) {
  549. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  550. }
  551. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  552. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  553. }
  554. var offset = 0;
  555. var instancesCount = 0;
  556. var world = this.getWorldMatrix();
  557. if (batch.renderSelf[subMesh._id]) {
  558. world.copyToArray(this._worldMatricesInstancesArray, offset);
  559. offset += 16;
  560. instancesCount++;
  561. }
  562. if (visibleInstances) {
  563. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  564. var instance = visibleInstances[instanceIndex];
  565. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  566. offset += 16;
  567. instancesCount++;
  568. }
  569. }
  570. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  571. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  572. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  573. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  574. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  575. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  576. this._draw(subMesh, fillMode, instancesCount);
  577. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  578. };
  579. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  580. var scene = this.getScene();
  581. var engine = scene.getEngine();
  582. if (hardwareInstancedRendering) {
  583. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  584. }
  585. else {
  586. if (batch.renderSelf[subMesh._id]) {
  587. // Draw
  588. if (onBeforeDraw) {
  589. onBeforeDraw(false, this.getWorldMatrix());
  590. }
  591. this._draw(subMesh, fillMode);
  592. }
  593. if (batch.visibleInstances[subMesh._id]) {
  594. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  595. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  596. // World
  597. var world = instance.getWorldMatrix();
  598. if (onBeforeDraw) {
  599. onBeforeDraw(true, world);
  600. }
  601. // Draw
  602. this._draw(subMesh, fillMode);
  603. }
  604. }
  605. }
  606. };
  607. Mesh.prototype.render = function (subMesh) {
  608. var scene = this.getScene();
  609. // Managing instances
  610. var batch = this._getInstancesRenderList(subMesh._id);
  611. if (batch.mustReturn) {
  612. return;
  613. }
  614. // Checking geometry state
  615. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  616. return;
  617. }
  618. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  619. this._onBeforeRenderCallbacks[callbackIndex](this);
  620. }
  621. var engine = scene.getEngine();
  622. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  623. // Material
  624. var effectiveMaterial = subMesh.getMaterial();
  625. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  626. return;
  627. }
  628. // Outline - step 1
  629. var savedDepthWrite = engine.getDepthWrite();
  630. if (this.renderOutline) {
  631. engine.setDepthWrite(false);
  632. scene.getOutlineRenderer().render(subMesh, batch);
  633. engine.setDepthWrite(savedDepthWrite);
  634. }
  635. effectiveMaterial._preBind();
  636. var effect = effectiveMaterial.getEffect();
  637. // Bind
  638. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  639. this._bind(subMesh, effect, fillMode);
  640. var world = this.getWorldMatrix();
  641. effectiveMaterial.bind(world, this);
  642. // Draw
  643. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  644. if (isInstance) {
  645. effectiveMaterial.bindOnlyWorldMatrix(world);
  646. }
  647. });
  648. // Unbind
  649. effectiveMaterial.unbind();
  650. // Outline - step 2
  651. if (this.renderOutline && savedDepthWrite) {
  652. engine.setDepthWrite(true);
  653. engine.setColorWrite(false);
  654. scene.getOutlineRenderer().render(subMesh, batch);
  655. engine.setColorWrite(true);
  656. }
  657. // Overlay
  658. if (this.renderOverlay) {
  659. var currentMode = engine.getAlphaMode();
  660. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  661. scene.getOutlineRenderer().render(subMesh, batch, true);
  662. engine.setAlphaMode(currentMode);
  663. }
  664. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  665. this._onAfterRenderCallbacks[callbackIndex](this);
  666. }
  667. };
  668. Mesh.prototype.getEmittedParticleSystems = function () {
  669. var results = new Array();
  670. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  671. var particleSystem = this.getScene().particleSystems[index];
  672. if (particleSystem.emitter === this) {
  673. results.push(particleSystem);
  674. }
  675. }
  676. return results;
  677. };
  678. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  679. var results = new Array();
  680. var descendants = this.getDescendants();
  681. descendants.push(this);
  682. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  683. var particleSystem = this.getScene().particleSystems[index];
  684. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  685. results.push(particleSystem);
  686. }
  687. }
  688. return results;
  689. };
  690. Mesh.prototype.getChildren = function () {
  691. var results = [];
  692. for (var index = 0; index < this.getScene().meshes.length; index++) {
  693. var mesh = this.getScene().meshes[index];
  694. if (mesh.parent === this) {
  695. results.push(mesh);
  696. }
  697. }
  698. return results;
  699. };
  700. Mesh.prototype._checkDelayState = function () {
  701. var _this = this;
  702. var that = this;
  703. var scene = this.getScene();
  704. if (this._geometry) {
  705. this._geometry.load(scene);
  706. }
  707. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  708. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  709. scene._addPendingData(that);
  710. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  711. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  712. if (data instanceof ArrayBuffer) {
  713. _this._delayLoadingFunction(data, _this);
  714. }
  715. else {
  716. _this._delayLoadingFunction(JSON.parse(data), _this);
  717. }
  718. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  719. scene._removePendingData(_this);
  720. }, function () {
  721. }, scene.database, getBinaryData);
  722. }
  723. };
  724. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  726. return false;
  727. }
  728. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  729. return false;
  730. }
  731. this._checkDelayState();
  732. return true;
  733. };
  734. Mesh.prototype.setMaterialByID = function (id) {
  735. var materials = this.getScene().materials;
  736. for (var index = 0; index < materials.length; index++) {
  737. if (materials[index].id === id) {
  738. this.material = materials[index];
  739. return;
  740. }
  741. }
  742. // Multi
  743. var multiMaterials = this.getScene().multiMaterials;
  744. for (index = 0; index < multiMaterials.length; index++) {
  745. if (multiMaterials[index].id === id) {
  746. this.material = multiMaterials[index];
  747. return;
  748. }
  749. }
  750. };
  751. Mesh.prototype.getAnimatables = function () {
  752. var results = [];
  753. if (this.material) {
  754. results.push(this.material);
  755. }
  756. if (this.skeleton) {
  757. results.push(this.skeleton);
  758. }
  759. return results;
  760. };
  761. // Geometry
  762. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  763. // Position
  764. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  765. return;
  766. }
  767. this._resetPointsArrayCache();
  768. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  769. var temp = [];
  770. for (var index = 0; index < data.length; index += 3) {
  771. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  772. }
  773. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  774. // Normals
  775. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  776. return;
  777. }
  778. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  779. temp = [];
  780. for (index = 0; index < data.length; index += 3) {
  781. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  782. }
  783. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  784. };
  785. // Cache
  786. Mesh.prototype._resetPointsArrayCache = function () {
  787. this._positions = null;
  788. };
  789. Mesh.prototype._generatePointsArray = function () {
  790. if (this._positions)
  791. return true;
  792. this._positions = [];
  793. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  794. if (!data) {
  795. return false;
  796. }
  797. for (var index = 0; index < data.length; index += 3) {
  798. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  799. }
  800. return true;
  801. };
  802. // Clone
  803. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  804. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  805. };
  806. // Dispose
  807. Mesh.prototype.dispose = function (doNotRecurse) {
  808. if (this._geometry) {
  809. this._geometry.releaseForMesh(this, true);
  810. }
  811. // Instances
  812. if (this._worldMatricesInstancesBuffer) {
  813. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  814. this._worldMatricesInstancesBuffer = null;
  815. }
  816. while (this.instances.length) {
  817. this.instances[0].dispose();
  818. }
  819. _super.prototype.dispose.call(this, doNotRecurse);
  820. };
  821. // Geometric tools
  822. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  823. var _this = this;
  824. var scene = this.getScene();
  825. var onload = function (img) {
  826. // Getting height map data
  827. var canvas = document.createElement("canvas");
  828. var context = canvas.getContext("2d");
  829. var heightMapWidth = img.width;
  830. var heightMapHeight = img.height;
  831. canvas.width = heightMapWidth;
  832. canvas.height = heightMapHeight;
  833. context.drawImage(img, 0, 0);
  834. // Create VertexData from map data
  835. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  836. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  837. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  838. //execute success callback, if set
  839. if (onSuccess) {
  840. onSuccess(_this);
  841. }
  842. };
  843. BABYLON.Tools.LoadImage(url, onload, function () {
  844. }, scene.database);
  845. };
  846. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  847. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  848. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  849. return;
  850. }
  851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  852. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  853. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  854. var position = BABYLON.Vector3.Zero();
  855. var normal = BABYLON.Vector3.Zero();
  856. var uv = BABYLON.Vector2.Zero();
  857. for (var index = 0; index < positions.length; index += 3) {
  858. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  859. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  860. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  861. // Compute height
  862. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  863. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  864. var pos = (u + v * heightMapWidth) * 4;
  865. var r = buffer[pos] / 255.0;
  866. var g = buffer[pos + 1] / 255.0;
  867. var b = buffer[pos + 2] / 255.0;
  868. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  869. normal.normalize();
  870. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  871. position = position.add(normal);
  872. position.toArray(positions, index);
  873. }
  874. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  875. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  876. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  877. };
  878. Mesh.prototype.convertToFlatShadedMesh = function () {
  879. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  880. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  881. var kinds = this.getVerticesDataKinds();
  882. var vbs = [];
  883. var data = [];
  884. var newdata = [];
  885. var updatableNormals = false;
  886. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  887. var kind = kinds[kindIndex];
  888. var vertexBuffer = this.getVertexBuffer(kind);
  889. if (kind === BABYLON.VertexBuffer.NormalKind) {
  890. updatableNormals = vertexBuffer.isUpdatable();
  891. kinds.splice(kindIndex, 1);
  892. kindIndex--;
  893. continue;
  894. }
  895. vbs[kind] = vertexBuffer;
  896. data[kind] = vbs[kind].getData();
  897. newdata[kind] = [];
  898. }
  899. // Save previous submeshes
  900. var previousSubmeshes = this.subMeshes.slice(0);
  901. var indices = this.getIndices();
  902. var totalIndices = this.getTotalIndices();
  903. for (var index = 0; index < totalIndices; index++) {
  904. var vertexIndex = indices[index];
  905. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  906. kind = kinds[kindIndex];
  907. var stride = vbs[kind].getStrideSize();
  908. for (var offset = 0; offset < stride; offset++) {
  909. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  910. }
  911. }
  912. }
  913. // Updating faces & normal
  914. var normals = [];
  915. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  916. for (index = 0; index < totalIndices; index += 3) {
  917. indices[index] = index;
  918. indices[index + 1] = index + 1;
  919. indices[index + 2] = index + 2;
  920. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  921. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  922. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  923. var p1p2 = p1.subtract(p2);
  924. var p3p2 = p3.subtract(p2);
  925. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  926. for (var localIndex = 0; localIndex < 3; localIndex++) {
  927. normals.push(normal.x);
  928. normals.push(normal.y);
  929. normals.push(normal.z);
  930. }
  931. }
  932. this.setIndices(indices);
  933. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  934. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  935. kind = kinds[kindIndex];
  936. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  937. }
  938. // Updating submeshes
  939. this.releaseSubMeshes();
  940. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  941. var previousOne = previousSubmeshes[submeshIndex];
  942. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  943. }
  944. this.synchronizeInstances();
  945. };
  946. // Instances
  947. Mesh.prototype.createInstance = function (name) {
  948. return new BABYLON.InstancedMesh(name, this);
  949. };
  950. Mesh.prototype.synchronizeInstances = function () {
  951. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  952. var instance = this.instances[instanceIndex];
  953. instance._syncSubMeshes();
  954. }
  955. };
  956. /**
  957. * Simplify the mesh according to the given array of settings.
  958. * Function will return immediately and will simplify async.
  959. * @param settings a collection of simplification settings.
  960. * @param parallelProcessing should all levels calculate parallel or one after the other.
  961. * @param type the type of simplification to run.
  962. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  963. */
  964. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  965. if (parallelProcessing === void 0) { parallelProcessing = true; }
  966. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  967. this.getScene().simplificationQueue.addTask({
  968. settings: settings,
  969. parallelProcessing: parallelProcessing,
  970. mesh: this,
  971. simplificationType: simplificationType,
  972. successCallback: successCallback
  973. });
  974. };
  975. /**
  976. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  977. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  978. * This should be used together with the simplification to avoid disappearing triangles.
  979. * @param successCallback an optional success callback to be called after the optimization finished.
  980. */
  981. Mesh.prototype.optimizeIndices = function (successCallback) {
  982. var _this = this;
  983. var indices = this.getIndices();
  984. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  985. var vectorPositions = [];
  986. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  987. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  988. }
  989. var dupes = [];
  990. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  991. var realPos = vectorPositions.length - 1 - iteration;
  992. var testedPosition = vectorPositions[realPos];
  993. for (var j = 0; j < realPos; ++j) {
  994. var againstPosition = vectorPositions[j];
  995. if (testedPosition.equals(againstPosition)) {
  996. dupes[realPos] = j;
  997. break;
  998. }
  999. }
  1000. }, function () {
  1001. for (var i = 0; i < indices.length; ++i) {
  1002. indices[i] = dupes[indices[i]] || indices[i];
  1003. }
  1004. //indices are now reordered
  1005. var originalSubMeshes = _this.subMeshes.slice(0);
  1006. _this.setIndices(indices);
  1007. _this.subMeshes = originalSubMeshes;
  1008. if (successCallback) {
  1009. successCallback(_this);
  1010. }
  1011. });
  1012. };
  1013. // Statics
  1014. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  1015. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1016. if (ribbonInstance === void 0) { ribbonInstance = null; }
  1017. if (ribbonInstance) {
  1018. // positionFunction : ribbon case
  1019. // only pathArray and sideOrientation parameters are taken into account for positions update
  1020. var positionsOfRibbon = function (pathArray, sideOrientation) {
  1021. var positionFunction = function (positions) {
  1022. var minlg = pathArray[0].length;
  1023. var i = 0;
  1024. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  1025. for (var si = 1; si <= ns; si++) {
  1026. for (var p = 0; p < pathArray.length; p++) {
  1027. var path = pathArray[p];
  1028. var l = path.length;
  1029. minlg = (minlg < l) ? minlg : l;
  1030. var j = 0;
  1031. while (j < minlg) {
  1032. positions[i] = path[j].x;
  1033. positions[i + 1] = path[j].y;
  1034. positions[i + 2] = path[j].z;
  1035. j++;
  1036. i += 3;
  1037. }
  1038. }
  1039. }
  1040. };
  1041. return positionFunction;
  1042. };
  1043. var sideOrientation = ribbonInstance.sideOrientation;
  1044. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  1045. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  1046. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  1047. return ribbonInstance;
  1048. }
  1049. else {
  1050. var ribbon = new Mesh(name, scene);
  1051. ribbon.sideOrientation = sideOrientation;
  1052. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  1053. vertexData.applyToMesh(ribbon, updatable);
  1054. return ribbon;
  1055. }
  1056. };
  1057. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  1058. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1059. var disc = new Mesh(name, scene);
  1060. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  1061. vertexData.applyToMesh(disc, updatable);
  1062. return disc;
  1063. };
  1064. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  1065. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1066. var box = new Mesh(name, scene);
  1067. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  1068. vertexData.applyToMesh(box, updatable);
  1069. return box;
  1070. };
  1071. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  1072. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1073. var sphere = new Mesh(name, scene);
  1074. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  1075. vertexData.applyToMesh(sphere, updatable);
  1076. return sphere;
  1077. };
  1078. // Cylinder and cone (Code inspired by SharpDX.org)
  1079. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  1080. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1081. // subdivisions is a new parameter, we need to support old signature
  1082. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  1083. if (scene !== undefined) {
  1084. updatable = scene;
  1085. }
  1086. scene = subdivisions;
  1087. subdivisions = 1;
  1088. }
  1089. var cylinder = new Mesh(name, scene);
  1090. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  1091. vertexData.applyToMesh(cylinder, updatable);
  1092. return cylinder;
  1093. };
  1094. // Torus (Code from SharpDX.org)
  1095. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  1096. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1097. var torus = new Mesh(name, scene);
  1098. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1099. vertexData.applyToMesh(torus, updatable);
  1100. return torus;
  1101. };
  1102. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  1103. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1104. var torusKnot = new Mesh(name, scene);
  1105. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1106. vertexData.applyToMesh(torusKnot, updatable);
  1107. return torusKnot;
  1108. };
  1109. // Lines
  1110. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  1111. if (linesInstance === void 0) { linesInstance = null; }
  1112. if (linesInstance) {
  1113. var positionsOfLines = function (points) {
  1114. var positionFunction = function (positions) {
  1115. var i = 0;
  1116. for (var p = 0; p < points.length; p++) {
  1117. positions[i] = points[p].x;
  1118. positions[i + 1] = points[p].y;
  1119. positions[i + 2] = points[p].z;
  1120. i += 3;
  1121. }
  1122. };
  1123. return positionFunction;
  1124. };
  1125. var positionFunction = positionsOfLines(points);
  1126. linesInstance.updateMeshPositions(positionFunction, false);
  1127. return linesInstance;
  1128. }
  1129. // lines creation
  1130. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  1131. var vertexData = BABYLON.VertexData.CreateLines(points);
  1132. vertexData.applyToMesh(lines, updatable);
  1133. return lines;
  1134. };
  1135. // Extrusion
  1136. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  1137. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1138. if (extrudedInstance === void 0) { extrudedInstance = null; }
  1139. scale = scale || 1;
  1140. rotation = rotation || 0;
  1141. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1142. return extruded;
  1143. };
  1144. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  1145. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1146. if (extrudedInstance === void 0) { extrudedInstance = null; }
  1147. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1148. return extrudedCustom;
  1149. };
  1150. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  1151. // extrusion geometry
  1152. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  1153. var tangents = path3D.getTangents();
  1154. var normals = path3D.getNormals();
  1155. var binormals = path3D.getBinormals();
  1156. var distances = path3D.getDistances();
  1157. var angle = 0;
  1158. var returnScale = function (i, distance) {
  1159. return scale;
  1160. };
  1161. var returnRotation = function (i, distance) {
  1162. return rotation;
  1163. };
  1164. var rotate = custom ? rotateFunction : returnRotation;
  1165. var scl = custom ? scaleFunction : returnScale;
  1166. var index = 0;
  1167. for (var i = 0; i < curve.length; i++) {
  1168. var shapePath = new Array();
  1169. var angleStep = rotate(i, distances[i]);
  1170. var scaleRatio = scl(i, distances[i]);
  1171. for (var p = 0; p < shape.length; p++) {
  1172. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  1173. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1174. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1175. shapePath.push(rotated);
  1176. }
  1177. shapePaths[index] = shapePath;
  1178. angle += angleStep;
  1179. index++;
  1180. }
  1181. // cap
  1182. var capPath = function (shapePath) {
  1183. var pointCap = Array();
  1184. var barycenter = BABYLON.Vector3.Zero();
  1185. var i;
  1186. for (i = 0; i < shapePath.length; i++) {
  1187. barycenter.addInPlace(shapePath[i]);
  1188. }
  1189. barycenter.scaleInPlace(1 / shapePath.length);
  1190. for (i = 0; i < shapePath.length; i++) {
  1191. pointCap.push(barycenter);
  1192. }
  1193. return pointCap;
  1194. };
  1195. switch (cap) {
  1196. case BABYLON.Mesh.NO_CAP:
  1197. break;
  1198. case BABYLON.Mesh.CAP_START:
  1199. shapePaths.unshift(capPath(shapePaths[0]));
  1200. break;
  1201. case BABYLON.Mesh.CAP_END:
  1202. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1203. break;
  1204. case BABYLON.Mesh.CAP_ALL:
  1205. shapePaths.unshift(capPath(shapePaths[0]));
  1206. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1207. break;
  1208. default:
  1209. break;
  1210. }
  1211. return shapePaths;
  1212. };
  1213. if (instance) {
  1214. var path3D = (instance.path3D).update(curve);
  1215. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  1216. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1217. return instance;
  1218. }
  1219. // extruded shape creation
  1220. var path3D = new BABYLON.Path3D(curve);
  1221. var newShapePaths = new Array();
  1222. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1223. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1224. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1225. extrudedGeneric.pathArray = pathArray;
  1226. extrudedGeneric.path3D = path3D;
  1227. extrudedGeneric.cap = cap;
  1228. return extrudedGeneric;
  1229. };
  1230. // Plane & ground
  1231. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  1232. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1233. var plane = new Mesh(name, scene);
  1234. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  1235. vertexData.applyToMesh(plane, updatable);
  1236. return plane;
  1237. };
  1238. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  1239. var ground = new BABYLON.GroundMesh(name, scene);
  1240. ground._setReady(false);
  1241. ground._subdivisions = subdivisions;
  1242. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  1243. vertexData.applyToMesh(ground, updatable);
  1244. ground._setReady(true);
  1245. return ground;
  1246. };
  1247. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  1248. var tiledGround = new Mesh(name, scene);
  1249. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1250. vertexData.applyToMesh(tiledGround, updatable);
  1251. return tiledGround;
  1252. };
  1253. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  1254. var ground = new BABYLON.GroundMesh(name, scene);
  1255. ground._subdivisions = subdivisions;
  1256. ground._setReady(false);
  1257. var onload = function (img) {
  1258. // Getting height map data
  1259. var canvas = document.createElement("canvas");
  1260. var context = canvas.getContext("2d");
  1261. var heightMapWidth = img.width;
  1262. var heightMapHeight = img.height;
  1263. canvas.width = heightMapWidth;
  1264. canvas.height = heightMapHeight;
  1265. context.drawImage(img, 0, 0);
  1266. // Create VertexData from map data
  1267. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1268. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1269. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1270. vertexData.applyToMesh(ground, updatable);
  1271. ground._setReady(true);
  1272. //execute ready callback, if set
  1273. if (onReady) {
  1274. onReady(ground);
  1275. }
  1276. };
  1277. BABYLON.Tools.LoadImage(url, onload, function () {
  1278. }, scene.database);
  1279. return ground;
  1280. };
  1281. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  1282. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1283. if (tubeInstance === void 0) { tubeInstance = null; }
  1284. // tube geometry
  1285. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  1286. var tangents = path3D.getTangents();
  1287. var normals = path3D.getNormals();
  1288. var distances = path3D.getDistances();
  1289. var pi2 = Math.PI * 2;
  1290. var step = pi2 / tessellation;
  1291. var returnRadius = function (i, distance) { return radius; };
  1292. var radiusFunctionFinal = radiusFunction || returnRadius;
  1293. var circlePath;
  1294. var rad;
  1295. var normal;
  1296. var rotated;
  1297. var rotationMatrix;
  1298. var index = 0;
  1299. for (var i = 0; i < path.length; i++) {
  1300. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1301. circlePath = Array(); // current circle array
  1302. normal = normals[i]; // current normal
  1303. for (var t = 0; t < tessellation; t++) {
  1304. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  1305. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1306. circlePath.push(rotated);
  1307. }
  1308. circlePath.push(circlePath[0]);
  1309. circlePaths[index] = circlePath;
  1310. index++;
  1311. }
  1312. // cap
  1313. var capPath = function (nbPoints, pathIndex) {
  1314. var pointCap = Array();
  1315. for (var i = 0; i < nbPoints; i++) {
  1316. pointCap.push(path[pathIndex]);
  1317. }
  1318. return pointCap;
  1319. };
  1320. switch (cap) {
  1321. case BABYLON.Mesh.NO_CAP:
  1322. break;
  1323. case BABYLON.Mesh.CAP_START:
  1324. circlePaths.unshift(capPath(tessellation + 1, 0));
  1325. break;
  1326. case BABYLON.Mesh.CAP_END:
  1327. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1328. break;
  1329. case BABYLON.Mesh.CAP_ALL:
  1330. circlePaths.unshift(capPath(tessellation + 1, 0));
  1331. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1332. break;
  1333. default:
  1334. break;
  1335. }
  1336. return circlePaths;
  1337. };
  1338. if (tubeInstance) {
  1339. var path3D = (tubeInstance.path3D).update(path);
  1340. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  1341. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1342. return tubeInstance;
  1343. }
  1344. // tube creation
  1345. var path3D = new BABYLON.Path3D(path);
  1346. var newPathArray = new Array();
  1347. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1348. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1349. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1350. tube.pathArray = pathArray;
  1351. tube.path3D = path3D;
  1352. tube.tessellation = tessellation;
  1353. tube.cap = cap;
  1354. return tube;
  1355. };
  1356. // Decals
  1357. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  1358. if (angle === void 0) { angle = 0; }
  1359. var indices = sourceMesh.getIndices();
  1360. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  1361. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  1362. // Getting correct rotation
  1363. if (!normal) {
  1364. var target = new BABYLON.Vector3(0, 0, 1);
  1365. var camera = sourceMesh.getScene().activeCamera;
  1366. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1367. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1368. }
  1369. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1370. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1371. var pitch = Math.atan2(normal.y, len);
  1372. // Matrix
  1373. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  1374. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  1375. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1376. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1377. var vertexData = new BABYLON.VertexData();
  1378. vertexData.indices = [];
  1379. vertexData.positions = [];
  1380. vertexData.normals = [];
  1381. vertexData.uvs = [];
  1382. var currentVertexDataIndex = 0;
  1383. var extractDecalVector3 = function (indexId) {
  1384. var vertexId = indices[indexId];
  1385. var result = new BABYLON.PositionNormalVertex();
  1386. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1387. // Send vector to decal local world
  1388. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  1389. // Get normal
  1390. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1391. return result;
  1392. };
  1393. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1394. var clip = function (vertices, axis) {
  1395. if (vertices.length === 0) {
  1396. return vertices;
  1397. }
  1398. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  1399. var clipVertices = function (v0, v1) {
  1400. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1401. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  1402. };
  1403. var result = new Array();
  1404. for (var index = 0; index < vertices.length; index += 3) {
  1405. var v1Out;
  1406. var v2Out;
  1407. var v3Out;
  1408. var total = 0;
  1409. var nV1, nV2, nV3, nV4;
  1410. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  1411. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1412. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1413. v1Out = d1 > 0;
  1414. v2Out = d2 > 0;
  1415. v3Out = d3 > 0;
  1416. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1417. switch (total) {
  1418. case 0:
  1419. result.push(vertices[index]);
  1420. result.push(vertices[index + 1]);
  1421. result.push(vertices[index + 2]);
  1422. break;
  1423. case 1:
  1424. if (v1Out) {
  1425. nV1 = vertices[index + 1];
  1426. nV2 = vertices[index + 2];
  1427. nV3 = clipVertices(vertices[index], nV1);
  1428. nV4 = clipVertices(vertices[index], nV2);
  1429. }
  1430. if (v2Out) {
  1431. nV1 = vertices[index];
  1432. nV2 = vertices[index + 2];
  1433. nV3 = clipVertices(vertices[index + 1], nV1);
  1434. nV4 = clipVertices(vertices[index + 1], nV2);
  1435. result.push(nV3);
  1436. result.push(nV2.clone());
  1437. result.push(nV1.clone());
  1438. result.push(nV2.clone());
  1439. result.push(nV3.clone());
  1440. result.push(nV4);
  1441. break;
  1442. }
  1443. if (v3Out) {
  1444. nV1 = vertices[index];
  1445. nV2 = vertices[index + 1];
  1446. nV3 = clipVertices(vertices[index + 2], nV1);
  1447. nV4 = clipVertices(vertices[index + 2], nV2);
  1448. }
  1449. result.push(nV1.clone());
  1450. result.push(nV2.clone());
  1451. result.push(nV3);
  1452. result.push(nV4);
  1453. result.push(nV3.clone());
  1454. result.push(nV2.clone());
  1455. break;
  1456. case 2:
  1457. if (!v1Out) {
  1458. nV1 = vertices[index].clone();
  1459. nV2 = clipVertices(nV1, vertices[index + 1]);
  1460. nV3 = clipVertices(nV1, vertices[index + 2]);
  1461. result.push(nV1);
  1462. result.push(nV2);
  1463. result.push(nV3);
  1464. }
  1465. if (!v2Out) {
  1466. nV1 = vertices[index + 1].clone();
  1467. nV2 = clipVertices(nV1, vertices[index + 2]);
  1468. nV3 = clipVertices(nV1, vertices[index]);
  1469. result.push(nV1);
  1470. result.push(nV2);
  1471. result.push(nV3);
  1472. }
  1473. if (!v3Out) {
  1474. nV1 = vertices[index + 2].clone();
  1475. nV2 = clipVertices(nV1, vertices[index]);
  1476. nV3 = clipVertices(nV1, vertices[index + 1]);
  1477. result.push(nV1);
  1478. result.push(nV2);
  1479. result.push(nV3);
  1480. }
  1481. break;
  1482. case 3:
  1483. break;
  1484. }
  1485. }
  1486. return result;
  1487. };
  1488. for (var index = 0; index < indices.length; index += 3) {
  1489. var faceVertices = new Array();
  1490. faceVertices.push(extractDecalVector3(index));
  1491. faceVertices.push(extractDecalVector3(index + 1));
  1492. faceVertices.push(extractDecalVector3(index + 2));
  1493. // Clip
  1494. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  1495. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  1496. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  1497. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  1498. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  1499. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  1500. if (faceVertices.length === 0) {
  1501. continue;
  1502. }
  1503. // Add UVs and get back to world
  1504. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  1505. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1506. var vertex = faceVertices[vIndex];
  1507. vertexData.indices.push(currentVertexDataIndex);
  1508. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1509. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1510. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1511. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1512. currentVertexDataIndex++;
  1513. }
  1514. }
  1515. // Return mesh
  1516. var decal = new Mesh(name, sourceMesh.getScene());
  1517. vertexData.applyToMesh(decal);
  1518. decal.position = position.clone();
  1519. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  1520. return decal;
  1521. };
  1522. // Tools
  1523. Mesh.MinMax = function (meshes) {
  1524. var minVector = null;
  1525. var maxVector = null;
  1526. for (var i in meshes) {
  1527. var mesh = meshes[i];
  1528. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1529. if (!minVector) {
  1530. minVector = boundingBox.minimumWorld;
  1531. maxVector = boundingBox.maximumWorld;
  1532. continue;
  1533. }
  1534. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1535. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1536. }
  1537. return {
  1538. min: minVector,
  1539. max: maxVector
  1540. };
  1541. };
  1542. Mesh.Center = function (meshesOrMinMaxVector) {
  1543. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1544. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  1545. };
  1546. /**
  1547. * Merge the array of meshes into a single mesh for performance reasons.
  1548. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1549. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1550. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1551. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1552. */
  1553. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  1554. if (disposeSource === void 0) { disposeSource = true; }
  1555. if (!allow32BitsIndices) {
  1556. var totalVertices = 0;
  1557. for (var index = 0; index < meshes.length; index++) {
  1558. if (meshes[index]) {
  1559. totalVertices += meshes[index].getTotalVertices();
  1560. if (totalVertices > 65536) {
  1561. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1562. return null;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. // Merge
  1568. var vertexData;
  1569. var otherVertexData;
  1570. var source;
  1571. for (index = 0; index < meshes.length; index++) {
  1572. if (meshes[index]) {
  1573. meshes[index].computeWorldMatrix(true);
  1574. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  1575. otherVertexData.transform(meshes[index].getWorldMatrix());
  1576. if (vertexData) {
  1577. vertexData.merge(otherVertexData);
  1578. }
  1579. else {
  1580. vertexData = otherVertexData;
  1581. source = meshes[index];
  1582. }
  1583. }
  1584. }
  1585. if (!meshSubclass) {
  1586. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1587. }
  1588. vertexData.applyToMesh(meshSubclass);
  1589. // Setting properties
  1590. meshSubclass.material = source.material;
  1591. meshSubclass.checkCollisions = source.checkCollisions;
  1592. // Cleaning
  1593. if (disposeSource) {
  1594. for (index = 0; index < meshes.length; index++) {
  1595. if (meshes[index]) {
  1596. meshes[index].dispose();
  1597. }
  1598. }
  1599. }
  1600. return meshSubclass;
  1601. };
  1602. // Consts
  1603. Mesh._FRONTSIDE = 0;
  1604. Mesh._BACKSIDE = 1;
  1605. Mesh._DOUBLESIDE = 2;
  1606. Mesh._DEFAULTSIDE = 0;
  1607. Mesh._NO_CAP = 0;
  1608. Mesh._CAP_START = 1;
  1609. Mesh._CAP_END = 2;
  1610. Mesh._CAP_ALL = 3;
  1611. return Mesh;
  1612. })(BABYLON.AbstractMesh);
  1613. BABYLON.Mesh = Mesh;
  1614. })(BABYLON || (BABYLON = {}));
  1615. //# sourceMappingURL=babylon.mesh.js.map