babylon.mesh.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  181. if (!this._geometry) {
  182. return;
  183. }
  184. if (!makeItUnique) {
  185. this._geometry.updateVerticesDataDirectly(kind, data);
  186. } else {
  187. this.makeGeometryUnique();
  188. this.updateVerticesDataDirectly(kind, data, false);
  189. }
  190. };
  191. Mesh.prototype.makeGeometryUnique = function () {
  192. if (!this._geometry) {
  193. return;
  194. }
  195. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  196. geometry.applyToMesh(this);
  197. };
  198. Mesh.prototype.setIndices = function (indices) {
  199. if (!this._geometry) {
  200. var vertexData = new BABYLON.VertexData();
  201. vertexData.indices = indices;
  202. var scene = this.getScene();
  203. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  204. } else {
  205. this._geometry.setIndices(indices);
  206. }
  207. };
  208. Mesh.prototype._bind = function (subMesh, effect, drawAs) {
  209. var engine = this.getScene().getEngine();
  210. var indexToBind = undefined;
  211. switch (drawAs) {
  212. case WebGLRenderingContext.LINES:
  213. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  214. break;
  215. case WebGLRenderingContext.POINTS:
  216. indexToBind = null;
  217. break;
  218. case WebGLRenderingContext.TRIANGLES:
  219. default:
  220. indexToBind = this._geometry.getIndexBuffer();
  221. break;
  222. }
  223. // VBOs
  224. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  225. };
  226. Mesh.prototype._getStartIndexOfMesh = function (subMesh, drawAs) {
  227. var start = 0;
  228. switch (drawAs) {
  229. case WebGLRenderingContext.LINES:
  230. start = 0;
  231. break;
  232. case WebGLRenderingContext.POINTS:
  233. start = 0;
  234. break;
  235. case WebGLRenderingContext.TRIANGLES:
  236. default:
  237. start = subMesh.indexStart;
  238. break;
  239. }
  240. return start;
  241. };
  242. Mesh.prototype._getCountOfMesh = function (subMesh, drawAs) {
  243. var count = 0;
  244. switch (drawAs) {
  245. case WebGLRenderingContext.LINES:
  246. count = subMesh.linesIndexCount;
  247. break;
  248. case WebGLRenderingContext.POINTS:
  249. count = subMesh.verticesCount;
  250. break;
  251. case WebGLRenderingContext.TRIANGLES:
  252. default:
  253. count = subMesh.indexCount;
  254. break;
  255. }
  256. return count;
  257. };
  258. Mesh.prototype._draw = function (subMesh, drawAs, instancesCount) {
  259. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  260. return;
  261. }
  262. var engine = this.getScene().getEngine();
  263. var start = this._getStartIndexOfMesh(subMesh, drawAs);
  264. var count = this._getCountOfMesh(subMesh, drawAs);
  265. // Draw order
  266. engine.draw(drawAs, start, count, instancesCount);
  267. };
  268. Mesh.prototype._fullDraw = function (subMesh, drawAs, instancesCount) {
  269. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  270. return;
  271. }
  272. var engine = this.getScene().getEngine();
  273. var start = this._getStartIndexOfMesh(subMesh, drawAs);
  274. var count = this._getCountOfMesh(subMesh, drawAs);
  275. // Draw order
  276. engine.draw(drawAs, start, count, instancesCount);
  277. };
  278. Mesh.prototype.registerBeforeRender = function (func) {
  279. this._onBeforeRenderCallbacks.push(func);
  280. };
  281. Mesh.prototype.unregisterBeforeRender = function (func) {
  282. var index = this._onBeforeRenderCallbacks.indexOf(func);
  283. if (index > -1) {
  284. this._onBeforeRenderCallbacks.splice(index, 1);
  285. }
  286. };
  287. Mesh.prototype.registerAfterRender = function (func) {
  288. this._onAfterRenderCallbacks.push(func);
  289. };
  290. Mesh.prototype.unregisterAfterRender = function (func) {
  291. var index = this._onAfterRenderCallbacks.indexOf(func);
  292. if (index > -1) {
  293. this._onAfterRenderCallbacks.splice(index, 1);
  294. }
  295. };
  296. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  297. var scene = this.getScene();
  298. this._batchCache.mustReturn = false;
  299. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  300. this._batchCache.visibleInstances[subMeshId] = null;
  301. if (this._visibleInstances) {
  302. var currentRenderId = scene.getRenderId();
  303. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  304. var selfRenderId = this._renderId;
  305. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  306. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  307. currentRenderId = this._visibleInstances.defaultRenderId;
  308. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  309. }
  310. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  311. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  312. this._batchCache.mustReturn = true;
  313. return this._batchCache;
  314. }
  315. if (currentRenderId !== selfRenderId) {
  316. this._batchCache.renderSelf[subMeshId] = false;
  317. }
  318. }
  319. this._renderIdForInstances[subMeshId] = currentRenderId;
  320. }
  321. return this._batchCache;
  322. };
  323. Mesh.prototype._renderWithInstances = function (subMesh, drawAs, batch, effect, engine) {
  324. var matricesCount = this.instances.length + 1;
  325. var bufferSize = matricesCount * 16 * 4;
  326. while (this._instancesBufferSize < bufferSize) {
  327. this._instancesBufferSize *= 2;
  328. }
  329. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  330. if (this._worldMatricesInstancesBuffer) {
  331. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  332. }
  333. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  334. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  335. }
  336. var offset = 0;
  337. var instancesCount = 0;
  338. var world = this.getWorldMatrix();
  339. if (batch.renderSelf[subMesh._id]) {
  340. world.copyToArray(this._worldMatricesInstancesArray, offset);
  341. offset += 16;
  342. instancesCount++;
  343. }
  344. var visibleInstances = batch.visibleInstances[subMesh._id];
  345. if (visibleInstances) {
  346. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  347. var instance = visibleInstances[instanceIndex];
  348. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  349. offset += 16;
  350. instancesCount++;
  351. }
  352. }
  353. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  354. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  355. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  356. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  357. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  358. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  359. this._draw(subMesh, drawAs, instancesCount);
  360. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  361. };
  362. Mesh.prototype.render = function (subMesh) {
  363. var scene = this.getScene();
  364. // Managing instances
  365. var batch = this._getInstancesRenderList(subMesh._id);
  366. if (batch.mustReturn) {
  367. return;
  368. }
  369. // Checking geometry state
  370. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  371. return;
  372. }
  373. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  374. this._onBeforeRenderCallbacks[callbackIndex]();
  375. }
  376. var engine = scene.getEngine();
  377. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  378. // Material
  379. var effectiveMaterial = subMesh.getMaterial();
  380. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  381. return;
  382. }
  383. // Outline - step 1
  384. var savedDepthWrite = engine.getDepthWrite();
  385. if (this.renderOutline) {
  386. engine.setDepthWrite(false);
  387. scene.getOutlineRenderer().render(subMesh, batch);
  388. }
  389. effectiveMaterial._preBind();
  390. var effect = effectiveMaterial.getEffect();
  391. // Bind
  392. var drawAs = engine.forceWireframe ? WebGLRenderingContext.LINES : effectiveMaterial.drawAs;
  393. this._bind(subMesh, effect, drawAs);
  394. var world = this.getWorldMatrix();
  395. effectiveMaterial.bind(world, this);
  396. // Instances rendering
  397. if (hardwareInstancedRendering) {
  398. this._renderWithInstances(subMesh, drawAs, batch, effect, engine);
  399. } else {
  400. if (batch.renderSelf[subMesh._id]) {
  401. // Draw
  402. this._draw(subMesh, drawAs);
  403. }
  404. if (batch.visibleInstances[subMesh._id]) {
  405. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  406. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  407. // World
  408. world = instance.getWorldMatrix();
  409. effectiveMaterial.bindOnlyWorldMatrix(world);
  410. // Draw
  411. this._draw(subMesh, drawAs);
  412. }
  413. }
  414. }
  415. // Unbind
  416. effectiveMaterial.unbind();
  417. // Outline - step 2
  418. if (this.renderOutline && savedDepthWrite) {
  419. engine.setDepthWrite(true);
  420. engine.setColorWrite(false);
  421. scene.getOutlineRenderer().render(subMesh, batch);
  422. engine.setColorWrite(true);
  423. }
  424. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  425. this._onAfterRenderCallbacks[callbackIndex]();
  426. }
  427. };
  428. Mesh.prototype.getEmittedParticleSystems = function () {
  429. var results = new Array();
  430. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  431. var particleSystem = this.getScene().particleSystems[index];
  432. if (particleSystem.emitter === this) {
  433. results.push(particleSystem);
  434. }
  435. }
  436. return results;
  437. };
  438. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  439. var results = new Array();
  440. var descendants = this.getDescendants();
  441. descendants.push(this);
  442. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  443. var particleSystem = this.getScene().particleSystems[index];
  444. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  445. results.push(particleSystem);
  446. }
  447. }
  448. return results;
  449. };
  450. Mesh.prototype.getChildren = function () {
  451. var results = [];
  452. for (var index = 0; index < this.getScene().meshes.length; index++) {
  453. var mesh = this.getScene().meshes[index];
  454. if (mesh.parent == this) {
  455. results.push(mesh);
  456. }
  457. }
  458. return results;
  459. };
  460. Mesh.prototype._checkDelayState = function () {
  461. var _this = this;
  462. var that = this;
  463. var scene = this.getScene();
  464. if (this._geometry) {
  465. this._geometry.load(scene);
  466. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  467. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  468. scene._addPendingData(that);
  469. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  470. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  471. if (data instanceof ArrayBuffer) {
  472. _this._delayLoadingFunction(data, _this);
  473. } else {
  474. _this._delayLoadingFunction(JSON.parse(data), _this);
  475. }
  476. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  477. scene._removePendingData(_this);
  478. }, function () {
  479. }, scene.database, getBinaryData);
  480. }
  481. };
  482. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  483. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  484. return false;
  485. }
  486. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  487. return false;
  488. }
  489. this._checkDelayState();
  490. return true;
  491. };
  492. Mesh.prototype.setMaterialByID = function (id) {
  493. var materials = this.getScene().materials;
  494. for (var index = 0; index < materials.length; index++) {
  495. if (materials[index].id == id) {
  496. this.material = materials[index];
  497. return;
  498. }
  499. }
  500. // Multi
  501. var multiMaterials = this.getScene().multiMaterials;
  502. for (index = 0; index < multiMaterials.length; index++) {
  503. if (multiMaterials[index].id == id) {
  504. this.material = multiMaterials[index];
  505. return;
  506. }
  507. }
  508. };
  509. Mesh.prototype.getAnimatables = function () {
  510. var results = [];
  511. if (this.material) {
  512. results.push(this.material);
  513. }
  514. if (this.skeleton) {
  515. results.push(this.skeleton);
  516. }
  517. return results;
  518. };
  519. // Geometry
  520. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  521. // Position
  522. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  523. return;
  524. }
  525. this._resetPointsArrayCache();
  526. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  527. var temp = [];
  528. for (var index = 0; index < data.length; index += 3) {
  529. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  530. }
  531. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  532. // Normals
  533. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  534. return;
  535. }
  536. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  537. for (index = 0; index < data.length; index += 3) {
  538. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  539. }
  540. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  541. };
  542. // Cache
  543. Mesh.prototype._resetPointsArrayCache = function () {
  544. this._positions = null;
  545. };
  546. Mesh.prototype._generatePointsArray = function () {
  547. if (this._positions)
  548. return true;
  549. this._positions = [];
  550. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  551. if (!data) {
  552. return false;
  553. }
  554. for (var index = 0; index < data.length; index += 3) {
  555. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  556. }
  557. return true;
  558. };
  559. // Clone
  560. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  561. var result = new BABYLON.Mesh(name, this.getScene());
  562. // Geometry
  563. this._geometry.applyToMesh(result);
  564. // Deep copy
  565. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  566. // Material
  567. result.material = this.material;
  568. // Parent
  569. if (newParent) {
  570. result.parent = newParent;
  571. }
  572. if (!doNotCloneChildren) {
  573. for (var index = 0; index < this.getScene().meshes.length; index++) {
  574. var mesh = this.getScene().meshes[index];
  575. if (mesh.parent == this) {
  576. mesh.clone(mesh.name, result);
  577. }
  578. }
  579. }
  580. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  581. var system = this.getScene().particleSystems[index];
  582. if (system.emitter == this) {
  583. system.clone(system.name, result);
  584. }
  585. }
  586. result.computeWorldMatrix(true);
  587. return result;
  588. };
  589. // Dispose
  590. Mesh.prototype.dispose = function (doNotRecurse) {
  591. if (this._geometry) {
  592. this._geometry.releaseForMesh(this, true);
  593. }
  594. // Instances
  595. if (this._worldMatricesInstancesBuffer) {
  596. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  597. this._worldMatricesInstancesBuffer = null;
  598. }
  599. while (this.instances.length) {
  600. this.instances[0].dispose();
  601. }
  602. _super.prototype.dispose.call(this, doNotRecurse);
  603. };
  604. // Geometric tools
  605. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  606. var _this = this;
  607. var scene = this.getScene();
  608. var onload = function (img) {
  609. // Getting height map data
  610. var canvas = document.createElement("canvas");
  611. var context = canvas.getContext("2d");
  612. var heightMapWidth = img.width;
  613. var heightMapHeight = img.height;
  614. canvas.width = heightMapWidth;
  615. canvas.height = heightMapHeight;
  616. context.drawImage(img, 0, 0);
  617. // Create VertexData from map data
  618. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  619. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  620. };
  621. BABYLON.Tools.LoadImage(url, onload, function () {
  622. }, scene.database);
  623. };
  624. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  626. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  627. return;
  628. }
  629. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  630. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  631. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  632. var position = BABYLON.Vector3.Zero();
  633. var normal = BABYLON.Vector3.Zero();
  634. var uv = BABYLON.Vector2.Zero();
  635. for (var index = 0; index < positions.length; index += 3) {
  636. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  637. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  638. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  639. // Compute height
  640. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  641. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  642. var pos = (u + v * heightMapWidth) * 4;
  643. var r = buffer[pos] / 255.0;
  644. var g = buffer[pos + 1] / 255.0;
  645. var b = buffer[pos + 2] / 255.0;
  646. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  647. normal.normalize();
  648. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  649. position = position.add(normal);
  650. position.toArray(positions, index);
  651. }
  652. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  653. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  654. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  655. };
  656. Mesh.prototype.convertToFlatShadedMesh = function () {
  657. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  658. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  659. var kinds = this.getVerticesDataKinds();
  660. var vbs = [];
  661. var data = [];
  662. var newdata = [];
  663. var updatableNormals = false;
  664. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  665. var kind = kinds[kindIndex];
  666. var vertexBuffer = this.getVertexBuffer(kind);
  667. if (kind === BABYLON.VertexBuffer.NormalKind) {
  668. updatableNormals = vertexBuffer.isUpdatable();
  669. kinds.splice(kindIndex, 1);
  670. kindIndex--;
  671. continue;
  672. }
  673. vbs[kind] = vertexBuffer;
  674. data[kind] = vbs[kind].getData();
  675. newdata[kind] = [];
  676. }
  677. // Save previous submeshes
  678. var previousSubmeshes = this.subMeshes.slice(0);
  679. var indices = this.getIndices();
  680. var totalIndices = this.getTotalIndices();
  681. for (index = 0; index < totalIndices; index++) {
  682. var vertexIndex = indices[index];
  683. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  684. kind = kinds[kindIndex];
  685. var stride = vbs[kind].getStrideSize();
  686. for (var offset = 0; offset < stride; offset++) {
  687. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  688. }
  689. }
  690. }
  691. // Updating faces & normal
  692. var normals = [];
  693. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  694. for (var index = 0; index < totalIndices; index += 3) {
  695. indices[index] = index;
  696. indices[index + 1] = index + 1;
  697. indices[index + 2] = index + 2;
  698. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  699. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  700. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  701. var p1p2 = p1.subtract(p2);
  702. var p3p2 = p3.subtract(p2);
  703. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  704. for (var localIndex = 0; localIndex < 3; localIndex++) {
  705. normals.push(normal.x);
  706. normals.push(normal.y);
  707. normals.push(normal.z);
  708. }
  709. }
  710. this.setIndices(indices);
  711. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  712. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  713. kind = kinds[kindIndex];
  714. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  715. }
  716. // Updating submeshes
  717. this.releaseSubMeshes();
  718. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  719. var previousOne = previousSubmeshes[submeshIndex];
  720. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  721. }
  722. this.synchronizeInstances();
  723. };
  724. // Instances
  725. Mesh.prototype.createInstance = function (name) {
  726. return new BABYLON.InstancedMesh(name, this);
  727. };
  728. Mesh.prototype.synchronizeInstances = function () {
  729. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  730. var instance = this.instances[instanceIndex];
  731. instance._syncSubMeshes();
  732. }
  733. };
  734. // Statics
  735. Mesh.CreateBox = function (name, size, scene, updatable) {
  736. var box = new BABYLON.Mesh(name, scene);
  737. var vertexData = BABYLON.VertexData.CreateBox(size);
  738. vertexData.applyToMesh(box, updatable);
  739. return box;
  740. };
  741. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  742. var sphere = new BABYLON.Mesh(name, scene);
  743. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  744. vertexData.applyToMesh(sphere, updatable);
  745. return sphere;
  746. };
  747. // Cylinder and cone (Code inspired by SharpDX.org)
  748. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  749. // subdivisions is a new parameter, we need to support old signature
  750. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  751. if (scene !== undefined) {
  752. updatable = scene;
  753. }
  754. scene = subdivisions;
  755. subdivisions = 1;
  756. }
  757. var cylinder = new BABYLON.Mesh(name, scene);
  758. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  759. vertexData.applyToMesh(cylinder, updatable);
  760. return cylinder;
  761. };
  762. // Torus (Code from SharpDX.org)
  763. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  764. var torus = new BABYLON.Mesh(name, scene);
  765. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  766. vertexData.applyToMesh(torus, updatable);
  767. return torus;
  768. };
  769. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  770. var torusKnot = new BABYLON.Mesh(name, scene);
  771. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  772. vertexData.applyToMesh(torusKnot, updatable);
  773. return torusKnot;
  774. };
  775. // Lines
  776. Mesh.CreateLines = function (name, points, scene, updatable) {
  777. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  778. var vertexData = BABYLON.VertexData.CreateLines(points);
  779. vertexData.applyToMesh(lines, updatable);
  780. return lines;
  781. };
  782. // Plane & ground
  783. Mesh.CreatePlane = function (name, size, scene, updatable) {
  784. var plane = new BABYLON.Mesh(name, scene);
  785. var vertexData = BABYLON.VertexData.CreatePlane(size);
  786. vertexData.applyToMesh(plane, updatable);
  787. return plane;
  788. };
  789. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  790. var ground = new BABYLON.GroundMesh(name, scene);
  791. ground._setReady(false);
  792. ground._subdivisions = subdivisions;
  793. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  794. vertexData.applyToMesh(ground, updatable);
  795. ground._setReady(true);
  796. return ground;
  797. };
  798. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  799. var tiledGround = new BABYLON.Mesh(name, scene);
  800. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  801. vertexData.applyToMesh(tiledGround, updatable);
  802. return tiledGround;
  803. };
  804. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  805. var ground = new BABYLON.GroundMesh(name, scene);
  806. ground._subdivisions = subdivisions;
  807. ground._setReady(false);
  808. var onload = function (img) {
  809. // Getting height map data
  810. var canvas = document.createElement("canvas");
  811. var context = canvas.getContext("2d");
  812. var heightMapWidth = img.width;
  813. var heightMapHeight = img.height;
  814. canvas.width = heightMapWidth;
  815. canvas.height = heightMapHeight;
  816. context.drawImage(img, 0, 0);
  817. // Create VertexData from map data
  818. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  819. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  820. vertexData.applyToMesh(ground, updatable);
  821. ground._setReady(true);
  822. };
  823. BABYLON.Tools.LoadImage(url, onload, function () {
  824. }, scene.database);
  825. return ground;
  826. };
  827. // Tools
  828. Mesh.MinMax = function (meshes) {
  829. var minVector = null;
  830. var maxVector = null;
  831. for (var i in meshes) {
  832. var mesh = meshes[i];
  833. var boundingBox = mesh.getBoundingInfo().boundingBox;
  834. if (!minVector) {
  835. minVector = boundingBox.minimumWorld;
  836. maxVector = boundingBox.maximumWorld;
  837. continue;
  838. }
  839. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  840. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  841. }
  842. return {
  843. min: minVector,
  844. max: maxVector
  845. };
  846. };
  847. Mesh.Center = function (meshesOrMinMaxVector) {
  848. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  849. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  850. };
  851. return Mesh;
  852. })(BABYLON.AbstractMesh);
  853. BABYLON.Mesh = Mesh;
  854. })(BABYLON || (BABYLON = {}));
  855. //# sourceMappingURL=babylon.mesh.js.map