babylon.mesh.js 42 KB

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