babylon.mesh.ts 31 KB

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