babylon.mesh.js 101 KB

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