babylon.mesh.ts 32 KB

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