babylon.mesh.ts 33 KB

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