babylon.mesh.js 78 KB

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