babylon.mesh.js 92 KB

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