babylon.mesh.js 72 KB

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