babylon.mesh.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. if (visibleInstances) {
  267. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  268. var instance = visibleInstances[instanceIndex];
  269. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  270. offset += 16;
  271. instancesCount++;
  272. }
  273. }
  274. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  275. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  276. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  277. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  278. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  279. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  280. this._draw(subMesh, !wireFrame, instancesCount);
  281. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  282. }
  283. public render(subMesh: SubMesh): void {
  284. var scene = this.getScene();
  285. // Managing instances
  286. var batch = this._getInstancesRenderList(subMesh._id);
  287. if (batch.mustReturn) {
  288. return;
  289. }
  290. // Checking geometry state
  291. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  292. return;
  293. }
  294. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  295. this._onBeforeRenderCallbacks[callbackIndex]();
  296. }
  297. var engine = scene.getEngine();
  298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  299. // Material
  300. var effectiveMaterial = subMesh.getMaterial();
  301. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  302. return;
  303. }
  304. effectiveMaterial._preBind();
  305. var effect = effectiveMaterial.getEffect();
  306. // Bind
  307. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  308. this._bind(subMesh, effect, wireFrame);
  309. var world = this.getWorldMatrix();
  310. effectiveMaterial.bind(world, this);
  311. // Instances rendering
  312. if (hardwareInstancedRendering) {
  313. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  314. } else {
  315. if (batch.renderSelf[subMesh._id]) {
  316. // Draw
  317. this._draw(subMesh, !wireFrame);
  318. }
  319. if (batch.visibleInstances[subMesh._id]) {
  320. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  321. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  322. // World
  323. world = instance.getWorldMatrix();
  324. effectiveMaterial.bindOnlyWorldMatrix(world);
  325. // Draw
  326. this._draw(subMesh, !wireFrame);
  327. }
  328. }
  329. }
  330. // Unbind
  331. effectiveMaterial.unbind();
  332. }
  333. public getEmittedParticleSystems(): ParticleSystem[] {
  334. var results = new Array<ParticleSystem>();
  335. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  336. var particleSystem = this.getScene().particleSystems[index];
  337. if (particleSystem.emitter === this) {
  338. results.push(particleSystem);
  339. }
  340. }
  341. return results;
  342. }
  343. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  344. var results = new Array<ParticleSystem>();
  345. var descendants = this.getDescendants();
  346. descendants.push(this);
  347. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  348. var particleSystem = this.getScene().particleSystems[index];
  349. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  350. results.push(particleSystem);
  351. }
  352. }
  353. return results;
  354. }
  355. public getChildren(): Node[] {
  356. var results = [];
  357. for (var index = 0; index < this.getScene().meshes.length; index++) {
  358. var mesh = this.getScene().meshes[index];
  359. if (mesh.parent == this) {
  360. results.push(mesh);
  361. }
  362. }
  363. return results;
  364. }
  365. public _checkDelayState(): void {
  366. var that = this;
  367. var scene = this.getScene();
  368. if (this._geometry) {
  369. this._geometry.load(scene);
  370. }
  371. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  372. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  373. scene._addPendingData(that);
  374. BABYLON.Tools.LoadFile(this.delayLoadingFile, data => {
  375. this._delayLoadingFunction(JSON.parse(data), this);
  376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  377. scene._removePendingData(this);
  378. }, () => { }, scene.database);
  379. }
  380. }
  381. public isInFrustum(frustumPlanes: Plane[]): boolean {
  382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  383. return false;
  384. }
  385. if (!super.isInFrustum(frustumPlanes)) {
  386. return false;
  387. }
  388. this._checkDelayState();
  389. return true;
  390. }
  391. public setMaterialByID(id: string): void {
  392. var materials = this.getScene().materials;
  393. for (var index = 0; index < materials.length; index++) {
  394. if (materials[index].id == id) {
  395. this.material = materials[index];
  396. return;
  397. }
  398. }
  399. // Multi
  400. var multiMaterials = this.getScene().multiMaterials;
  401. for (index = 0; index < multiMaterials.length; index++) {
  402. if (multiMaterials[index].id == id) {
  403. this.material = multiMaterials[index];
  404. return;
  405. }
  406. }
  407. }
  408. public getAnimatables(): IAnimatable[] {
  409. var results = [];
  410. if (this.material) {
  411. results.push(this.material);
  412. }
  413. return results;
  414. }
  415. // Geometry
  416. public bakeTransformIntoVertices(transform: Matrix): void {
  417. // Position
  418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  419. return;
  420. }
  421. this._resetPointsArrayCache();
  422. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  423. var temp = [];
  424. for (var index = 0; index < data.length; index += 3) {
  425. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  426. }
  427. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  428. // Normals
  429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  430. return;
  431. }
  432. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  433. for (index = 0; index < data.length; index += 3) {
  434. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  435. }
  436. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  437. }
  438. // Cache
  439. public _resetPointsArrayCache(): void {
  440. this._positions = null;
  441. }
  442. public _generatePointsArray(): boolean {
  443. if (this._positions)
  444. return true;
  445. this._positions = [];
  446. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  447. if (!data) {
  448. return false;
  449. }
  450. for (var index = 0; index < data.length; index += 3) {
  451. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  452. }
  453. return true;
  454. }
  455. // Clone
  456. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  457. var result = new BABYLON.Mesh(name, this.getScene());
  458. // Geometry
  459. this._geometry.applyToMesh(result);
  460. // Deep copy
  461. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  462. // Material
  463. result.material = this.material;
  464. // Parent
  465. if (newParent) {
  466. result.parent = newParent;
  467. }
  468. if (!doNotCloneChildren) {
  469. // Children
  470. for (var index = 0; index < this.getScene().meshes.length; index++) {
  471. var mesh = this.getScene().meshes[index];
  472. if (mesh.parent == this) {
  473. mesh.clone(mesh.name, result);
  474. }
  475. }
  476. }
  477. // Particles
  478. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  479. var system = this.getScene().particleSystems[index];
  480. if (system.emitter == this) {
  481. system.clone(system.name, result);
  482. }
  483. }
  484. result.computeWorldMatrix(true);
  485. return result;
  486. }
  487. // Dispose
  488. public dispose(doNotRecurse?: boolean): void {
  489. if (this._geometry) {
  490. this._geometry.releaseForMesh(this, true);
  491. }
  492. // Instances
  493. if (this._worldMatricesInstancesBuffer) {
  494. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  495. this._worldMatricesInstancesBuffer = null;
  496. }
  497. while (this.instances.length) {
  498. this.instances[0].dispose();
  499. }
  500. super.dispose(doNotRecurse);
  501. }
  502. // Geometric tools
  503. public convertToFlatShadedMesh(): void {
  504. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  505. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  506. var kinds = this.getVerticesDataKinds();
  507. var vbs = [];
  508. var data = [];
  509. var newdata = [];
  510. var updatableNormals = false;
  511. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  512. var kind = kinds[kindIndex];
  513. var vertexBuffer = this.getVertexBuffer(kind);
  514. if (kind === BABYLON.VertexBuffer.NormalKind) {
  515. updatableNormals = vertexBuffer.isUpdatable();
  516. kinds.splice(kindIndex, 1);
  517. kindIndex--;
  518. continue;
  519. }
  520. vbs[kind] = vertexBuffer;
  521. data[kind] = vbs[kind].getData();
  522. newdata[kind] = [];
  523. }
  524. // Save previous submeshes
  525. var previousSubmeshes = this.subMeshes.slice(0);
  526. var indices = this.getIndices();
  527. var totalIndices = this.getTotalIndices();
  528. // Generating unique vertices per face
  529. for (index = 0; index < totalIndices; index++) {
  530. var vertexIndex = indices[index];
  531. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  532. kind = kinds[kindIndex];
  533. var stride = vbs[kind].getStrideSize();
  534. for (var offset = 0; offset < stride; offset++) {
  535. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  536. }
  537. }
  538. }
  539. // Updating faces & normal
  540. var normals = [];
  541. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  542. for (var index = 0; index < totalIndices; index += 3) {
  543. indices[index] = index;
  544. indices[index + 1] = index + 1;
  545. indices[index + 2] = index + 2;
  546. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  547. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  548. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  549. var p1p2 = p1.subtract(p2);
  550. var p3p2 = p3.subtract(p2);
  551. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  552. // Store same normals for every vertex
  553. for (var localIndex = 0; localIndex < 3; localIndex++) {
  554. normals.push(normal.x);
  555. normals.push(normal.y);
  556. normals.push(normal.z);
  557. }
  558. }
  559. this.setIndices(indices);
  560. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  561. // Updating vertex buffers
  562. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  563. kind = kinds[kindIndex];
  564. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  565. }
  566. // Updating submeshes
  567. this.releaseSubMeshes();
  568. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  569. var previousOne = previousSubmeshes[submeshIndex];
  570. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  571. }
  572. this.synchronizeInstances();
  573. }
  574. // Instances
  575. public createInstance(name: string): InstancedMesh {
  576. return new InstancedMesh(name, this);
  577. }
  578. public synchronizeInstances(): void {
  579. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  580. var instance = this.instances[instanceIndex];
  581. instance._syncSubMeshes();
  582. }
  583. }
  584. // Statics
  585. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  586. var box = new BABYLON.Mesh(name, scene);
  587. var vertexData = BABYLON.VertexData.CreateBox(size);
  588. vertexData.applyToMesh(box, updatable);
  589. return box;
  590. }
  591. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  592. var sphere = new BABYLON.Mesh(name, scene);
  593. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  594. vertexData.applyToMesh(sphere, updatable);
  595. return sphere;
  596. }
  597. // Cylinder and cone (Code inspired by SharpDX.org)
  598. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  599. var cylinder = new BABYLON.Mesh(name, scene);
  600. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  601. vertexData.applyToMesh(cylinder, updatable);
  602. return cylinder;
  603. }
  604. // Torus (Code from SharpDX.org)
  605. public static CreateTorus(name: string, diameter:number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  606. var torus = new BABYLON.Mesh(name, scene);
  607. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  608. vertexData.applyToMesh(torus, updatable);
  609. return torus;
  610. }
  611. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  612. var torusKnot = new BABYLON.Mesh(name, scene);
  613. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  614. vertexData.applyToMesh(torusKnot, updatable);
  615. return torusKnot;
  616. }
  617. // Lines
  618. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  619. var lines = new LinesMesh(name, scene, updatable);
  620. var vertexData = BABYLON.VertexData.CreateLines(points);
  621. vertexData.applyToMesh(lines, updatable);
  622. return lines;
  623. }
  624. // Plane & ground
  625. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  626. var plane = new BABYLON.Mesh(name, scene);
  627. var vertexData = BABYLON.VertexData.CreatePlane(size);
  628. vertexData.applyToMesh(plane, updatable);
  629. return plane;
  630. }
  631. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  632. var ground = new BABYLON.GroundMesh(name, scene);
  633. ground._setReady(false);
  634. ground._subdivisions = subdivisions;
  635. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  636. vertexData.applyToMesh(ground, updatable);
  637. ground._setReady(true);
  638. return ground;
  639. }
  640. 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 {
  641. var tiledGround = new BABYLON.GroundMesh(name, scene);
  642. tiledGround._setReady(false);
  643. tiledGround._subdivisions = subdivisions;
  644. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  645. vertexData.applyToMesh(tiledGround, updatable);
  646. tiledGround._setReady(true);
  647. return tiledGround;
  648. }
  649. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): GroundMesh {
  650. var ground = new BABYLON.GroundMesh(name, scene);
  651. ground._subdivisions = subdivisions;
  652. ground._setReady(false);
  653. var onload = img => {
  654. // Getting height map data
  655. var canvas = document.createElement("canvas");
  656. var context = canvas.getContext("2d");
  657. var heightMapWidth = img.width;
  658. var heightMapHeight = img.height;
  659. canvas.width = heightMapWidth;
  660. canvas.height = heightMapHeight;
  661. context.drawImage(img, 0, 0);
  662. // Create VertexData from map data
  663. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  664. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  665. vertexData.applyToMesh(ground, updatable);
  666. ground._setReady(true);
  667. };
  668. Tools.LoadImage(url, onload, () => { }, scene.database);
  669. return ground;
  670. }
  671. // Tools
  672. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  673. var minVector = null;
  674. var maxVector = null;
  675. for (var i in meshes) {
  676. var mesh = meshes[i];
  677. var boundingBox = mesh.getBoundingInfo().boundingBox;
  678. if (!minVector) {
  679. minVector = boundingBox.minimumWorld;
  680. maxVector = boundingBox.maximumWorld;
  681. continue;
  682. }
  683. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  684. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  685. }
  686. return {
  687. min: minVector,
  688. max: maxVector
  689. };
  690. }
  691. public static Center(meshesOrMinMaxVector): Vector3 {
  692. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  693. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  694. }
  695. }
  696. }