babylon.mesh.ts 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  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. // Consts
  9. public static _FRONTSIDE: number = 0;
  10. public static _BACKSIDE: number = 1;
  11. public static _DOUBLESIDE: number = 2;
  12. public static _DEFAULTSIDE: number = 0;
  13. public static _NO_CAP = 0;
  14. public static _CAP_START = 1;
  15. public static _CAP_END = 2;
  16. public static _CAP_ALL = 3;
  17. public static get FRONTSIDE(): number {
  18. return Mesh._FRONTSIDE;
  19. }
  20. public static get BACKSIDE(): number {
  21. return Mesh._BACKSIDE;
  22. }
  23. public static get DOUBLESIDE(): number {
  24. return Mesh._DOUBLESIDE;
  25. }
  26. public static get DEFAULTSIDE(): number {
  27. return Mesh._DEFAULTSIDE;
  28. }
  29. public static get NO_CAP(): number {
  30. return Mesh._NO_CAP;
  31. }
  32. public static get CAP_START(): number {
  33. return Mesh._CAP_START;
  34. }
  35. public static get CAP_END(): number {
  36. return Mesh._CAP_END;
  37. }
  38. public static get CAP_ALL(): number {
  39. return Mesh._CAP_ALL;
  40. }
  41. // Members
  42. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  43. public instances = new Array<InstancedMesh>();
  44. public delayLoadingFile: string;
  45. public _binaryInfo: any;
  46. private _LODLevels = new Array<Internals.MeshLODLevel>();
  47. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  48. // Private
  49. public _geometry: Geometry;
  50. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  51. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  52. public _delayInfo; //ANY
  53. public _delayLoadingFunction: (any, Mesh) => void;
  54. public _visibleInstances: any = {};
  55. private _renderIdForInstances = new Array<number>();
  56. private _batchCache = new _InstancesBatch();
  57. private _worldMatricesInstancesBuffer: WebGLBuffer;
  58. private _worldMatricesInstancesArray: Float32Array;
  59. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  60. public _shouldGenerateFlatShading: boolean;
  61. private _preActivateId: number;
  62. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  63. /**
  64. * @constructor
  65. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  66. * @param {Scene} scene - The scene to add this mesh to.
  67. * @param {Node} parent - The parent of this mesh, if it has one
  68. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  69. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  70. * When false, achieved by calling a clone(), also passing False.
  71. * This will make creation of children, recursive.
  72. */
  73. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  74. super(name, scene);
  75. if (source) {
  76. // Geometry
  77. if (source._geometry) {
  78. source._geometry.applyToMesh(this);
  79. }
  80. // Deep copy
  81. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  82. // Material
  83. this.material = source.material;
  84. if (!doNotCloneChildren) {
  85. // Children
  86. for (var index = 0; index < scene.meshes.length; index++) {
  87. var mesh = scene.meshes[index];
  88. if (mesh.parent === source) {
  89. // doNotCloneChildren is always going to be False
  90. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  91. }
  92. }
  93. }
  94. // Particles
  95. for (index = 0; index < scene.particleSystems.length; index++) {
  96. var system = scene.particleSystems[index];
  97. if (system.emitter === source) {
  98. system.clone(system.name, this);
  99. }
  100. }
  101. this.computeWorldMatrix(true);
  102. }
  103. // Parent
  104. if (parent !== null) {
  105. this.parent = parent;
  106. }
  107. }
  108. // Methods
  109. public get hasLODLevels(): boolean {
  110. return this._LODLevels.length > 0;
  111. }
  112. private _sortLODLevels(): void {
  113. this._LODLevels.sort((a, b) => {
  114. if (a.distance < b.distance) {
  115. return 1;
  116. }
  117. if (a.distance > b.distance) {
  118. return -1;
  119. }
  120. return 0;
  121. });
  122. }
  123. /**
  124. * Add a mesh as LOD level triggered at the given distance.
  125. * @param {number} distance - the distance from the center of the object to show this level
  126. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  127. * @return {BABYLON.Mesh} this mesh (for chaining)
  128. */
  129. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  130. if (mesh && mesh._masterMesh) {
  131. Tools.Warn("You cannot use a mesh as LOD level twice");
  132. return this;
  133. }
  134. var level = new Internals.MeshLODLevel(distance, mesh);
  135. this._LODLevels.push(level);
  136. if (mesh) {
  137. mesh._masterMesh = this;
  138. }
  139. this._sortLODLevels();
  140. return this;
  141. }
  142. public getLODLevelAtDistance(distance: number): Mesh {
  143. for (var index = 0; index < this._LODLevels.length; index++) {
  144. var level = this._LODLevels[index];
  145. if (level.distance === distance) {
  146. return level.mesh;
  147. }
  148. }
  149. return null;
  150. }
  151. /**
  152. * Remove a mesh from the LOD array
  153. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  154. * @return {BABYLON.Mesh} this mesh (for chaining)
  155. */
  156. public removeLODLevel(mesh: Mesh): Mesh {
  157. for (var index = 0; index < this._LODLevels.length; index++) {
  158. if (this._LODLevels[index].mesh === mesh) {
  159. this._LODLevels.splice(index, 1);
  160. if (mesh) {
  161. mesh._masterMesh = null;
  162. }
  163. }
  164. }
  165. this._sortLODLevels();
  166. return this;
  167. }
  168. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  169. if (!this._LODLevels || this._LODLevels.length === 0) {
  170. return this;
  171. }
  172. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  173. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  174. if (this.onLODLevelSelection) {
  175. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  176. }
  177. return this;
  178. }
  179. for (var index = 0; index < this._LODLevels.length; index++) {
  180. var level = this._LODLevels[index];
  181. if (level.distance < distanceToCamera) {
  182. if (level.mesh) {
  183. level.mesh._preActivate();
  184. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  185. }
  186. if (this.onLODLevelSelection) {
  187. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  188. }
  189. return level.mesh;
  190. }
  191. }
  192. if (this.onLODLevelSelection) {
  193. this.onLODLevelSelection(distanceToCamera, this, this);
  194. }
  195. return this;
  196. }
  197. public get geometry(): Geometry {
  198. return this._geometry;
  199. }
  200. public getTotalVertices(): number {
  201. if (!this._geometry) {
  202. return 0;
  203. }
  204. return this._geometry.getTotalVertices();
  205. }
  206. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] {
  207. if (!this._geometry) {
  208. return null;
  209. }
  210. return this._geometry.getVerticesData(kind, copyWhenShared);
  211. }
  212. public getVertexBuffer(kind): VertexBuffer {
  213. if (!this._geometry) {
  214. return undefined;
  215. }
  216. return this._geometry.getVertexBuffer(kind);
  217. }
  218. public isVerticesDataPresent(kind: string): boolean {
  219. if (!this._geometry) {
  220. if (this._delayInfo) {
  221. return this._delayInfo.indexOf(kind) !== -1;
  222. }
  223. return false;
  224. }
  225. return this._geometry.isVerticesDataPresent(kind);
  226. }
  227. public getVerticesDataKinds(): string[] {
  228. if (!this._geometry) {
  229. var result = [];
  230. if (this._delayInfo) {
  231. for (var kind in this._delayInfo) {
  232. result.push(kind);
  233. }
  234. }
  235. return result;
  236. }
  237. return this._geometry.getVerticesDataKinds();
  238. }
  239. public getTotalIndices(): number {
  240. if (!this._geometry) {
  241. return 0;
  242. }
  243. return this._geometry.getTotalIndices();
  244. }
  245. public getIndices(copyWhenShared?: boolean): number[] {
  246. if (!this._geometry) {
  247. return [];
  248. }
  249. return this._geometry.getIndices(copyWhenShared);
  250. }
  251. public get isBlocked(): boolean {
  252. return this._masterMesh !== null && this._masterMesh !== undefined;
  253. }
  254. public isReady(): boolean {
  255. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  256. return false;
  257. }
  258. return super.isReady();
  259. }
  260. public isDisposed(): boolean {
  261. return this._isDisposed;
  262. }
  263. public get sideOrientation(): number {
  264. return this._sideOrientation;
  265. }
  266. public set sideOrientation(sideO: number) {
  267. this._sideOrientation = sideO;
  268. }
  269. // Methods
  270. public _preActivate(): void {
  271. var sceneRenderId = this.getScene().getRenderId();
  272. if (this._preActivateId === sceneRenderId) {
  273. return;
  274. }
  275. this._preActivateId = sceneRenderId;
  276. this._visibleInstances = null;
  277. }
  278. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  279. if (!this._visibleInstances) {
  280. this._visibleInstances = {};
  281. this._visibleInstances.defaultRenderId = renderId;
  282. this._visibleInstances.selfDefaultRenderId = this._renderId;
  283. }
  284. if (!this._visibleInstances[renderId]) {
  285. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  286. }
  287. this._visibleInstances[renderId].push(instance);
  288. }
  289. public refreshBoundingInfo(): void {
  290. var data = this.getVerticesData(VertexBuffer.PositionKind);
  291. if (data) {
  292. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  293. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  294. }
  295. if (this.subMeshes) {
  296. for (var index = 0; index < this.subMeshes.length; index++) {
  297. this.subMeshes[index].refreshBoundingInfo();
  298. }
  299. }
  300. this._updateBoundingInfo();
  301. }
  302. public _createGlobalSubMesh(): SubMesh {
  303. var totalVertices = this.getTotalVertices();
  304. if (!totalVertices || !this.getIndices()) {
  305. return null;
  306. }
  307. this.releaseSubMeshes();
  308. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  309. }
  310. public subdivide(count: number): void {
  311. if (count < 1) {
  312. return;
  313. }
  314. var totalIndices = this.getTotalIndices();
  315. var subdivisionSize = (totalIndices / count) | 0;
  316. var offset = 0;
  317. // Ensure that subdivisionSize is a multiple of 3
  318. while (subdivisionSize % 3 !== 0) {
  319. subdivisionSize++;
  320. }
  321. this.releaseSubMeshes();
  322. for (var index = 0; index < count; index++) {
  323. if (offset >= totalIndices) {
  324. break;
  325. }
  326. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  327. offset += subdivisionSize;
  328. }
  329. this.synchronizeInstances();
  330. }
  331. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  332. if (kind instanceof Array) {
  333. var temp = data;
  334. data = kind;
  335. kind = temp;
  336. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  337. }
  338. if (!this._geometry) {
  339. var vertexData = new VertexData();
  340. vertexData.set(data, kind);
  341. var scene = this.getScene();
  342. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  343. }
  344. else {
  345. this._geometry.setVerticesData(kind, data, updatable, stride);
  346. }
  347. }
  348. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  349. if (!this._geometry) {
  350. return;
  351. }
  352. if (!makeItUnique) {
  353. this._geometry.updateVerticesData(kind, data, updateExtends);
  354. }
  355. else {
  356. this.makeGeometryUnique();
  357. this.updateVerticesData(kind, data, updateExtends, false);
  358. }
  359. }
  360. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  361. if (!this._geometry) {
  362. return;
  363. }
  364. if (!makeItUnique) {
  365. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  366. }
  367. else {
  368. this.makeGeometryUnique();
  369. this.updateVerticesDataDirectly(kind, data, offset, false);
  370. }
  371. }
  372. // Mesh positions update function :
  373. // updates the mesh positions according to the positionFunction returned values.
  374. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  375. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  376. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  377. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  378. positionFunction(positions);
  379. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  380. if (computeNormals) {
  381. var indices = this.getIndices();
  382. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  383. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  384. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  385. }
  386. }
  387. public makeGeometryUnique() {
  388. if (!this._geometry) {
  389. return;
  390. }
  391. var geometry = this._geometry.copy(Geometry.RandomId());
  392. geometry.applyToMesh(this);
  393. }
  394. public setIndices(indices: number[], totalVertices?: number): void {
  395. if (!this._geometry) {
  396. var vertexData = new VertexData();
  397. vertexData.indices = indices;
  398. var scene = this.getScene();
  399. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  400. }
  401. else {
  402. this._geometry.setIndices(indices, totalVertices);
  403. }
  404. }
  405. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  406. var engine = this.getScene().getEngine();
  407. // Wireframe
  408. var indexToBind;
  409. switch (fillMode) {
  410. case Material.PointFillMode:
  411. indexToBind = null;
  412. break;
  413. case Material.WireFrameFillMode:
  414. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  415. break;
  416. default:
  417. case Material.TriangleFillMode:
  418. indexToBind = this._geometry.getIndexBuffer();
  419. break;
  420. }
  421. // VBOs
  422. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  423. }
  424. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  425. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  426. return;
  427. }
  428. var engine = this.getScene().getEngine();
  429. // Draw order
  430. switch (fillMode) {
  431. case Material.PointFillMode:
  432. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  433. break;
  434. case Material.WireFrameFillMode:
  435. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  436. break;
  437. default:
  438. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  439. }
  440. }
  441. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  442. this._onBeforeRenderCallbacks.push(func);
  443. }
  444. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  445. var index = this._onBeforeRenderCallbacks.indexOf(func);
  446. if (index > -1) {
  447. this._onBeforeRenderCallbacks.splice(index, 1);
  448. }
  449. }
  450. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  451. this._onAfterRenderCallbacks.push(func);
  452. }
  453. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  454. var index = this._onAfterRenderCallbacks.indexOf(func);
  455. if (index > -1) {
  456. this._onAfterRenderCallbacks.splice(index, 1);
  457. }
  458. }
  459. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  460. var scene = this.getScene();
  461. this._batchCache.mustReturn = false;
  462. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  463. this._batchCache.visibleInstances[subMeshId] = null;
  464. if (this._visibleInstances) {
  465. var currentRenderId = scene.getRenderId();
  466. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  467. var selfRenderId = this._renderId;
  468. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  469. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  470. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  471. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  472. }
  473. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  474. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  475. this._batchCache.mustReturn = true;
  476. return this._batchCache;
  477. }
  478. if (currentRenderId !== selfRenderId) {
  479. this._batchCache.renderSelf[subMeshId] = false;
  480. }
  481. }
  482. this._renderIdForInstances[subMeshId] = currentRenderId;
  483. }
  484. return this._batchCache;
  485. }
  486. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  487. var visibleInstances = batch.visibleInstances[subMesh._id];
  488. var matricesCount = visibleInstances.length + 1;
  489. var bufferSize = matricesCount * 16 * 4;
  490. while (this._instancesBufferSize < bufferSize) {
  491. this._instancesBufferSize *= 2;
  492. }
  493. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  494. if (this._worldMatricesInstancesBuffer) {
  495. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  496. }
  497. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  498. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  499. }
  500. var offset = 0;
  501. var instancesCount = 0;
  502. var world = this.getWorldMatrix();
  503. if (batch.renderSelf[subMesh._id]) {
  504. world.copyToArray(this._worldMatricesInstancesArray, offset);
  505. offset += 16;
  506. instancesCount++;
  507. }
  508. if (visibleInstances) {
  509. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  510. var instance = visibleInstances[instanceIndex];
  511. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  512. offset += 16;
  513. instancesCount++;
  514. }
  515. }
  516. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  517. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  518. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  519. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  520. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  521. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  522. this._draw(subMesh, fillMode, instancesCount);
  523. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  524. }
  525. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  526. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  527. var scene = this.getScene();
  528. var engine = scene.getEngine();
  529. if (hardwareInstancedRendering) {
  530. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  531. } else {
  532. if (batch.renderSelf[subMesh._id]) {
  533. // Draw
  534. if (onBeforeDraw) {
  535. onBeforeDraw(false, this.getWorldMatrix());
  536. }
  537. this._draw(subMesh, fillMode);
  538. }
  539. if (batch.visibleInstances[subMesh._id]) {
  540. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  541. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  542. // World
  543. var world = instance.getWorldMatrix();
  544. if (onBeforeDraw) {
  545. onBeforeDraw(true, world);
  546. }
  547. // Draw
  548. this._draw(subMesh, fillMode);
  549. }
  550. }
  551. }
  552. }
  553. public render(subMesh: SubMesh): void {
  554. var scene = this.getScene();
  555. // Managing instances
  556. var batch = this._getInstancesRenderList(subMesh._id);
  557. if (batch.mustReturn) {
  558. return;
  559. }
  560. // Checking geometry state
  561. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  562. return;
  563. }
  564. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  565. this._onBeforeRenderCallbacks[callbackIndex](this);
  566. }
  567. var engine = scene.getEngine();
  568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  569. // Material
  570. var effectiveMaterial = subMesh.getMaterial();
  571. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  572. return;
  573. }
  574. // Outline - step 1
  575. var savedDepthWrite = engine.getDepthWrite();
  576. if (this.renderOutline) {
  577. engine.setDepthWrite(false);
  578. scene.getOutlineRenderer().render(subMesh, batch);
  579. engine.setDepthWrite(savedDepthWrite);
  580. }
  581. effectiveMaterial._preBind();
  582. var effect = effectiveMaterial.getEffect();
  583. // Bind
  584. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  585. this._bind(subMesh, effect, fillMode);
  586. var world = this.getWorldMatrix();
  587. effectiveMaterial.bind(world, this);
  588. // Draw
  589. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  590. (isInstance, world) => {
  591. if (isInstance) {
  592. effectiveMaterial.bindOnlyWorldMatrix(world);
  593. }
  594. });
  595. // Unbind
  596. effectiveMaterial.unbind();
  597. // Outline - step 2
  598. if (this.renderOutline && savedDepthWrite) {
  599. engine.setDepthWrite(true);
  600. engine.setColorWrite(false);
  601. scene.getOutlineRenderer().render(subMesh, batch);
  602. engine.setColorWrite(true);
  603. }
  604. // Overlay
  605. if (this.renderOverlay) {
  606. var currentMode = engine.getAlphaMode();
  607. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  608. scene.getOutlineRenderer().render(subMesh, batch, true);
  609. engine.setAlphaMode(currentMode);
  610. }
  611. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  612. this._onAfterRenderCallbacks[callbackIndex](this);
  613. }
  614. }
  615. public getEmittedParticleSystems(): ParticleSystem[] {
  616. var results = new Array<ParticleSystem>();
  617. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  618. var particleSystem = this.getScene().particleSystems[index];
  619. if (particleSystem.emitter === this) {
  620. results.push(particleSystem);
  621. }
  622. }
  623. return results;
  624. }
  625. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  626. var results = new Array<ParticleSystem>();
  627. var descendants = this.getDescendants();
  628. descendants.push(this);
  629. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  630. var particleSystem = this.getScene().particleSystems[index];
  631. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  632. results.push(particleSystem);
  633. }
  634. }
  635. return results;
  636. }
  637. public getChildren(): Node[] {
  638. var results = [];
  639. for (var index = 0; index < this.getScene().meshes.length; index++) {
  640. var mesh = this.getScene().meshes[index];
  641. if (mesh.parent === this) {
  642. results.push(mesh);
  643. }
  644. }
  645. return results;
  646. }
  647. public _checkDelayState(): void {
  648. var that = this;
  649. var scene = this.getScene();
  650. if (this._geometry) {
  651. this._geometry.load(scene);
  652. }
  653. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  654. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  655. scene._addPendingData(that);
  656. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  657. Tools.LoadFile(this.delayLoadingFile, data => {
  658. if (data instanceof ArrayBuffer) {
  659. this._delayLoadingFunction(data, this);
  660. }
  661. else {
  662. this._delayLoadingFunction(JSON.parse(data), this);
  663. }
  664. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  665. scene._removePendingData(this);
  666. },() => { }, scene.database, getBinaryData);
  667. }
  668. }
  669. public isInFrustum(frustumPlanes: Plane[]): boolean {
  670. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  671. return false;
  672. }
  673. if (!super.isInFrustum(frustumPlanes)) {
  674. return false;
  675. }
  676. this._checkDelayState();
  677. return true;
  678. }
  679. public setMaterialByID(id: string): void {
  680. var materials = this.getScene().materials;
  681. for (var index = 0; index < materials.length; index++) {
  682. if (materials[index].id === id) {
  683. this.material = materials[index];
  684. return;
  685. }
  686. }
  687. // Multi
  688. var multiMaterials = this.getScene().multiMaterials;
  689. for (index = 0; index < multiMaterials.length; index++) {
  690. if (multiMaterials[index].id === id) {
  691. this.material = multiMaterials[index];
  692. return;
  693. }
  694. }
  695. }
  696. public getAnimatables(): IAnimatable[] {
  697. var results = [];
  698. if (this.material) {
  699. results.push(this.material);
  700. }
  701. if (this.skeleton) {
  702. results.push(this.skeleton);
  703. }
  704. return results;
  705. }
  706. // Geometry
  707. public bakeTransformIntoVertices(transform: Matrix): void {
  708. // Position
  709. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  710. return;
  711. }
  712. this._resetPointsArrayCache();
  713. var data = this.getVerticesData(VertexBuffer.PositionKind);
  714. var temp = [];
  715. for (var index = 0; index < data.length; index += 3) {
  716. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  717. }
  718. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  719. // Normals
  720. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  721. return;
  722. }
  723. data = this.getVerticesData(VertexBuffer.NormalKind);
  724. temp = [];
  725. for (index = 0; index < data.length; index += 3) {
  726. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  727. }
  728. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  729. }
  730. // Cache
  731. public _resetPointsArrayCache(): void {
  732. this._positions = null;
  733. }
  734. public _generatePointsArray(): boolean {
  735. if (this._positions)
  736. return true;
  737. this._positions = [];
  738. var data = this.getVerticesData(VertexBuffer.PositionKind);
  739. if (!data) {
  740. return false;
  741. }
  742. for (var index = 0; index < data.length; index += 3) {
  743. this._positions.push(Vector3.FromArray(data, index));
  744. }
  745. return true;
  746. }
  747. // Clone
  748. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  749. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  750. }
  751. // Dispose
  752. public dispose(doNotRecurse?: boolean): void {
  753. if (this._geometry) {
  754. this._geometry.releaseForMesh(this, true);
  755. }
  756. // Instances
  757. if (this._worldMatricesInstancesBuffer) {
  758. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  759. this._worldMatricesInstancesBuffer = null;
  760. }
  761. while (this.instances.length) {
  762. this.instances[0].dispose();
  763. }
  764. super.dispose(doNotRecurse);
  765. }
  766. // Geometric tools
  767. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  768. var scene = this.getScene();
  769. var onload = img => {
  770. // Getting height map data
  771. var canvas = document.createElement("canvas");
  772. var context = canvas.getContext("2d");
  773. var heightMapWidth = img.width;
  774. var heightMapHeight = img.height;
  775. canvas.width = heightMapWidth;
  776. canvas.height = heightMapHeight;
  777. context.drawImage(img, 0, 0);
  778. // Create VertexData from map data
  779. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  780. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  781. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  782. //execute success callback, if set
  783. if (onSuccess) {
  784. onSuccess(this);
  785. }
  786. };
  787. Tools.LoadImage(url, onload,() => { }, scene.database);
  788. }
  789. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  790. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  791. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  792. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  793. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  794. return;
  795. }
  796. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  797. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  798. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  799. var position = Vector3.Zero();
  800. var normal = Vector3.Zero();
  801. var uv = Vector2.Zero();
  802. for (var index = 0; index < positions.length; index += 3) {
  803. Vector3.FromArrayToRef(positions, index, position);
  804. Vector3.FromArrayToRef(normals, index, normal);
  805. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  806. // Compute height
  807. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  808. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  809. var pos = (u + v * heightMapWidth) * 4;
  810. var r = buffer[pos] / 255.0;
  811. var g = buffer[pos + 1] / 255.0;
  812. var b = buffer[pos + 2] / 255.0;
  813. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  814. normal.normalize();
  815. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  816. position = position.add(normal);
  817. position.toArray(positions, index);
  818. }
  819. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  820. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  821. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  822. }
  823. public convertToFlatShadedMesh(): void {
  824. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  825. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  826. var kinds = this.getVerticesDataKinds();
  827. var vbs = [];
  828. var data = [];
  829. var newdata = [];
  830. var updatableNormals = false;
  831. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  832. var kind = kinds[kindIndex];
  833. var vertexBuffer = this.getVertexBuffer(kind);
  834. if (kind === VertexBuffer.NormalKind) {
  835. updatableNormals = vertexBuffer.isUpdatable();
  836. kinds.splice(kindIndex, 1);
  837. kindIndex--;
  838. continue;
  839. }
  840. vbs[kind] = vertexBuffer;
  841. data[kind] = vbs[kind].getData();
  842. newdata[kind] = [];
  843. }
  844. // Save previous submeshes
  845. var previousSubmeshes = this.subMeshes.slice(0);
  846. var indices = this.getIndices();
  847. var totalIndices = this.getTotalIndices();
  848. // Generating unique vertices per face
  849. for (var index = 0; index < totalIndices; index++) {
  850. var vertexIndex = indices[index];
  851. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  852. kind = kinds[kindIndex];
  853. var stride = vbs[kind].getStrideSize();
  854. for (var offset = 0; offset < stride; offset++) {
  855. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  856. }
  857. }
  858. }
  859. // Updating faces & normal
  860. var normals = [];
  861. var positions = newdata[VertexBuffer.PositionKind];
  862. for (index = 0; index < totalIndices; index += 3) {
  863. indices[index] = index;
  864. indices[index + 1] = index + 1;
  865. indices[index + 2] = index + 2;
  866. var p1 = Vector3.FromArray(positions, index * 3);
  867. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  868. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  869. var p1p2 = p1.subtract(p2);
  870. var p3p2 = p3.subtract(p2);
  871. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  872. // Store same normals for every vertex
  873. for (var localIndex = 0; localIndex < 3; localIndex++) {
  874. normals.push(normal.x);
  875. normals.push(normal.y);
  876. normals.push(normal.z);
  877. }
  878. }
  879. this.setIndices(indices);
  880. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  881. // Updating vertex buffers
  882. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  883. kind = kinds[kindIndex];
  884. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  885. }
  886. // Updating submeshes
  887. this.releaseSubMeshes();
  888. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  889. var previousOne = previousSubmeshes[submeshIndex];
  890. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  891. }
  892. this.synchronizeInstances();
  893. }
  894. // Instances
  895. public createInstance(name: string): InstancedMesh {
  896. return new InstancedMesh(name, this);
  897. }
  898. public synchronizeInstances(): void {
  899. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  900. var instance = this.instances[instanceIndex];
  901. instance._syncSubMeshes();
  902. }
  903. }
  904. /**
  905. * Simplify the mesh according to the given array of settings.
  906. * Function will return immediately and will simplify async.
  907. * @param settings a collection of simplification settings.
  908. * @param parallelProcessing should all levels calculate parallel or one after the other.
  909. * @param type the type of simplification to run.
  910. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  911. */
  912. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  913. this.getScene().simplificationQueue.addTask({
  914. settings: settings,
  915. parallelProcessing: parallelProcessing,
  916. mesh: this,
  917. simplificationType: simplificationType,
  918. successCallback: successCallback
  919. });
  920. }
  921. /**
  922. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  923. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  924. * This should be used together with the simplification to avoid disappearing triangles.
  925. * @param successCallback an optional success callback to be called after the optimization finished.
  926. */
  927. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  928. var indices = this.getIndices();
  929. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  930. var vectorPositions = [];
  931. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  932. vectorPositions.push(Vector3.FromArray(positions, pos));
  933. }
  934. var dupes = [];
  935. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40,(iteration) => {
  936. var realPos = vectorPositions.length - 1 - iteration;
  937. var testedPosition = vectorPositions[realPos];
  938. for (var j = 0; j < realPos; ++j) {
  939. var againstPosition = vectorPositions[j];
  940. if (testedPosition.equals(againstPosition)) {
  941. dupes[realPos] = j;
  942. break;
  943. }
  944. }
  945. },() => {
  946. for (var i = 0; i < indices.length; ++i) {
  947. indices[i] = dupes[indices[i]] || indices[i];
  948. }
  949. //indices are now reordered
  950. var originalSubMeshes = this.subMeshes.slice(0);
  951. this.setIndices(indices);
  952. this.subMeshes = originalSubMeshes;
  953. if (successCallback) {
  954. successCallback(this);
  955. }
  956. });
  957. }
  958. // Statics
  959. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, ribbonInstance: Mesh = null): Mesh {
  960. if (ribbonInstance) { // existing ribbon instance update
  961. // positionFunction : ribbon case
  962. // only pathArray and sideOrientation parameters are taken into account for positions update
  963. var positionsOfRibbon = function (pathArray, sideOrientation) {
  964. var positionFunction = function (positions) {
  965. var minlg = pathArray[0].length;
  966. var i = 0;
  967. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  968. for (var si = 1; si <= ns; si++) {
  969. for (var p = 0; p < pathArray.length; p++) {
  970. var path = pathArray[p];
  971. var l = path.length;
  972. minlg = (minlg < l) ? minlg : l;
  973. var j = 0;
  974. while (j < minlg) {
  975. positions[i] = path[j].x;
  976. positions[i + 1] = path[j].y;
  977. positions[i + 2] = path[j].z;
  978. j++;
  979. i += 3;
  980. }
  981. }
  982. }
  983. };
  984. return positionFunction;
  985. };
  986. var sideOrientation = ribbonInstance.sideOrientation;
  987. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  988. ribbonInstance.updateMeshPositions(positionFunction, true);
  989. return ribbonInstance;
  990. }
  991. else { // new ribbon creation
  992. var ribbon = new Mesh(name, scene);
  993. ribbon.sideOrientation = sideOrientation;
  994. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  995. vertexData.applyToMesh(ribbon, updatable);
  996. return ribbon;
  997. }
  998. }
  999. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1000. var disc = new Mesh(name, scene);
  1001. var vertexData = VertexData.CreateDisc(radius, tessellation, sideOrientation);
  1002. vertexData.applyToMesh(disc, updatable);
  1003. return disc;
  1004. }
  1005. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1006. var box = new Mesh(name, scene);
  1007. var vertexData = VertexData.CreateBox(size, sideOrientation);
  1008. vertexData.applyToMesh(box, updatable);
  1009. return box;
  1010. }
  1011. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1012. var sphere = new Mesh(name, scene);
  1013. var vertexData = VertexData.CreateSphere(segments, diameter, sideOrientation);
  1014. vertexData.applyToMesh(sphere, updatable);
  1015. return sphere;
  1016. }
  1017. // Cylinder and cone (Code inspired by SharpDX.org)
  1018. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1019. // subdivisions is a new parameter, we need to support old signature
  1020. if (scene === undefined || !(scene instanceof Scene)) {
  1021. if (scene !== undefined) {
  1022. updatable = scene;
  1023. }
  1024. scene = <Scene>subdivisions;
  1025. subdivisions = 1;
  1026. }
  1027. var cylinder = new Mesh(name, scene);
  1028. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  1029. vertexData.applyToMesh(cylinder, updatable);
  1030. return cylinder;
  1031. }
  1032. // Torus (Code from SharpDX.org)
  1033. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1034. var torus = new Mesh(name, scene);
  1035. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1036. vertexData.applyToMesh(torus, updatable);
  1037. return torus;
  1038. }
  1039. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1040. var torusKnot = new Mesh(name, scene);
  1041. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1042. vertexData.applyToMesh(torusKnot, updatable);
  1043. return torusKnot;
  1044. }
  1045. // Lines
  1046. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, linesInstance: LinesMesh = null): LinesMesh {
  1047. if (linesInstance) { // lines update
  1048. var positionsOfLines = function (points) {
  1049. var positionFunction = function (positions) {
  1050. var i = 0;
  1051. for (var p = 0; p < points.length; p++) {
  1052. positions[i] = points[p].x;
  1053. positions[i + 1] = points[p].y;
  1054. positions[i + 2] = points[p].z;
  1055. i += 3;
  1056. }
  1057. };
  1058. return positionFunction;
  1059. };
  1060. var positionFunction = positionsOfLines(points);
  1061. linesInstance.updateMeshPositions(positionFunction, false);
  1062. return linesInstance;
  1063. }
  1064. // lines creation
  1065. var lines = new LinesMesh(name, scene, updatable);
  1066. var vertexData = VertexData.CreateLines(points);
  1067. vertexData.applyToMesh(lines, updatable);
  1068. return lines;
  1069. }
  1070. // Extrusion
  1071. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1072. scale = scale || 1;
  1073. rotation = rotation || 0;
  1074. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1075. return extruded;
  1076. }
  1077. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1078. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1079. return extrudedCustom;
  1080. }
  1081. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh): Mesh {
  1082. // extrusion geometry
  1083. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  1084. var tangents = path3D.getTangents();
  1085. var normals = path3D.getNormals();
  1086. var binormals = path3D.getBinormals();
  1087. var distances = path3D.getDistances();
  1088. var angle = 0;
  1089. var returnScale: { (i: number, distance: number): number; } = (i, distance) => { return scale; };
  1090. var returnRotation: { (i: number, distance: number): number; } = (i, distance) => { return rotation; };
  1091. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1092. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1093. var index = 0;
  1094. for (var i = 0; i < curve.length; i++) {
  1095. var shapePath = new Array<Vector3>();
  1096. var angleStep = rotate(i, distances[i]);
  1097. var scaleRatio = scl(i, distances[i]);
  1098. for (var p = 0; p < shape.length; p++) {
  1099. var rotationMatrix = Matrix.RotationAxis(tangents[i], angle);
  1100. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1101. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1102. shapePath.push(rotated);
  1103. }
  1104. shapePaths[index] = shapePath;
  1105. angle += angleStep;
  1106. index++;
  1107. }
  1108. // cap
  1109. var capPath = function (shapePath) {
  1110. var pointCap = Array<Vector3>();
  1111. var barycenter = Vector3.Zero();
  1112. var i: number;
  1113. for (i = 0; i < shapePath.length; i++) {
  1114. barycenter.addInPlace(shapePath[i]);
  1115. }
  1116. barycenter.scaleInPlace(1 / shapePath.length);
  1117. for (i = 0; i < shapePath.length; i++) {
  1118. pointCap.push(barycenter);
  1119. }
  1120. return pointCap;
  1121. };
  1122. switch (cap) {
  1123. case BABYLON.Mesh.NO_CAP:
  1124. break;
  1125. case BABYLON.Mesh.CAP_START:
  1126. shapePaths.unshift(capPath(shapePaths[0]));
  1127. break;
  1128. case BABYLON.Mesh.CAP_END:
  1129. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1130. break;
  1131. case BABYLON.Mesh.CAP_ALL:
  1132. shapePaths.unshift(capPath(shapePaths[0]));
  1133. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1134. break;
  1135. default:
  1136. break;
  1137. }
  1138. return shapePaths;
  1139. };
  1140. if (instance) { // instance update
  1141. var path3D = ((<any>instance).path3D).update(curve);
  1142. var pathArray = extrusionPathArray(shape, curve,(<any>instance).path3D,(<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction,(<any>instance).cap, custom);
  1143. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1144. return instance;
  1145. }
  1146. // extruded shape creation
  1147. var path3D = <any>new Path3D(curve);
  1148. var newShapePaths = new Array<Array<Vector3>>();
  1149. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1150. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1151. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1152. (<any>extrudedGeneric).pathArray = pathArray;
  1153. (<any>extrudedGeneric).path3D = path3D;
  1154. (<any>extrudedGeneric).cap = cap;
  1155. return extrudedGeneric;
  1156. }
  1157. // Plane & ground
  1158. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1159. var plane = new Mesh(name, scene);
  1160. var vertexData = VertexData.CreatePlane(size, sideOrientation);
  1161. vertexData.applyToMesh(plane, updatable);
  1162. return plane;
  1163. }
  1164. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1165. var ground = new GroundMesh(name, scene);
  1166. ground._setReady(false);
  1167. ground._subdivisions = subdivisions;
  1168. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  1169. vertexData.applyToMesh(ground, updatable);
  1170. ground._setReady(true);
  1171. return ground;
  1172. }
  1173. 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 {
  1174. var tiledGround = new Mesh(name, scene);
  1175. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1176. vertexData.applyToMesh(tiledGround, updatable);
  1177. return tiledGround;
  1178. }
  1179. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh {
  1180. var ground = new GroundMesh(name, scene);
  1181. ground._subdivisions = subdivisions;
  1182. ground._setReady(false);
  1183. var onload = img => {
  1184. // Getting height map data
  1185. var canvas = document.createElement("canvas");
  1186. var context = canvas.getContext("2d");
  1187. var heightMapWidth = img.width;
  1188. var heightMapHeight = img.height;
  1189. canvas.width = heightMapWidth;
  1190. canvas.height = heightMapHeight;
  1191. context.drawImage(img, 0, 0);
  1192. // Create VertexData from map data
  1193. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1194. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1195. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1196. vertexData.applyToMesh(ground, updatable);
  1197. ground._setReady(true);
  1198. //execute ready callback, if set
  1199. if (onReady) {
  1200. onReady(ground);
  1201. }
  1202. };
  1203. Tools.LoadImage(url, onload,() => { }, scene.database);
  1204. return ground;
  1205. }
  1206. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, tubeInstance: Mesh = null): Mesh {
  1207. // tube geometry
  1208. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  1209. var tangents = path3D.getTangents();
  1210. var normals = path3D.getNormals();
  1211. var distances = path3D.getDistances();
  1212. var pi2 = Math.PI * 2;
  1213. var step = pi2 / tessellation;
  1214. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1215. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1216. var circlePath: Vector3[];
  1217. var rad: number;
  1218. var normal: Vector3;
  1219. var rotated: Vector3;
  1220. var rotationMatrix: Matrix;
  1221. var index = 0;
  1222. for (var i = 0; i < path.length; i++) {
  1223. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1224. circlePath = Array<Vector3>(); // current circle array
  1225. normal = normals[i]; // current normal
  1226. for (var t = 0; t < tessellation; t++) {
  1227. rotationMatrix = Matrix.RotationAxis(tangents[i], step * t);
  1228. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1229. circlePath.push(rotated);
  1230. }
  1231. circlePath.push(circlePath[0]);
  1232. circlePaths[index] = circlePath;
  1233. index++;
  1234. }
  1235. // cap
  1236. var capPath = function (nbPoints, pathIndex) {
  1237. var pointCap = Array<Vector3>();
  1238. for (var i = 0; i < nbPoints; i++) {
  1239. pointCap.push(path[pathIndex]);
  1240. }
  1241. return pointCap;
  1242. };
  1243. switch (cap) {
  1244. case BABYLON.Mesh.NO_CAP:
  1245. break;
  1246. case BABYLON.Mesh.CAP_START:
  1247. circlePaths.unshift(capPath(tessellation + 1, 0));
  1248. break;
  1249. case BABYLON.Mesh.CAP_END:
  1250. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1251. break;
  1252. case BABYLON.Mesh.CAP_ALL:
  1253. circlePaths.unshift(capPath(tessellation + 1, 0));
  1254. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1255. break;
  1256. default:
  1257. break;
  1258. }
  1259. return circlePaths;
  1260. };
  1261. if (tubeInstance) { // tube update
  1262. var path3D = ((<any>tubeInstance).path3D).update(path);
  1263. var pathArray = tubePathArray(path, path3D,(<any>tubeInstance).pathArray, radius,(<any>tubeInstance).tessellation, radiusFunction,(<any>tubeInstance).cap);
  1264. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1265. return tubeInstance;
  1266. }
  1267. // tube creation
  1268. var path3D = <any>new Path3D(path);
  1269. var newPathArray = new Array<Array<Vector3>>();
  1270. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1271. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1272. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1273. (<any>tube).pathArray = pathArray;
  1274. (<any>tube).path3D = path3D;
  1275. (<any>tube).tessellation = tessellation;
  1276. (<any>tube).cap = cap;
  1277. return tube;
  1278. }
  1279. // Decals
  1280. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number = 0) {
  1281. var indices = sourceMesh.getIndices();
  1282. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  1283. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  1284. // Getting correct rotation
  1285. if (!normal) {
  1286. var target = new Vector3(0, 0, 1);
  1287. var camera = sourceMesh.getScene().activeCamera;
  1288. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1289. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1290. }
  1291. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1292. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1293. var pitch = Math.atan2(normal.y, len);
  1294. // Matrix
  1295. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1296. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1297. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1298. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1299. var vertexData = new VertexData();
  1300. vertexData.indices = [];
  1301. vertexData.positions = [];
  1302. vertexData.normals = [];
  1303. vertexData.uvs = [];
  1304. var currentVertexDataIndex = 0;
  1305. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1306. var vertexId = indices[indexId];
  1307. var result = new PositionNormalVertex();
  1308. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1309. // Send vector to decal local world
  1310. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1311. // Get normal
  1312. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1313. return result;
  1314. }
  1315. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1316. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  1317. if (vertices.length === 0) {
  1318. return vertices;
  1319. }
  1320. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1321. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1322. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1323. return new PositionNormalVertex(
  1324. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1325. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1326. );
  1327. }
  1328. var result = new Array<PositionNormalVertex>();
  1329. for (var index = 0; index < vertices.length; index += 3) {
  1330. var v1Out: boolean;
  1331. var v2Out: boolean;
  1332. var v3Out: boolean;
  1333. var total = 0;
  1334. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  1335. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1336. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1337. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1338. v1Out = d1 > 0;
  1339. v2Out = d2 > 0;
  1340. v3Out = d3 > 0;
  1341. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1342. switch (total) {
  1343. case 0:
  1344. result.push(vertices[index]);
  1345. result.push(vertices[index + 1]);
  1346. result.push(vertices[index + 2]);
  1347. break;
  1348. case 1:
  1349. if (v1Out) {
  1350. nV1 = vertices[index + 1];
  1351. nV2 = vertices[index + 2];
  1352. nV3 = clipVertices(vertices[index], nV1);
  1353. nV4 = clipVertices(vertices[index], nV2);
  1354. }
  1355. if (v2Out) {
  1356. nV1 = vertices[index];
  1357. nV2 = vertices[index + 2];
  1358. nV3 = clipVertices(vertices[index + 1], nV1);
  1359. nV4 = clipVertices(vertices[index + 1], nV2);
  1360. result.push(nV3);
  1361. result.push(nV2.clone());
  1362. result.push(nV1.clone());
  1363. result.push(nV2.clone());
  1364. result.push(nV3.clone());
  1365. result.push(nV4);
  1366. break;
  1367. }
  1368. if (v3Out) {
  1369. nV1 = vertices[index];
  1370. nV2 = vertices[index + 1];
  1371. nV3 = clipVertices(vertices[index + 2], nV1);
  1372. nV4 = clipVertices(vertices[index + 2], nV2);
  1373. }
  1374. result.push(nV1.clone());
  1375. result.push(nV2.clone());
  1376. result.push(nV3);
  1377. result.push(nV4);
  1378. result.push(nV3.clone());
  1379. result.push(nV2.clone());
  1380. break;
  1381. case 2:
  1382. if (!v1Out) {
  1383. nV1 = vertices[index].clone();
  1384. nV2 = clipVertices(nV1, vertices[index + 1]);
  1385. nV3 = clipVertices(nV1, vertices[index + 2]);
  1386. result.push(nV1);
  1387. result.push(nV2);
  1388. result.push(nV3);
  1389. }
  1390. if (!v2Out) {
  1391. nV1 = vertices[index + 1].clone();
  1392. nV2 = clipVertices(nV1, vertices[index + 2]);
  1393. nV3 = clipVertices(nV1, vertices[index]);
  1394. result.push(nV1);
  1395. result.push(nV2);
  1396. result.push(nV3);
  1397. }
  1398. if (!v3Out) {
  1399. nV1 = vertices[index + 2].clone();
  1400. nV2 = clipVertices(nV1, vertices[index]);
  1401. nV3 = clipVertices(nV1, vertices[index + 1]);
  1402. result.push(nV1);
  1403. result.push(nV2);
  1404. result.push(nV3);
  1405. }
  1406. break;
  1407. case 3:
  1408. break;
  1409. }
  1410. }
  1411. return result;
  1412. }
  1413. for (var index = 0; index < indices.length; index += 3) {
  1414. var faceVertices = new Array<PositionNormalVertex>();
  1415. faceVertices.push(extractDecalVector3(index));
  1416. faceVertices.push(extractDecalVector3(index + 1));
  1417. faceVertices.push(extractDecalVector3(index + 2));
  1418. // Clip
  1419. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1420. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1421. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1422. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1423. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1424. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1425. if (faceVertices.length === 0) {
  1426. continue;
  1427. }
  1428. // Add UVs and get back to world
  1429. var localRotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  1430. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1431. var vertex = faceVertices[vIndex];
  1432. vertexData.indices.push(currentVertexDataIndex);
  1433. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1434. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1435. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1436. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1437. currentVertexDataIndex++;
  1438. }
  1439. }
  1440. // Return mesh
  1441. var decal = new Mesh(name, sourceMesh.getScene());
  1442. vertexData.applyToMesh(decal);
  1443. decal.position = position.clone();
  1444. decal.rotation = new Vector3(pitch, yaw, angle);
  1445. return decal;
  1446. }
  1447. // Tools
  1448. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1449. var minVector: Vector3 = null;
  1450. var maxVector: Vector3 = null;
  1451. for (var i in meshes) {
  1452. var mesh = meshes[i];
  1453. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1454. if (!minVector) {
  1455. minVector = boundingBox.minimumWorld;
  1456. maxVector = boundingBox.maximumWorld;
  1457. continue;
  1458. }
  1459. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1460. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1461. }
  1462. return {
  1463. min: minVector,
  1464. max: maxVector
  1465. };
  1466. }
  1467. public static Center(meshesOrMinMaxVector): Vector3 {
  1468. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1469. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1470. }
  1471. /**
  1472. * Merge the array of meshes into a single mesh for performance reasons.
  1473. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1474. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1475. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1476. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1477. */
  1478. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1479. if (!allow32BitsIndices) {
  1480. var totalVertices = 0;
  1481. // Counting vertices
  1482. for (var index = 0; index < meshes.length; index++) {
  1483. if (meshes[index]) {
  1484. totalVertices += meshes[index].getTotalVertices();
  1485. if (totalVertices > 65536) {
  1486. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1487. return null;
  1488. }
  1489. }
  1490. }
  1491. }
  1492. // Merge
  1493. var vertexData: VertexData;
  1494. var otherVertexData: VertexData;
  1495. var source: Mesh;
  1496. for (index = 0; index < meshes.length; index++) {
  1497. if (meshes[index]) {
  1498. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1499. otherVertexData.transform(meshes[index].getWorldMatrix());
  1500. if (vertexData) {
  1501. vertexData.merge(otherVertexData);
  1502. } else {
  1503. vertexData = otherVertexData;
  1504. source = meshes[index];
  1505. }
  1506. }
  1507. }
  1508. if (!meshSubclass) {
  1509. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1510. }
  1511. vertexData.applyToMesh(meshSubclass);
  1512. // Setting properties
  1513. meshSubclass.material = source.material;
  1514. meshSubclass.checkCollisions = source.checkCollisions;
  1515. // Cleaning
  1516. if (disposeSource) {
  1517. for (index = 0; index < meshes.length; index++) {
  1518. if (meshes[index]) {
  1519. meshes[index].dispose();
  1520. }
  1521. }
  1522. }
  1523. return meshSubclass;
  1524. }
  1525. }
  1526. }