babylon.mesh.js 66 KB

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