babylon.mesh.ts 30 KB

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