babylon.mesh.js 90 KB

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