babylon.mesh.ts 28 KB

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