babylon.mesh.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. function Mesh(name, scene) {
  21. _super.call(this, name, scene);
  22. // Members
  23. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24. this.instances = new Array();
  25. this._onBeforeRenderCallbacks = new Array();
  26. this._onAfterRenderCallbacks = new Array();
  27. this._visibleInstances = {};
  28. this._renderIdForInstances = new Array();
  29. this._batchCache = new _InstancesBatch();
  30. this._instancesBufferSize = 32 * 16 * 4;
  31. }
  32. Mesh.prototype.getTotalVertices = function () {
  33. if (!this._geometry) {
  34. return 0;
  35. }
  36. return this._geometry.getTotalVertices();
  37. };
  38. Mesh.prototype.getVerticesData = function (kind) {
  39. if (!this._geometry) {
  40. return null;
  41. }
  42. return this._geometry.getVerticesData(kind);
  43. };
  44. Mesh.prototype.getVertexBuffer = function (kind) {
  45. if (!this._geometry) {
  46. return undefined;
  47. }
  48. return this._geometry.getVertexBuffer(kind);
  49. };
  50. Mesh.prototype.isVerticesDataPresent = function (kind) {
  51. if (!this._geometry) {
  52. if (this._delayInfo) {
  53. return this._delayInfo.indexOf(kind) !== -1;
  54. }
  55. return false;
  56. }
  57. return this._geometry.isVerticesDataPresent(kind);
  58. };
  59. Mesh.prototype.getVerticesDataKinds = function () {
  60. if (!this._geometry) {
  61. var result = [];
  62. if (this._delayInfo) {
  63. for (var kind in this._delayInfo) {
  64. result.push(kind);
  65. }
  66. }
  67. return result;
  68. }
  69. return this._geometry.getVerticesDataKinds();
  70. };
  71. Mesh.prototype.getTotalIndices = function () {
  72. if (!this._geometry) {
  73. return 0;
  74. }
  75. return this._geometry.getTotalIndices();
  76. };
  77. Mesh.prototype.getIndices = function () {
  78. if (!this._geometry) {
  79. return [];
  80. }
  81. return this._geometry.getIndices();
  82. };
  83. Mesh.prototype.isReady = function () {
  84. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  85. return false;
  86. }
  87. return _super.prototype.isReady.call(this);
  88. };
  89. Mesh.prototype.isDisposed = function () {
  90. return this._isDisposed;
  91. };
  92. // Methods
  93. Mesh.prototype._preActivate = function () {
  94. var sceneRenderId = this.getScene().getRenderId();
  95. if (this._preActivateId == sceneRenderId) {
  96. return;
  97. }
  98. this._preActivateId = sceneRenderId;
  99. this._visibleInstances = null;
  100. };
  101. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  102. if (!this._visibleInstances) {
  103. this._visibleInstances = {};
  104. this._visibleInstances.defaultRenderId = renderId;
  105. this._visibleInstances.selfDefaultRenderId = this._renderId;
  106. }
  107. if (!this._visibleInstances[renderId]) {
  108. this._visibleInstances[renderId] = new Array();
  109. }
  110. this._visibleInstances[renderId].push(instance);
  111. };
  112. Mesh.prototype.refreshBoundingInfo = function () {
  113. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  114. if (data) {
  115. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  116. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  117. }
  118. if (this.subMeshes) {
  119. for (var index = 0; index < this.subMeshes.length; index++) {
  120. this.subMeshes[index].refreshBoundingInfo();
  121. }
  122. }
  123. this._updateBoundingInfo();
  124. };
  125. Mesh.prototype._createGlobalSubMesh = function () {
  126. var totalVertices = this.getTotalVertices();
  127. if (!totalVertices || !this.getIndices()) {
  128. return null;
  129. }
  130. this.releaseSubMeshes();
  131. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  132. };
  133. Mesh.prototype.subdivide = function (count) {
  134. if (count < 1) {
  135. return;
  136. }
  137. var totalIndices = this.getTotalIndices();
  138. var subdivisionSize = (totalIndices / count) | 0;
  139. var offset = 0;
  140. while (subdivisionSize % 3 != 0) {
  141. subdivisionSize++;
  142. }
  143. this.releaseSubMeshes();
  144. for (var index = 0; index < count; index++) {
  145. if (offset >= totalIndices) {
  146. break;
  147. }
  148. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  149. offset += subdivisionSize;
  150. }
  151. this.synchronizeInstances();
  152. };
  153. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  154. if (kind instanceof Array) {
  155. var temp = data;
  156. data = kind;
  157. kind = temp;
  158. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  159. }
  160. if (!this._geometry) {
  161. var vertexData = new BABYLON.VertexData();
  162. vertexData.set(data, kind);
  163. var scene = this.getScene();
  164. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  165. } else {
  166. this._geometry.setVerticesData(kind, data, updatable);
  167. }
  168. };
  169. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  170. if (!this._geometry) {
  171. return;
  172. }
  173. if (!makeItUnique) {
  174. this._geometry.updateVerticesData(kind, data, updateExtends);
  175. } else {
  176. this.makeGeometryUnique();
  177. this.updateVerticesData(kind, data, updateExtends, false);
  178. }
  179. };
  180. Mesh.prototype.makeGeometryUnique = function () {
  181. if (!this._geometry) {
  182. return;
  183. }
  184. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  185. geometry.applyToMesh(this);
  186. };
  187. Mesh.prototype.setIndices = function (indices) {
  188. if (!this._geometry) {
  189. var vertexData = new BABYLON.VertexData();
  190. vertexData.indices = indices;
  191. var scene = this.getScene();
  192. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  193. } else {
  194. this._geometry.setIndices(indices);
  195. }
  196. };
  197. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  198. var engine = this.getScene().getEngine();
  199. // Wireframe
  200. var indexToBind = this._geometry.getIndexBuffer();
  201. if (wireframe) {
  202. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  203. }
  204. // VBOs
  205. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  206. };
  207. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  208. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  209. return;
  210. }
  211. var engine = this.getScene().getEngine();
  212. // Draw order
  213. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  214. };
  215. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  216. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  217. return;
  218. }
  219. var engine = this.getScene().getEngine();
  220. // Draw order
  221. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  222. };
  223. Mesh.prototype.registerBeforeRender = function (func) {
  224. this._onBeforeRenderCallbacks.push(func);
  225. };
  226. Mesh.prototype.unregisterBeforeRender = function (func) {
  227. var index = this._onBeforeRenderCallbacks.indexOf(func);
  228. if (index > -1) {
  229. this._onBeforeRenderCallbacks.splice(index, 1);
  230. }
  231. };
  232. Mesh.prototype.registerAfterRender = function (func) {
  233. this._onAfterRenderCallbacks.push(func);
  234. };
  235. Mesh.prototype.unregisterAfterRender = function (func) {
  236. var index = this._onAfterRenderCallbacks.indexOf(func);
  237. if (index > -1) {
  238. this._onAfterRenderCallbacks.splice(index, 1);
  239. }
  240. };
  241. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  242. var scene = this.getScene();
  243. this._batchCache.mustReturn = false;
  244. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  245. this._batchCache.visibleInstances[subMeshId] = null;
  246. if (this._visibleInstances) {
  247. var currentRenderId = scene.getRenderId();
  248. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  249. var selfRenderId = this._renderId;
  250. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  251. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  252. currentRenderId = this._visibleInstances.defaultRenderId;
  253. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  254. }
  255. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  256. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  257. this._batchCache.mustReturn = true;
  258. return this._batchCache;
  259. }
  260. if (currentRenderId !== selfRenderId) {
  261. this._batchCache.renderSelf[subMeshId] = false;
  262. }
  263. }
  264. this._renderIdForInstances[subMeshId] = currentRenderId;
  265. }
  266. return this._batchCache;
  267. };
  268. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  269. var matricesCount = this.instances.length + 1;
  270. var bufferSize = matricesCount * 16 * 4;
  271. while (this._instancesBufferSize < bufferSize) {
  272. this._instancesBufferSize *= 2;
  273. }
  274. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  275. if (this._worldMatricesInstancesBuffer) {
  276. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  277. }
  278. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  279. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  280. }
  281. var offset = 0;
  282. var instancesCount = 0;
  283. var world = this.getWorldMatrix();
  284. if (batch.renderSelf[subMesh._id]) {
  285. world.copyToArray(this._worldMatricesInstancesArray, offset);
  286. offset += 16;
  287. instancesCount++;
  288. }
  289. var visibleInstances = batch.visibleInstances[subMesh._id];
  290. if (visibleInstances) {
  291. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  292. var instance = visibleInstances[instanceIndex];
  293. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  294. offset += 16;
  295. instancesCount++;
  296. }
  297. }
  298. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  299. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  300. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  301. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  302. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  303. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  304. this._draw(subMesh, !wireFrame, instancesCount);
  305. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  306. };
  307. Mesh.prototype.render = function (subMesh) {
  308. var scene = this.getScene();
  309. // Managing instances
  310. var batch = this._getInstancesRenderList(subMesh._id);
  311. if (batch.mustReturn) {
  312. return;
  313. }
  314. // Checking geometry state
  315. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  316. return;
  317. }
  318. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  319. this._onBeforeRenderCallbacks[callbackIndex]();
  320. }
  321. var engine = scene.getEngine();
  322. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  323. // Material
  324. var effectiveMaterial = subMesh.getMaterial();
  325. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  326. return;
  327. }
  328. // Outline - step 1
  329. var savedDepthWrite = engine.getDepthWrite();
  330. if (this.renderOutline) {
  331. engine.setDepthWrite(false);
  332. scene.getOutlineRenderer().render(subMesh, batch);
  333. }
  334. effectiveMaterial._preBind();
  335. var effect = effectiveMaterial.getEffect();
  336. // Bind
  337. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  338. this._bind(subMesh, effect, wireFrame);
  339. var world = this.getWorldMatrix();
  340. effectiveMaterial.bind(world, this);
  341. // Instances rendering
  342. if (hardwareInstancedRendering) {
  343. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  344. } else {
  345. if (batch.renderSelf[subMesh._id]) {
  346. // Draw
  347. this._draw(subMesh, !wireFrame);
  348. }
  349. if (batch.visibleInstances[subMesh._id]) {
  350. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  351. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  352. // World
  353. world = instance.getWorldMatrix();
  354. effectiveMaterial.bindOnlyWorldMatrix(world);
  355. // Draw
  356. this._draw(subMesh, !wireFrame);
  357. }
  358. }
  359. }
  360. // Unbind
  361. effectiveMaterial.unbind();
  362. // Outline - step 2
  363. if (this.renderOutline && savedDepthWrite) {
  364. engine.setDepthWrite(true);
  365. engine.setColorWrite(false);
  366. scene.getOutlineRenderer().render(subMesh, batch);
  367. engine.setColorWrite(true);
  368. }
  369. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  370. this._onAfterRenderCallbacks[callbackIndex]();
  371. }
  372. };
  373. Mesh.prototype.getEmittedParticleSystems = function () {
  374. var results = new Array();
  375. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  376. var particleSystem = this.getScene().particleSystems[index];
  377. if (particleSystem.emitter === this) {
  378. results.push(particleSystem);
  379. }
  380. }
  381. return results;
  382. };
  383. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  384. var results = new Array();
  385. var descendants = this.getDescendants();
  386. descendants.push(this);
  387. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  388. var particleSystem = this.getScene().particleSystems[index];
  389. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  390. results.push(particleSystem);
  391. }
  392. }
  393. return results;
  394. };
  395. Mesh.prototype.getChildren = function () {
  396. var results = [];
  397. for (var index = 0; index < this.getScene().meshes.length; index++) {
  398. var mesh = this.getScene().meshes[index];
  399. if (mesh.parent == this) {
  400. results.push(mesh);
  401. }
  402. }
  403. return results;
  404. };
  405. Mesh.prototype._checkDelayState = function () {
  406. var _this = this;
  407. var that = this;
  408. var scene = this.getScene();
  409. if (this._geometry) {
  410. this._geometry.load(scene);
  411. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  412. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  413. scene._addPendingData(that);
  414. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  415. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  416. if (data instanceof ArrayBuffer) {
  417. _this._delayLoadingFunction(data, _this);
  418. } else {
  419. _this._delayLoadingFunction(JSON.parse(data), _this);
  420. }
  421. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  422. scene._removePendingData(_this);
  423. }, function () {
  424. }, scene.database, getBinaryData);
  425. }
  426. };
  427. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  428. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  429. return false;
  430. }
  431. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  432. return false;
  433. }
  434. this._checkDelayState();
  435. return true;
  436. };
  437. Mesh.prototype.setMaterialByID = function (id) {
  438. var materials = this.getScene().materials;
  439. for (var index = 0; index < materials.length; index++) {
  440. if (materials[index].id == id) {
  441. this.material = materials[index];
  442. return;
  443. }
  444. }
  445. // Multi
  446. var multiMaterials = this.getScene().multiMaterials;
  447. for (index = 0; index < multiMaterials.length; index++) {
  448. if (multiMaterials[index].id == id) {
  449. this.material = multiMaterials[index];
  450. return;
  451. }
  452. }
  453. };
  454. Mesh.prototype.getAnimatables = function () {
  455. var results = [];
  456. if (this.material) {
  457. results.push(this.material);
  458. }
  459. return results;
  460. };
  461. // Geometry
  462. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  463. // Position
  464. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  465. return;
  466. }
  467. this._resetPointsArrayCache();
  468. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  469. var temp = [];
  470. for (var index = 0; index < data.length; index += 3) {
  471. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  472. }
  473. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  474. // Normals
  475. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  476. return;
  477. }
  478. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  479. for (index = 0; index < data.length; index += 3) {
  480. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  481. }
  482. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  483. };
  484. // Cache
  485. Mesh.prototype._resetPointsArrayCache = function () {
  486. this._positions = null;
  487. };
  488. Mesh.prototype._generatePointsArray = function () {
  489. if (this._positions)
  490. return true;
  491. this._positions = [];
  492. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  493. if (!data) {
  494. return false;
  495. }
  496. for (var index = 0; index < data.length; index += 3) {
  497. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  498. }
  499. return true;
  500. };
  501. // Clone
  502. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  503. var result = new BABYLON.Mesh(name, this.getScene());
  504. // Geometry
  505. this._geometry.applyToMesh(result);
  506. // Deep copy
  507. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  508. // Material
  509. result.material = this.material;
  510. // Parent
  511. if (newParent) {
  512. result.parent = newParent;
  513. }
  514. if (!doNotCloneChildren) {
  515. for (var index = 0; index < this.getScene().meshes.length; index++) {
  516. var mesh = this.getScene().meshes[index];
  517. if (mesh.parent == this) {
  518. mesh.clone(mesh.name, result);
  519. }
  520. }
  521. }
  522. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  523. var system = this.getScene().particleSystems[index];
  524. if (system.emitter == this) {
  525. system.clone(system.name, result);
  526. }
  527. }
  528. result.computeWorldMatrix(true);
  529. return result;
  530. };
  531. // Dispose
  532. Mesh.prototype.dispose = function (doNotRecurse) {
  533. if (this._geometry) {
  534. this._geometry.releaseForMesh(this, true);
  535. }
  536. // Instances
  537. if (this._worldMatricesInstancesBuffer) {
  538. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  539. this._worldMatricesInstancesBuffer = null;
  540. }
  541. while (this.instances.length) {
  542. this.instances[0].dispose();
  543. }
  544. _super.prototype.dispose.call(this, doNotRecurse);
  545. };
  546. // Geometric tools
  547. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  548. var _this = this;
  549. var scene = this.getScene();
  550. var onload = function (img) {
  551. // Getting height map data
  552. var canvas = document.createElement("canvas");
  553. var context = canvas.getContext("2d");
  554. var heightMapWidth = img.width;
  555. var heightMapHeight = img.height;
  556. canvas.width = heightMapWidth;
  557. canvas.height = heightMapHeight;
  558. context.drawImage(img, 0, 0);
  559. // Create VertexData from map data
  560. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  561. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  562. };
  563. BABYLON.Tools.LoadImage(url, onload, function () {
  564. }, scene.database);
  565. };
  566. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  567. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  568. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  569. return;
  570. }
  571. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  572. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  573. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  574. var position = BABYLON.Vector3.Zero();
  575. var normal = BABYLON.Vector3.Zero();
  576. var uv = BABYLON.Vector2.Zero();
  577. for (var index = 0; index < positions.length; index += 3) {
  578. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  579. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  580. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  581. // Compute height
  582. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  583. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  584. var pos = (u + v * heightMapWidth) * 4;
  585. var r = buffer[pos] / 255.0;
  586. var g = buffer[pos + 1] / 255.0;
  587. var b = buffer[pos + 2] / 255.0;
  588. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  589. normal.normalize();
  590. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  591. position = position.add(normal);
  592. position.toArray(positions, index);
  593. }
  594. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  595. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  596. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  597. };
  598. Mesh.prototype.convertToFlatShadedMesh = function () {
  599. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  600. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  601. var kinds = this.getVerticesDataKinds();
  602. var vbs = [];
  603. var data = [];
  604. var newdata = [];
  605. var updatableNormals = false;
  606. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  607. var kind = kinds[kindIndex];
  608. var vertexBuffer = this.getVertexBuffer(kind);
  609. if (kind === BABYLON.VertexBuffer.NormalKind) {
  610. updatableNormals = vertexBuffer.isUpdatable();
  611. kinds.splice(kindIndex, 1);
  612. kindIndex--;
  613. continue;
  614. }
  615. vbs[kind] = vertexBuffer;
  616. data[kind] = vbs[kind].getData();
  617. newdata[kind] = [];
  618. }
  619. // Save previous submeshes
  620. var previousSubmeshes = this.subMeshes.slice(0);
  621. var indices = this.getIndices();
  622. var totalIndices = this.getTotalIndices();
  623. for (index = 0; index < totalIndices; index++) {
  624. var vertexIndex = indices[index];
  625. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  626. kind = kinds[kindIndex];
  627. var stride = vbs[kind].getStrideSize();
  628. for (var offset = 0; offset < stride; offset++) {
  629. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  630. }
  631. }
  632. }
  633. // Updating faces & normal
  634. var normals = [];
  635. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  636. for (var index = 0; index < totalIndices; index += 3) {
  637. indices[index] = index;
  638. indices[index + 1] = index + 1;
  639. indices[index + 2] = index + 2;
  640. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  641. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  642. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  643. var p1p2 = p1.subtract(p2);
  644. var p3p2 = p3.subtract(p2);
  645. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  646. for (var localIndex = 0; localIndex < 3; localIndex++) {
  647. normals.push(normal.x);
  648. normals.push(normal.y);
  649. normals.push(normal.z);
  650. }
  651. }
  652. this.setIndices(indices);
  653. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  654. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  655. kind = kinds[kindIndex];
  656. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  657. }
  658. // Updating submeshes
  659. this.releaseSubMeshes();
  660. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  661. var previousOne = previousSubmeshes[submeshIndex];
  662. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  663. }
  664. this.synchronizeInstances();
  665. };
  666. // Instances
  667. Mesh.prototype.createInstance = function (name) {
  668. return new BABYLON.InstancedMesh(name, this);
  669. };
  670. Mesh.prototype.synchronizeInstances = function () {
  671. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  672. var instance = this.instances[instanceIndex];
  673. instance._syncSubMeshes();
  674. }
  675. };
  676. // Statics
  677. Mesh.CreateBox = function (name, size, scene, updatable) {
  678. var box = new BABYLON.Mesh(name, scene);
  679. var vertexData = BABYLON.VertexData.CreateBox(size);
  680. vertexData.applyToMesh(box, updatable);
  681. return box;
  682. };
  683. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  684. var sphere = new BABYLON.Mesh(name, scene);
  685. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  686. vertexData.applyToMesh(sphere, updatable);
  687. return sphere;
  688. };
  689. // Cylinder and cone (Code inspired by SharpDX.org)
  690. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  691. // subdivisions is a new parameter, we need to support old signature
  692. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  693. if (scene !== undefined) {
  694. updatable = scene;
  695. }
  696. scene = subdivisions;
  697. subdivisions = 1;
  698. }
  699. var cylinder = new BABYLON.Mesh(name, scene);
  700. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  701. vertexData.applyToMesh(cylinder, updatable);
  702. return cylinder;
  703. };
  704. // Torus (Code from SharpDX.org)
  705. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  706. var torus = new BABYLON.Mesh(name, scene);
  707. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  708. vertexData.applyToMesh(torus, updatable);
  709. return torus;
  710. };
  711. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  712. var torusKnot = new BABYLON.Mesh(name, scene);
  713. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  714. vertexData.applyToMesh(torusKnot, updatable);
  715. return torusKnot;
  716. };
  717. // Lines
  718. Mesh.CreateLines = function (name, points, scene, updatable) {
  719. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  720. var vertexData = BABYLON.VertexData.CreateLines(points);
  721. vertexData.applyToMesh(lines, updatable);
  722. return lines;
  723. };
  724. // Plane & ground
  725. Mesh.CreatePlane = function (name, size, scene, updatable) {
  726. var plane = new BABYLON.Mesh(name, scene);
  727. var vertexData = BABYLON.VertexData.CreatePlane(size);
  728. vertexData.applyToMesh(plane, updatable);
  729. return plane;
  730. };
  731. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  732. var ground = new BABYLON.GroundMesh(name, scene);
  733. ground._setReady(false);
  734. ground._subdivisions = subdivisions;
  735. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  736. vertexData.applyToMesh(ground, updatable);
  737. ground._setReady(true);
  738. return ground;
  739. };
  740. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  741. var tiledGround = new BABYLON.Mesh(name, scene);
  742. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  743. vertexData.applyToMesh(tiledGround, updatable);
  744. return tiledGround;
  745. };
  746. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  747. var ground = new BABYLON.GroundMesh(name, scene);
  748. ground._subdivisions = subdivisions;
  749. ground._setReady(false);
  750. var onload = function (img) {
  751. // Getting height map data
  752. var canvas = document.createElement("canvas");
  753. var context = canvas.getContext("2d");
  754. var heightMapWidth = img.width;
  755. var heightMapHeight = img.height;
  756. canvas.width = heightMapWidth;
  757. canvas.height = heightMapHeight;
  758. context.drawImage(img, 0, 0);
  759. // Create VertexData from map data
  760. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  761. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  762. vertexData.applyToMesh(ground, updatable);
  763. ground._setReady(true);
  764. };
  765. BABYLON.Tools.LoadImage(url, onload, function () {
  766. }, scene.database);
  767. return ground;
  768. };
  769. // Tools
  770. Mesh.MinMax = function (meshes) {
  771. var minVector = null;
  772. var maxVector = null;
  773. for (var i in meshes) {
  774. var mesh = meshes[i];
  775. var boundingBox = mesh.getBoundingInfo().boundingBox;
  776. if (!minVector) {
  777. minVector = boundingBox.minimumWorld;
  778. maxVector = boundingBox.maximumWorld;
  779. continue;
  780. }
  781. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  782. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  783. }
  784. return {
  785. min: minVector,
  786. max: maxVector
  787. };
  788. };
  789. Mesh.Center = function (meshesOrMinMaxVector) {
  790. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  791. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  792. };
  793. return Mesh;
  794. })(BABYLON.AbstractMesh);
  795. BABYLON.Mesh = Mesh;
  796. })(BABYLON || (BABYLON = {}));
  797. //# sourceMappingURL=babylon.mesh.js.map