babylon.mesh.ts 38 KB

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