babylon.mesh.ts 44 KB

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