babylon.mesh.js 77 KB

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