babylon.mesh.ts 30 KB

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