babylon.mesh.ts 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  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: any, mesh: 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. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  64. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  65. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  66. /**
  67. * @constructor
  68. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  69. * @param {Scene} scene - The scene to add this mesh to.
  70. * @param {Node} parent - The parent of this mesh, if it has one
  71. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  72. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  73. * When false, achieved by calling a clone(), also passing False.
  74. * This will make creation of children, recursive.
  75. */
  76. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  77. super(name, scene);
  78. if (source) {
  79. // Geometry
  80. if (source._geometry) {
  81. source._geometry.applyToMesh(this);
  82. }
  83. // Deep copy
  84. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  85. this.id = name + "." + source.id;
  86. // Material
  87. this.material = source.material;
  88. var index: number;
  89. if (!doNotCloneChildren) {
  90. // Children
  91. for (index = 0; index < scene.meshes.length; index++) {
  92. var mesh = scene.meshes[index];
  93. if (mesh.parent === source) {
  94. // doNotCloneChildren is always going to be False
  95. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  96. }
  97. }
  98. }
  99. // Particles
  100. for (index = 0; index < scene.particleSystems.length; index++) {
  101. var system = scene.particleSystems[index];
  102. if (system.emitter === source) {
  103. system.clone(system.name, this);
  104. }
  105. }
  106. this.computeWorldMatrix(true);
  107. }
  108. // Parent
  109. if (parent !== null) {
  110. this.parent = parent;
  111. }
  112. }
  113. // Methods
  114. public get hasLODLevels(): boolean {
  115. return this._LODLevels.length > 0;
  116. }
  117. private _sortLODLevels(): void {
  118. this._LODLevels.sort((a, b) => {
  119. if (a.distance < b.distance) {
  120. return 1;
  121. }
  122. if (a.distance > b.distance) {
  123. return -1;
  124. }
  125. return 0;
  126. });
  127. }
  128. /**
  129. * Add a mesh as LOD level triggered at the given distance.
  130. * @param {number} distance - the distance from the center of the object to show this level
  131. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  132. * @return {BABYLON.Mesh} this mesh (for chaining)
  133. */
  134. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  135. if (mesh && mesh._masterMesh) {
  136. Tools.Warn("You cannot use a mesh as LOD level twice");
  137. return this;
  138. }
  139. var level = new Internals.MeshLODLevel(distance, mesh);
  140. this._LODLevels.push(level);
  141. if (mesh) {
  142. mesh._masterMesh = this;
  143. }
  144. this._sortLODLevels();
  145. return this;
  146. }
  147. public getLODLevelAtDistance(distance: number): Mesh {
  148. for (var index = 0; index < this._LODLevels.length; index++) {
  149. var level = this._LODLevels[index];
  150. if (level.distance === distance) {
  151. return level.mesh;
  152. }
  153. }
  154. return null;
  155. }
  156. /**
  157. * Remove a mesh from the LOD array
  158. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  159. * @return {BABYLON.Mesh} this mesh (for chaining)
  160. */
  161. public removeLODLevel(mesh: Mesh): Mesh {
  162. for (var index = 0; index < this._LODLevels.length; index++) {
  163. if (this._LODLevels[index].mesh === mesh) {
  164. this._LODLevels.splice(index, 1);
  165. if (mesh) {
  166. mesh._masterMesh = null;
  167. }
  168. }
  169. }
  170. this._sortLODLevels();
  171. return this;
  172. }
  173. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  174. if (!this._LODLevels || this._LODLevels.length === 0) {
  175. return this;
  176. }
  177. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  178. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  179. if (this.onLODLevelSelection) {
  180. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  181. }
  182. return this;
  183. }
  184. for (var index = 0; index < this._LODLevels.length; index++) {
  185. var level = this._LODLevels[index];
  186. if (level.distance < distanceToCamera) {
  187. if (level.mesh) {
  188. level.mesh._preActivate();
  189. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  190. }
  191. if (this.onLODLevelSelection) {
  192. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  193. }
  194. return level.mesh;
  195. }
  196. }
  197. if (this.onLODLevelSelection) {
  198. this.onLODLevelSelection(distanceToCamera, this, this);
  199. }
  200. return this;
  201. }
  202. public get geometry(): Geometry {
  203. return this._geometry;
  204. }
  205. public getTotalVertices(): number {
  206. if (!this._geometry) {
  207. return 0;
  208. }
  209. return this._geometry.getTotalVertices();
  210. }
  211. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] {
  212. if (!this._geometry) {
  213. return null;
  214. }
  215. return this._geometry.getVerticesData(kind, copyWhenShared);
  216. }
  217. public getVertexBuffer(kind): VertexBuffer {
  218. if (!this._geometry) {
  219. return undefined;
  220. }
  221. return this._geometry.getVertexBuffer(kind);
  222. }
  223. public isVerticesDataPresent(kind: string): boolean {
  224. if (!this._geometry) {
  225. if (this._delayInfo) {
  226. return this._delayInfo.indexOf(kind) !== -1;
  227. }
  228. return false;
  229. }
  230. return this._geometry.isVerticesDataPresent(kind);
  231. }
  232. public getVerticesDataKinds(): string[] {
  233. if (!this._geometry) {
  234. var result = [];
  235. if (this._delayInfo) {
  236. for (var kind in this._delayInfo) {
  237. result.push(kind);
  238. }
  239. }
  240. return result;
  241. }
  242. return this._geometry.getVerticesDataKinds();
  243. }
  244. public getTotalIndices(): number {
  245. if (!this._geometry) {
  246. return 0;
  247. }
  248. return this._geometry.getTotalIndices();
  249. }
  250. public getIndices(copyWhenShared?: boolean): number[] {
  251. if (!this._geometry) {
  252. return [];
  253. }
  254. return this._geometry.getIndices(copyWhenShared);
  255. }
  256. public get isBlocked(): boolean {
  257. return this._masterMesh !== null && this._masterMesh !== undefined;
  258. }
  259. public isReady(): boolean {
  260. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  261. return false;
  262. }
  263. return super.isReady();
  264. }
  265. public isDisposed(): boolean {
  266. return this._isDisposed;
  267. }
  268. public get sideOrientation(): number {
  269. return this._sideOrientation;
  270. }
  271. public set sideOrientation(sideO: number) {
  272. this._sideOrientation = sideO;
  273. }
  274. public get areNormalsFrozen(): boolean {
  275. return this._areNormalsFrozen;
  276. }
  277. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  278. public freezeNormals(): void {
  279. this._areNormalsFrozen = true;
  280. }
  281. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  282. public unfreezeNormals(): void {
  283. this._areNormalsFrozen = false;
  284. }
  285. // Methods
  286. public _preActivate(): void {
  287. var sceneRenderId = this.getScene().getRenderId();
  288. if (this._preActivateId === sceneRenderId) {
  289. return;
  290. }
  291. this._preActivateId = sceneRenderId;
  292. this._visibleInstances = null;
  293. }
  294. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  295. if (!this._visibleInstances) {
  296. this._visibleInstances = {};
  297. this._visibleInstances.defaultRenderId = renderId;
  298. this._visibleInstances.selfDefaultRenderId = this._renderId;
  299. }
  300. if (!this._visibleInstances[renderId]) {
  301. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  302. }
  303. this._visibleInstances[renderId].push(instance);
  304. }
  305. public refreshBoundingInfo(): void {
  306. var data = this.getVerticesData(VertexBuffer.PositionKind);
  307. if (data) {
  308. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  309. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  310. }
  311. if (this.subMeshes) {
  312. for (var index = 0; index < this.subMeshes.length; index++) {
  313. this.subMeshes[index].refreshBoundingInfo();
  314. }
  315. }
  316. this._updateBoundingInfo();
  317. }
  318. public _createGlobalSubMesh(): SubMesh {
  319. var totalVertices = this.getTotalVertices();
  320. if (!totalVertices || !this.getIndices()) {
  321. return null;
  322. }
  323. this.releaseSubMeshes();
  324. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  325. }
  326. public subdivide(count: number): void {
  327. if (count < 1) {
  328. return;
  329. }
  330. var totalIndices = this.getTotalIndices();
  331. var subdivisionSize = (totalIndices / count) | 0;
  332. var offset = 0;
  333. // Ensure that subdivisionSize is a multiple of 3
  334. while (subdivisionSize % 3 !== 0) {
  335. subdivisionSize++;
  336. }
  337. this.releaseSubMeshes();
  338. for (var index = 0; index < count; index++) {
  339. if (offset >= totalIndices) {
  340. break;
  341. }
  342. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  343. offset += subdivisionSize;
  344. }
  345. this.synchronizeInstances();
  346. }
  347. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  348. if (kind instanceof Array) {
  349. var temp = data;
  350. data = kind;
  351. kind = temp;
  352. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  353. }
  354. if (!this._geometry) {
  355. var vertexData = new VertexData();
  356. vertexData.set(data, kind);
  357. var scene = this.getScene();
  358. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  359. }
  360. else {
  361. this._geometry.setVerticesData(kind, data, updatable, stride);
  362. }
  363. }
  364. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  365. if (!this._geometry) {
  366. return;
  367. }
  368. if (!makeItUnique) {
  369. this._geometry.updateVerticesData(kind, data, updateExtends);
  370. }
  371. else {
  372. this.makeGeometryUnique();
  373. this.updateVerticesData(kind, data, updateExtends, false);
  374. }
  375. }
  376. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  377. if (!this._geometry) {
  378. return;
  379. }
  380. if (!makeItUnique) {
  381. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  382. }
  383. else {
  384. this.makeGeometryUnique();
  385. this.updateVerticesDataDirectly(kind, data, offset, false);
  386. }
  387. }
  388. // Mesh positions update function :
  389. // updates the mesh positions according to the positionFunction returned values.
  390. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  391. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  392. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  393. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  394. positionFunction(positions);
  395. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  396. if (computeNormals) {
  397. var indices = this.getIndices();
  398. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  399. VertexData.ComputeNormals(positions, indices, normals);
  400. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  401. }
  402. }
  403. public makeGeometryUnique() {
  404. if (!this._geometry) {
  405. return;
  406. }
  407. var geometry = this._geometry.copy(Geometry.RandomId());
  408. geometry.applyToMesh(this);
  409. }
  410. public setIndices(indices: number[], totalVertices?: number): void {
  411. if (!this._geometry) {
  412. var vertexData = new VertexData();
  413. vertexData.indices = indices;
  414. var scene = this.getScene();
  415. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  416. }
  417. else {
  418. this._geometry.setIndices(indices, totalVertices);
  419. }
  420. }
  421. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  422. var engine = this.getScene().getEngine();
  423. // Wireframe
  424. var indexToBind;
  425. switch (fillMode) {
  426. case Material.PointFillMode:
  427. indexToBind = null;
  428. break;
  429. case Material.WireFrameFillMode:
  430. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  431. break;
  432. default:
  433. case Material.TriangleFillMode:
  434. indexToBind = this._geometry.getIndexBuffer();
  435. break;
  436. }
  437. // VBOs
  438. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  439. }
  440. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  441. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  442. return;
  443. }
  444. var engine = this.getScene().getEngine();
  445. // Draw order
  446. switch (fillMode) {
  447. case Material.PointFillMode:
  448. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  449. break;
  450. case Material.WireFrameFillMode:
  451. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  452. break;
  453. default:
  454. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  455. }
  456. }
  457. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  458. this._onBeforeRenderCallbacks.push(func);
  459. }
  460. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  461. var index = this._onBeforeRenderCallbacks.indexOf(func);
  462. if (index > -1) {
  463. this._onBeforeRenderCallbacks.splice(index, 1);
  464. }
  465. }
  466. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  467. this._onAfterRenderCallbacks.push(func);
  468. }
  469. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  470. var index = this._onAfterRenderCallbacks.indexOf(func);
  471. if (index > -1) {
  472. this._onAfterRenderCallbacks.splice(index, 1);
  473. }
  474. }
  475. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  476. var scene = this.getScene();
  477. this._batchCache.mustReturn = false;
  478. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  479. this._batchCache.visibleInstances[subMeshId] = null;
  480. if (this._visibleInstances) {
  481. var currentRenderId = scene.getRenderId();
  482. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  483. var selfRenderId = this._renderId;
  484. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  485. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  486. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  487. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  488. }
  489. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  490. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  491. this._batchCache.mustReturn = true;
  492. return this._batchCache;
  493. }
  494. if (currentRenderId !== selfRenderId) {
  495. this._batchCache.renderSelf[subMeshId] = false;
  496. }
  497. }
  498. this._renderIdForInstances[subMeshId] = currentRenderId;
  499. }
  500. return this._batchCache;
  501. }
  502. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  503. var visibleInstances = batch.visibleInstances[subMesh._id];
  504. var matricesCount = visibleInstances.length + 1;
  505. var bufferSize = matricesCount * 16 * 4;
  506. while (this._instancesBufferSize < bufferSize) {
  507. this._instancesBufferSize *= 2;
  508. }
  509. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  510. if (this._worldMatricesInstancesBuffer) {
  511. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  512. }
  513. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  514. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  515. }
  516. var offset = 0;
  517. var instancesCount = 0;
  518. var world = this.getWorldMatrix();
  519. if (batch.renderSelf[subMesh._id]) {
  520. world.copyToArray(this._worldMatricesInstancesArray, offset);
  521. offset += 16;
  522. instancesCount++;
  523. }
  524. if (visibleInstances) {
  525. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  526. var instance = visibleInstances[instanceIndex];
  527. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  528. offset += 16;
  529. instancesCount++;
  530. }
  531. }
  532. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  533. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  534. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  535. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  536. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  537. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  538. this._draw(subMesh, fillMode, instancesCount);
  539. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  540. }
  541. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  542. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  543. var scene = this.getScene();
  544. var engine = scene.getEngine();
  545. if (hardwareInstancedRendering) {
  546. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  547. } else {
  548. if (batch.renderSelf[subMesh._id]) {
  549. // Draw
  550. if (onBeforeDraw) {
  551. onBeforeDraw(false, this.getWorldMatrix());
  552. }
  553. this._draw(subMesh, fillMode);
  554. }
  555. if (batch.visibleInstances[subMesh._id]) {
  556. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  557. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  558. // World
  559. var world = instance.getWorldMatrix();
  560. if (onBeforeDraw) {
  561. onBeforeDraw(true, world);
  562. }
  563. // Draw
  564. this._draw(subMesh, fillMode);
  565. }
  566. }
  567. }
  568. }
  569. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  570. var scene = this.getScene();
  571. // Managing instances
  572. var batch = this._getInstancesRenderList(subMesh._id);
  573. if (batch.mustReturn) {
  574. return;
  575. }
  576. // Checking geometry state
  577. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  578. return;
  579. }
  580. var callbackIndex: number;
  581. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  582. this._onBeforeRenderCallbacks[callbackIndex](this);
  583. }
  584. var engine = scene.getEngine();
  585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  586. // Material
  587. var effectiveMaterial = subMesh.getMaterial();
  588. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  589. return;
  590. }
  591. // Outline - step 1
  592. var savedDepthWrite = engine.getDepthWrite();
  593. if (this.renderOutline) {
  594. engine.setDepthWrite(false);
  595. scene.getOutlineRenderer().render(subMesh, batch);
  596. engine.setDepthWrite(savedDepthWrite);
  597. }
  598. effectiveMaterial._preBind();
  599. var effect = effectiveMaterial.getEffect();
  600. // Bind
  601. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  602. this._bind(subMesh, effect, fillMode);
  603. var world = this.getWorldMatrix();
  604. effectiveMaterial.bind(world, this);
  605. // Alpha mode
  606. if (enableAlphaMode) {
  607. engine.setAlphaMode(effectiveMaterial.alphaMode);
  608. }
  609. // Draw
  610. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  611. (isInstance, world) => {
  612. if (isInstance) {
  613. effectiveMaterial.bindOnlyWorldMatrix(world);
  614. }
  615. });
  616. // Unbind
  617. effectiveMaterial.unbind();
  618. // Outline - step 2
  619. if (this.renderOutline && savedDepthWrite) {
  620. engine.setDepthWrite(true);
  621. engine.setColorWrite(false);
  622. scene.getOutlineRenderer().render(subMesh, batch);
  623. engine.setColorWrite(true);
  624. }
  625. // Overlay
  626. if (this.renderOverlay) {
  627. var currentMode = engine.getAlphaMode();
  628. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  629. scene.getOutlineRenderer().render(subMesh, batch, true);
  630. engine.setAlphaMode(currentMode);
  631. }
  632. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  633. this._onAfterRenderCallbacks[callbackIndex](this);
  634. }
  635. }
  636. public getEmittedParticleSystems(): ParticleSystem[] {
  637. var results = new Array<ParticleSystem>();
  638. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  639. var particleSystem = this.getScene().particleSystems[index];
  640. if (particleSystem.emitter === this) {
  641. results.push(particleSystem);
  642. }
  643. }
  644. return results;
  645. }
  646. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  647. var results = new Array<ParticleSystem>();
  648. var descendants = this.getDescendants();
  649. descendants.push(this);
  650. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  651. var particleSystem = this.getScene().particleSystems[index];
  652. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  653. results.push(particleSystem);
  654. }
  655. }
  656. return results;
  657. }
  658. public getChildren(): Node[] {
  659. var results = [];
  660. for (var index = 0; index < this.getScene().meshes.length; index++) {
  661. var mesh = this.getScene().meshes[index];
  662. if (mesh.parent === this) {
  663. results.push(mesh);
  664. }
  665. }
  666. return results;
  667. }
  668. public _checkDelayState(): void {
  669. var that = this;
  670. var scene = this.getScene();
  671. if (this._geometry) {
  672. this._geometry.load(scene);
  673. }
  674. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  675. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  676. scene._addPendingData(that);
  677. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  678. Tools.LoadFile(this.delayLoadingFile, data => {
  679. if (data instanceof ArrayBuffer) {
  680. this._delayLoadingFunction(data, this);
  681. }
  682. else {
  683. this._delayLoadingFunction(JSON.parse(data), this);
  684. }
  685. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  686. scene._removePendingData(this);
  687. }, () => { }, scene.database, getBinaryData);
  688. }
  689. }
  690. public isInFrustum(frustumPlanes: Plane[]): boolean {
  691. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  692. return false;
  693. }
  694. if (!super.isInFrustum(frustumPlanes)) {
  695. return false;
  696. }
  697. this._checkDelayState();
  698. return true;
  699. }
  700. public setMaterialByID(id: string): void {
  701. var materials = this.getScene().materials;
  702. var index: number;
  703. for (index = 0; index < materials.length; index++) {
  704. if (materials[index].id === id) {
  705. this.material = materials[index];
  706. return;
  707. }
  708. }
  709. // Multi
  710. var multiMaterials = this.getScene().multiMaterials;
  711. for (index = 0; index < multiMaterials.length; index++) {
  712. if (multiMaterials[index].id === id) {
  713. this.material = multiMaterials[index];
  714. return;
  715. }
  716. }
  717. }
  718. public getAnimatables(): IAnimatable[] {
  719. var results = [];
  720. if (this.material) {
  721. results.push(this.material);
  722. }
  723. if (this.skeleton) {
  724. results.push(this.skeleton);
  725. }
  726. return results;
  727. }
  728. // Geometry
  729. public bakeTransformIntoVertices(transform: Matrix): void {
  730. // Position
  731. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  732. return;
  733. }
  734. this._resetPointsArrayCache();
  735. var data = this.getVerticesData(VertexBuffer.PositionKind);
  736. var temp = [];
  737. var index: number;
  738. for (index = 0; index < data.length; index += 3) {
  739. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  740. }
  741. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  742. // Normals
  743. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  744. return;
  745. }
  746. data = this.getVerticesData(VertexBuffer.NormalKind);
  747. temp = [];
  748. for (index = 0; index < data.length; index += 3) {
  749. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  750. }
  751. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  752. // flip faces?
  753. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  754. }
  755. // Will apply current transform to mesh and reset world matrix
  756. public bakeCurrentTransformIntoVertices(): void {
  757. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  758. this.scaling.copyFromFloats(1, 1, 1);
  759. this.position.copyFromFloats(0, 0, 0);
  760. this.rotation.copyFromFloats(0, 0, 0);
  761. //only if quaternion is already set
  762. if (this.rotationQuaternion) {
  763. this.rotationQuaternion = Quaternion.Identity();
  764. }
  765. this._worldMatrix = Matrix.Identity();
  766. }
  767. // Cache
  768. public _resetPointsArrayCache(): void {
  769. this._positions = null;
  770. }
  771. public _generatePointsArray(): boolean {
  772. if (this._positions)
  773. return true;
  774. this._positions = [];
  775. var data = this.getVerticesData(VertexBuffer.PositionKind);
  776. if (!data) {
  777. return false;
  778. }
  779. for (var index = 0; index < data.length; index += 3) {
  780. this._positions.push(Vector3.FromArray(data, index));
  781. }
  782. return true;
  783. }
  784. // Clone
  785. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  786. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  787. }
  788. // Dispose
  789. public dispose(doNotRecurse?: boolean): void {
  790. if (this._geometry) {
  791. this._geometry.releaseForMesh(this, true);
  792. }
  793. // Instances
  794. if (this._worldMatricesInstancesBuffer) {
  795. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  796. this._worldMatricesInstancesBuffer = null;
  797. }
  798. while (this.instances.length) {
  799. this.instances[0].dispose();
  800. }
  801. super.dispose(doNotRecurse);
  802. }
  803. // Geometric tools
  804. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  805. var scene = this.getScene();
  806. var onload = img => {
  807. // Getting height map data
  808. var canvas = document.createElement("canvas");
  809. var context = canvas.getContext("2d");
  810. var heightMapWidth = img.width;
  811. var heightMapHeight = img.height;
  812. canvas.width = heightMapWidth;
  813. canvas.height = heightMapHeight;
  814. context.drawImage(img, 0, 0);
  815. // Create VertexData from map data
  816. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  817. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  818. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  819. //execute success callback, if set
  820. if (onSuccess) {
  821. onSuccess(this);
  822. }
  823. };
  824. Tools.LoadImage(url, onload, () => { }, scene.database);
  825. }
  826. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  827. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  828. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  829. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  830. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  831. return;
  832. }
  833. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  834. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  835. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  836. var position = Vector3.Zero();
  837. var normal = Vector3.Zero();
  838. var uv = Vector2.Zero();
  839. for (var index = 0; index < positions.length; index += 3) {
  840. Vector3.FromArrayToRef(positions, index, position);
  841. Vector3.FromArrayToRef(normals, index, normal);
  842. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  843. // Compute height
  844. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  845. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  846. var pos = (u + v * heightMapWidth) * 4;
  847. var r = buffer[pos] / 255.0;
  848. var g = buffer[pos + 1] / 255.0;
  849. var b = buffer[pos + 2] / 255.0;
  850. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  851. normal.normalize();
  852. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  853. position = position.add(normal);
  854. position.toArray(positions, index);
  855. }
  856. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  857. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  858. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  859. }
  860. public convertToFlatShadedMesh(): void {
  861. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  862. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  863. var kinds = this.getVerticesDataKinds();
  864. var vbs = [];
  865. var data = [];
  866. var newdata = [];
  867. var updatableNormals = false;
  868. var kindIndex: number;
  869. var kind: string;
  870. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  871. kind = kinds[kindIndex];
  872. var vertexBuffer = this.getVertexBuffer(kind);
  873. if (kind === VertexBuffer.NormalKind) {
  874. updatableNormals = vertexBuffer.isUpdatable();
  875. kinds.splice(kindIndex, 1);
  876. kindIndex--;
  877. continue;
  878. }
  879. vbs[kind] = vertexBuffer;
  880. data[kind] = vbs[kind].getData();
  881. newdata[kind] = [];
  882. }
  883. // Save previous submeshes
  884. var previousSubmeshes = this.subMeshes.slice(0);
  885. var indices = this.getIndices();
  886. var totalIndices = this.getTotalIndices();
  887. // Generating unique vertices per face
  888. var index: number;
  889. for (index = 0; index < totalIndices; index++) {
  890. var vertexIndex = indices[index];
  891. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  892. kind = kinds[kindIndex];
  893. var stride = vbs[kind].getStrideSize();
  894. for (var offset = 0; offset < stride; offset++) {
  895. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  896. }
  897. }
  898. }
  899. // Updating faces & normal
  900. var normals = [];
  901. var positions = newdata[VertexBuffer.PositionKind];
  902. for (index = 0; index < totalIndices; index += 3) {
  903. indices[index] = index;
  904. indices[index + 1] = index + 1;
  905. indices[index + 2] = index + 2;
  906. var p1 = Vector3.FromArray(positions, index * 3);
  907. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  908. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  909. var p1p2 = p1.subtract(p2);
  910. var p3p2 = p3.subtract(p2);
  911. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  912. // Store same normals for every vertex
  913. for (var localIndex = 0; localIndex < 3; localIndex++) {
  914. normals.push(normal.x);
  915. normals.push(normal.y);
  916. normals.push(normal.z);
  917. }
  918. }
  919. this.setIndices(indices);
  920. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  921. // Updating vertex buffers
  922. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  923. kind = kinds[kindIndex];
  924. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  925. }
  926. // Updating submeshes
  927. this.releaseSubMeshes();
  928. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  929. var previousOne = previousSubmeshes[submeshIndex];
  930. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  931. }
  932. this.synchronizeInstances();
  933. }
  934. // will inverse faces orientations, and invert normals too if specified
  935. public flipFaces(flipNormals: boolean = false): void {
  936. var vertex_data = VertexData.ExtractFromMesh(this);
  937. var i: number;
  938. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  939. for (i = 0; i < vertex_data.normals.length; i++) {
  940. vertex_data.normals[i] *= -1;
  941. }
  942. }
  943. var temp;
  944. for (i = 0; i < vertex_data.indices.length; i += 3) {
  945. // reassign indices
  946. temp = vertex_data.indices[i + 1];
  947. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  948. vertex_data.indices[i + 2] = temp;
  949. }
  950. vertex_data.applyToMesh(this);
  951. }
  952. // Instances
  953. public createInstance(name: string): InstancedMesh {
  954. return new InstancedMesh(name, this);
  955. }
  956. public synchronizeInstances(): void {
  957. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  958. var instance = this.instances[instanceIndex];
  959. instance._syncSubMeshes();
  960. }
  961. }
  962. /**
  963. * Simplify the mesh according to the given array of settings.
  964. * Function will return immediately and will simplify async.
  965. * @param settings a collection of simplification settings.
  966. * @param parallelProcessing should all levels calculate parallel or one after the other.
  967. * @param type the type of simplification to run.
  968. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  969. */
  970. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  971. this.getScene().simplificationQueue.addTask({
  972. settings: settings,
  973. parallelProcessing: parallelProcessing,
  974. mesh: this,
  975. simplificationType: simplificationType,
  976. successCallback: successCallback
  977. });
  978. }
  979. /**
  980. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  981. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  982. * This should be used together with the simplification to avoid disappearing triangles.
  983. * @param successCallback an optional success callback to be called after the optimization finished.
  984. */
  985. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  986. var indices = this.getIndices();
  987. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  988. var vectorPositions = [];
  989. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  990. vectorPositions.push(Vector3.FromArray(positions, pos));
  991. }
  992. var dupes = [];
  993. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  994. var realPos = vectorPositions.length - 1 - iteration;
  995. var testedPosition = vectorPositions[realPos];
  996. for (var j = 0; j < realPos; ++j) {
  997. var againstPosition = vectorPositions[j];
  998. if (testedPosition.equals(againstPosition)) {
  999. dupes[realPos] = j;
  1000. break;
  1001. }
  1002. }
  1003. }, () => {
  1004. for (var i = 0; i < indices.length; ++i) {
  1005. indices[i] = dupes[indices[i]] || indices[i];
  1006. }
  1007. //indices are now reordered
  1008. var originalSubMeshes = this.subMeshes.slice(0);
  1009. this.setIndices(indices);
  1010. this.subMeshes = originalSubMeshes;
  1011. if (successCallback) {
  1012. successCallback(this);
  1013. }
  1014. });
  1015. }
  1016. // Statics
  1017. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh;
  1018. public static CreateRibbon(name: string, options: { pathArray: Vector3[][], closeArray?: boolean, closePath?: boolean, offset?: number, updatable?: boolean, sideOrientation?: number, instance?: Mesh }, scene?: Scene): Mesh;
  1019. public static CreateRibbon(name: string, options: any, closeArrayOrScene?: any, closePath?: boolean, offset?: number, scene?: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, instance: Mesh = null): Mesh {
  1020. var pathArray;
  1021. var closeArray;
  1022. if (Array.isArray(options)) {
  1023. pathArray = options;
  1024. closeArray = closeArrayOrScene;
  1025. if (!instance) {
  1026. options = {
  1027. pathArray: pathArray,
  1028. closeArray: closeArray,
  1029. closePath: closePath,
  1030. offset: offset,
  1031. updatable: updatable,
  1032. sideOrientation: sideOrientation
  1033. }
  1034. }
  1035. } else {
  1036. scene = closeArrayOrScene;
  1037. pathArray = options.pathArray;
  1038. closeArray = options.closeArray;
  1039. closePath = options.closePath;
  1040. offset = options.offset;
  1041. sideOrientation = options.sideOrientation;
  1042. instance = options.instance;
  1043. updatable = options.updatable;
  1044. }
  1045. if (instance) { // existing ribbon instance update
  1046. // positionFunction : ribbon case
  1047. // only pathArray and sideOrientation parameters are taken into account for positions update
  1048. var positionFunction = positions => {
  1049. var minlg = pathArray[0].length;
  1050. var i = 0;
  1051. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  1052. for (var si = 1; si <= ns; si++) {
  1053. for (var p = 0; p < pathArray.length; p++) {
  1054. var path = pathArray[p];
  1055. var l = path.length;
  1056. minlg = (minlg < l) ? minlg : l;
  1057. var j = 0;
  1058. while (j < minlg) {
  1059. positions[i] = path[j].x;
  1060. positions[i + 1] = path[j].y;
  1061. positions[i + 2] = path[j].z;
  1062. j++;
  1063. i += 3;
  1064. }
  1065. if ((<any>instance)._closePath) {
  1066. positions[i] = path[0].x;
  1067. positions[i + 1] = path[0].y;
  1068. positions[i + 2] = path[0].z;
  1069. i += 3;
  1070. }
  1071. }
  1072. }
  1073. };
  1074. var positions = instance.getVerticesData(VertexBuffer.PositionKind);
  1075. positionFunction(positions);
  1076. instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  1077. if (!(instance.areNormalsFrozen)) {
  1078. var indices = instance.getIndices();
  1079. var normals = instance.getVerticesData(VertexBuffer.NormalKind);
  1080. VertexData.ComputeNormals(positions, indices, normals);
  1081. if ((<any>instance)._closePath) {
  1082. var indexFirst: number = 0;
  1083. var indexLast: number = 0;
  1084. for (var p = 0; p < pathArray.length; p++) {
  1085. indexFirst = (<any>instance)._idx[p] * 3;
  1086. if (p + 1 < pathArray.length) {
  1087. indexLast = ((<any>instance)._idx[p + 1] - 1) * 3;
  1088. }
  1089. else {
  1090. indexLast = normals.length - 3;
  1091. }
  1092. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  1093. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  1094. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  1095. normals[indexLast] = normals[indexFirst];
  1096. normals[indexLast + 1] = normals[indexFirst + 1];
  1097. normals[indexLast + 2] = normals[indexFirst + 2];
  1098. }
  1099. }
  1100. instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  1101. }
  1102. return instance;
  1103. }
  1104. else { // new ribbon creation
  1105. var ribbon = new Mesh(name, scene);
  1106. ribbon.sideOrientation = sideOrientation;
  1107. var vertexData = VertexData.CreateRibbon(options);
  1108. if (closePath) {
  1109. (<any>ribbon)._idx = (<any>vertexData)._idx;
  1110. }
  1111. (<any>ribbon)._closePath = closePath;
  1112. (<any>ribbon)._closeArray = closeArray;
  1113. vertexData.applyToMesh(ribbon, updatable);
  1114. return ribbon;
  1115. }
  1116. }
  1117. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1118. public static CreateDisc(name: string, options: { radius: number, tessellation: number, updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh;
  1119. public static CreateDisc(name: string, options: any, tessellationOrScene: any, scene?: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1120. if (tessellationOrScene instanceof Scene) {
  1121. scene = tessellationOrScene;
  1122. } else {
  1123. var radius = options;
  1124. options = {
  1125. radius: radius,
  1126. tessellation: tessellationOrScene,
  1127. sideOrientation: sideOrientation
  1128. }
  1129. }
  1130. var disc = new Mesh(name, scene);
  1131. var vertexData = VertexData.CreateDisc(options);
  1132. vertexData.applyToMesh(disc, updatable || options.updatable);
  1133. return disc;
  1134. }
  1135. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1136. public static CreateBox(name: string, options: { width?: number, height?: number, depth?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh;
  1137. public static CreateBox(name: string, options: any, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1138. // Check parameters
  1139. updatable = updatable || options.updatable;
  1140. if (typeof options === 'number') {
  1141. var size = options;
  1142. options = {
  1143. size: size,
  1144. sideOrientation: sideOrientation
  1145. };
  1146. }
  1147. var box = new Mesh(name, scene);
  1148. var vertexData = VertexData.CreateBox(options);
  1149. vertexData.applyToMesh(box, updatable);
  1150. return box;
  1151. }
  1152. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1153. public static CreateSphere(name: string, options: { segments?: number, diameter?: number, diameterX?: number, diameterY?: number, diameterZ?: number, sideOrientation?: number, updatable?: boolean }, scene: any): Mesh;
  1154. public static CreateSphere(name: string, options: any, diameterOrScene: any, scene?: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1155. if (diameterOrScene instanceof Scene) {
  1156. scene = diameterOrScene;
  1157. updatable = options.updatable;
  1158. } else {
  1159. var segments = options;
  1160. options = {
  1161. segments: segments,
  1162. diameterX: diameterOrScene,
  1163. diameterY: diameterOrScene,
  1164. diameterZ: diameterOrScene,
  1165. sideOrientation: sideOrientation
  1166. }
  1167. }
  1168. var sphere = new Mesh(name, scene);
  1169. var vertexData = VertexData.CreateSphere(options);
  1170. vertexData.applyToMesh(sphere, updatable);
  1171. return sphere;
  1172. }
  1173. // Cylinder and cone
  1174. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh;
  1175. public static CreateCylinder(name: string, options: { height?: number, diameterTop?: number, diameterBottom?: number, tessellation?: number, subdivisions?: number, updatable?: boolean, sideOrientation?: number }, scene: any): Mesh;
  1176. public static CreateCylinder(name: string, options: any, diameterTopOrScene: any, diameterBottom?: number, tessellation?: number, subdivisions?: any, scene?: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1177. if (diameterTopOrScene instanceof Scene) {
  1178. scene = diameterTopOrScene;
  1179. updatable = options.updatable;
  1180. } else {
  1181. if (scene === undefined || !(scene instanceof Scene)) {
  1182. if (scene !== undefined) {
  1183. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  1184. updatable = scene;
  1185. }
  1186. scene = <Scene>subdivisions;
  1187. subdivisions = 1;
  1188. }
  1189. var height = options;
  1190. options = {
  1191. height: height,
  1192. diameterTop: diameterTopOrScene,
  1193. diameterBottom: diameterBottom,
  1194. tessellation: tessellation,
  1195. subdivisions: subdivisions,
  1196. sideOrientation: sideOrientation
  1197. }
  1198. }
  1199. var cylinder = new Mesh(name, scene);
  1200. var vertexData = VertexData.CreateCylinder(options);
  1201. vertexData.applyToMesh(cylinder, updatable);
  1202. return cylinder;
  1203. }
  1204. // Torus (Code from SharpDX.org)
  1205. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1206. public static CreateTorus(name: string, options: { diameter?: number, thickness?: number, tessellation?: number, updatable?: boolean, sideOrientation?: number }, scene: any): Mesh;
  1207. public static CreateTorus(name: string, options: any, thicknessOrScene: any, tessellation?: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1208. if (thicknessOrScene instanceof Scene) {
  1209. scene = thicknessOrScene;
  1210. updatable = options.updatable;
  1211. } else {
  1212. var diameter = options;
  1213. options = {
  1214. diameter: diameter,
  1215. thickness: thicknessOrScene,
  1216. tessellation: tessellation,
  1217. sideOrientation: sideOrientation
  1218. }
  1219. }
  1220. var torus = new Mesh(name, scene);
  1221. var vertexData = VertexData.CreateTorus(options);
  1222. vertexData.applyToMesh(torus, updatable);
  1223. return torus;
  1224. }
  1225. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1226. public static CreateTorusKnot(name: string, options: { radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, updatable?: boolean, sideOrientation?: number }, scene: any): Mesh;
  1227. public static CreateTorusKnot(name: string, options: any, tubeOrScene: any, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1228. if (tubeOrScene instanceof Scene) {
  1229. scene = tubeOrScene;
  1230. updatable = options.updatable;
  1231. } else {
  1232. var radius = options;
  1233. options = {
  1234. radius: radius,
  1235. tube: tubeOrScene,
  1236. radialSegments: radialSegments,
  1237. tubularSegments: tubularSegments,
  1238. p: p,
  1239. q: q,
  1240. sideOrientation: sideOrientation
  1241. }
  1242. }
  1243. var torusKnot = new Mesh(name, scene);
  1244. var vertexData = VertexData.CreateTorusKnot(options);
  1245. vertexData.applyToMesh(torusKnot, updatable);
  1246. return torusKnot;
  1247. }
  1248. // Lines
  1249. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh;
  1250. public static CreateLines(name: string, options: { points: Vector3[], updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh;
  1251. public static CreateLines(name: string, options: any, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1252. var points: Vector3[];
  1253. if (Array.isArray(options)) {
  1254. points = options;
  1255. if (!instance) {
  1256. options = {
  1257. points: points
  1258. }
  1259. }
  1260. } else {
  1261. instance = options.instance;
  1262. points = options.points;
  1263. }
  1264. if (instance) { // lines update
  1265. var positionFunction = positions => {
  1266. var i = 0;
  1267. for (var p = 0; p < points.length; p++) {
  1268. positions[i] = points[p].x;
  1269. positions[i + 1] = points[p].y;
  1270. positions[i + 2] = points[p].z;
  1271. i += 3;
  1272. }
  1273. };
  1274. instance.updateMeshPositions(positionFunction, false);
  1275. return instance;
  1276. }
  1277. // lines creation
  1278. var lines = new LinesMesh(name, scene);
  1279. var vertexData = VertexData.CreateLines(options);
  1280. vertexData.applyToMesh(lines, updatable || options.updatable);
  1281. return lines;
  1282. }
  1283. // Dashed Lines
  1284. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh;
  1285. public static CreateDashedLines(name: string, options: { points: Vector3[], dashSize?: number, gapSize?: number, dashNb?: number, updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh;
  1286. public static CreateDashedLines(name: string, options: any, dashSizeOrScene: any, gapSize?: number, dashNb?: number, scene?: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1287. var points: Vector3[];
  1288. var dashSize: number;
  1289. if (Array.isArray(options)) {
  1290. points = options;
  1291. dashSize = dashSizeOrScene;
  1292. if (!instance) {
  1293. options = {
  1294. points: points,
  1295. dashSize: dashSize,
  1296. gapSize: gapSize,
  1297. dashNb: dashNb
  1298. }
  1299. }
  1300. } else {
  1301. scene = dashSizeOrScene,
  1302. points = options.points;
  1303. instance = options.instance;
  1304. gapSize = options.gapSize;
  1305. dashNb = options.dashNb;
  1306. dashSize = options.dashSize;
  1307. }
  1308. if (instance) { // dashed lines update
  1309. var positionFunction = (positions: number[]): void => {
  1310. var curvect = Vector3.Zero();
  1311. var nbSeg = positions.length / 6;
  1312. var lg = 0;
  1313. var nb = 0;
  1314. var shft = 0;
  1315. var dashshft = 0;
  1316. var curshft = 0;
  1317. var p = 0;
  1318. var i = 0;
  1319. var j = 0;
  1320. for (i = 0; i < points.length - 1; i++) {
  1321. points[i + 1].subtractToRef(points[i], curvect);
  1322. lg += curvect.length();
  1323. }
  1324. shft = lg / nbSeg;
  1325. dashshft = (<any>instance).dashSize * shft / ((<any>instance).dashSize + (<any>instance).gapSize);
  1326. for (i = 0; i < points.length - 1; i++) {
  1327. points[i + 1].subtractToRef(points[i], curvect);
  1328. nb = Math.floor(curvect.length() / shft);
  1329. curvect.normalize();
  1330. j = 0;
  1331. while (j < nb && p < positions.length) {
  1332. curshft = shft * j;
  1333. positions[p] = points[i].x + curshft * curvect.x;
  1334. positions[p + 1] = points[i].y + curshft * curvect.y;
  1335. positions[p + 2] = points[i].z + curshft * curvect.z;
  1336. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  1337. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  1338. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  1339. p += 6;
  1340. j++;
  1341. }
  1342. }
  1343. while (p < positions.length) {
  1344. positions[p] = points[i].x;
  1345. positions[p + 1] = points[i].y;
  1346. positions[p + 2] = points[i].z;
  1347. p += 3;
  1348. }
  1349. };
  1350. instance.updateMeshPositions(positionFunction, false);
  1351. return instance;
  1352. }
  1353. // dashed lines creation
  1354. var dashedLines = new LinesMesh(name, scene);
  1355. var vertexData = VertexData.CreateDashedLines(options);
  1356. vertexData.applyToMesh(dashedLines, updatable || options.updatable);
  1357. (<any>dashedLines).dashSize = dashSize;
  1358. (<any>dashedLines).gapSize = gapSize;
  1359. return dashedLines;
  1360. }
  1361. // Extrusion
  1362. 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 {
  1363. scale = scale || 1;
  1364. rotation = rotation || 0;
  1365. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1366. return extruded;
  1367. }
  1368. 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 {
  1369. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1370. return extrudedCustom;
  1371. }
  1372. 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 {
  1373. // extrusion geometry
  1374. var extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) => {
  1375. var tangents = path3D.getTangents();
  1376. var normals = path3D.getNormals();
  1377. var binormals = path3D.getBinormals();
  1378. var distances = path3D.getDistances();
  1379. var angle = 0;
  1380. var returnScale: { (i: number, distance: number): number; } = (i, distance) => { return scale; };
  1381. var returnRotation: { (i: number, distance: number): number; } = (i, distance) => { return rotation; };
  1382. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1383. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1384. var index = 0;
  1385. for (var i = 0; i < curve.length; i++) {
  1386. var shapePath = new Array<Vector3>();
  1387. var angleStep = rotate(i, distances[i]);
  1388. var scaleRatio = scl(i, distances[i]);
  1389. for (var p = 0; p < shape.length; p++) {
  1390. var rotationMatrix = Matrix.RotationAxis(tangents[i], angle);
  1391. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1392. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1393. shapePath.push(rotated);
  1394. }
  1395. shapePaths[index] = shapePath;
  1396. angle += angleStep;
  1397. index++;
  1398. }
  1399. // cap
  1400. var capPath = shapePath => {
  1401. var pointCap = Array<Vector3>();
  1402. var barycenter = Vector3.Zero();
  1403. var i: number;
  1404. for (i = 0; i < shapePath.length; i++) {
  1405. barycenter.addInPlace(shapePath[i]);
  1406. }
  1407. barycenter.scaleInPlace(1 / shapePath.length);
  1408. for (i = 0; i < shapePath.length; i++) {
  1409. pointCap.push(barycenter);
  1410. }
  1411. return pointCap;
  1412. };
  1413. switch (cap) {
  1414. case Mesh.NO_CAP:
  1415. break;
  1416. case Mesh.CAP_START:
  1417. shapePaths.unshift(capPath(shapePaths[0]));
  1418. break;
  1419. case Mesh.CAP_END:
  1420. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1421. break;
  1422. case Mesh.CAP_ALL:
  1423. shapePaths.unshift(capPath(shapePaths[0]));
  1424. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1425. break;
  1426. default:
  1427. break;
  1428. }
  1429. return shapePaths;
  1430. };
  1431. var path3D;
  1432. var pathArray;
  1433. if (instance) { // instance update
  1434. path3D = ((<any>instance).path3D).update(curve);
  1435. pathArray = extrusionPathArray(shape, curve, (<any>instance).path3D, (<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, (<any>instance).cap, custom);
  1436. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1437. return instance;
  1438. }
  1439. // extruded shape creation
  1440. path3D = <any>new Path3D(curve);
  1441. var newShapePaths = new Array<Array<Vector3>>();
  1442. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1443. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1444. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1445. (<any>extrudedGeneric).pathArray = pathArray;
  1446. (<any>extrudedGeneric).path3D = path3D;
  1447. (<any>extrudedGeneric).cap = cap;
  1448. return extrudedGeneric;
  1449. }
  1450. // Lathe
  1451. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1452. radius = radius || 1;
  1453. tessellation = tessellation || radius * 60;
  1454. var pi2 = Math.PI * 2;
  1455. var shapeLathe = new Array<Vector3>();
  1456. // first rotatable point
  1457. var i = 0;
  1458. while (shape[i].x === 0) {
  1459. i++;
  1460. }
  1461. var pt = shape[i];
  1462. for (i = 0; i < shape.length; i++) {
  1463. shapeLathe.push(shape[i].subtract(pt));
  1464. }
  1465. // circle path
  1466. var step = pi2 / tessellation;
  1467. var rotated;
  1468. var path = new Array<Vector3>();;
  1469. for (i = 0; i < tessellation; i++) {
  1470. rotated = new Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  1471. path.push(rotated);
  1472. }
  1473. path.push(path[0]);
  1474. // extrusion
  1475. var scaleFunction = () => { return 1; };
  1476. var rotateFunction = () => { return 0; };
  1477. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  1478. return lathe;
  1479. }
  1480. // Plane & ground
  1481. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1482. public static CreatePlane(name: string, options: { size?: number, width?: number, height?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh;
  1483. public static CreatePlane(name: string, options: any, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1484. if (typeof options === 'number') {
  1485. var size = options;
  1486. options = {
  1487. size: size,
  1488. width: size,
  1489. height: size,
  1490. sideOrientation: sideOrientation
  1491. }
  1492. }
  1493. var plane = new Mesh(name, scene);
  1494. var vertexData = VertexData.CreatePlane(options);
  1495. vertexData.applyToMesh(plane, updatable || options.updatable);
  1496. return plane;
  1497. }
  1498. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh;
  1499. public static CreateGround(name: string, options: { width?: number, height?: number, subdivisions?: number, updatable?: boolean }, scene: any): Mesh;
  1500. public static CreateGround(name: string, options: any, heightOrScene: any, subdivisions?: number, scene?: Scene, updatable?: boolean): Mesh {
  1501. if (heightOrScene instanceof Scene) {
  1502. scene = heightOrScene;
  1503. updatable = options.updatable;
  1504. } else {
  1505. var width = options;
  1506. options = {
  1507. width: width,
  1508. height: heightOrScene,
  1509. subdivisions: subdivisions
  1510. }
  1511. }
  1512. var ground = new GroundMesh(name, scene);
  1513. ground._setReady(false);
  1514. ground._subdivisions = options.subdivisions || 1;
  1515. var vertexData = VertexData.CreateGround(options);
  1516. vertexData.applyToMesh(ground, updatable || options.updatable);
  1517. ground._setReady(true);
  1518. return ground;
  1519. }
  1520. 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 {
  1521. var tiledGround = new Mesh(name, scene);
  1522. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1523. vertexData.applyToMesh(tiledGround, updatable);
  1524. return tiledGround;
  1525. }
  1526. 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 {
  1527. var ground = new GroundMesh(name, scene);
  1528. ground._subdivisions = subdivisions;
  1529. ground._setReady(false);
  1530. var onload = img => {
  1531. // Getting height map data
  1532. var canvas = document.createElement("canvas");
  1533. var context = canvas.getContext("2d");
  1534. var heightMapWidth = img.width;
  1535. var heightMapHeight = img.height;
  1536. canvas.width = heightMapWidth;
  1537. canvas.height = heightMapHeight;
  1538. context.drawImage(img, 0, 0);
  1539. // Create VertexData from map data
  1540. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1541. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1542. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1543. vertexData.applyToMesh(ground, updatable);
  1544. ground._setReady(true);
  1545. //execute ready callback, if set
  1546. if (onReady) {
  1547. onReady(ground);
  1548. }
  1549. };
  1550. Tools.LoadImage(url, onload, () => { }, scene.database);
  1551. return ground;
  1552. }
  1553. 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, instance?: Mesh): Mesh;
  1554. public static CreateTube(name: string, options: { path: Vector3[], radius?: number, tessellation?: number, radiusFunction?: { (i: number, distance: number): number; }, cap?: number, updatable?: boolean, sideOrientation?: number, instance?: Mesh }, scene: Scene): Mesh;
  1555. public static CreateTube(name: string, options: any, radiusOrScene: any, tessellation?: number, radiusFunction?: { (i: number, distance: number): number; }, cap?: number, scene?: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, instance: Mesh = null): Mesh {
  1556. var path: Vector3[];
  1557. var radius: number;
  1558. if (Array.isArray(options)) {
  1559. path = options;
  1560. radius = radiusOrScene;
  1561. } else {
  1562. scene = radiusOrScene;
  1563. path = options.path;
  1564. radius = options.radius || 1;
  1565. tessellation = options.tessellation || 64;
  1566. radiusFunction = options.radiusFunction;
  1567. cap = options.cap || Mesh.NO_CAP,
  1568. updatable = options.updatable;
  1569. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  1570. instance = options.instance
  1571. }
  1572. // tube geometry
  1573. var tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) => {
  1574. var tangents = path3D.getTangents();
  1575. var normals = path3D.getNormals();
  1576. var distances = path3D.getDistances();
  1577. var pi2 = Math.PI * 2;
  1578. var step = pi2 / tessellation;
  1579. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1580. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1581. var circlePath: Vector3[];
  1582. var rad: number;
  1583. var normal: Vector3;
  1584. var rotated: Vector3;
  1585. var rotationMatrix: Matrix;
  1586. var index = 0;
  1587. for (var i = 0; i < path.length; i++) {
  1588. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1589. circlePath = Array<Vector3>(); // current circle array
  1590. normal = normals[i]; // current normal
  1591. for (var t = 0; t < tessellation; t++) {
  1592. rotationMatrix = Matrix.RotationAxis(tangents[i], step * t);
  1593. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1594. circlePath.push(rotated);
  1595. }
  1596. circlePaths[index] = circlePath;
  1597. index++;
  1598. }
  1599. // cap
  1600. var capPath = (nbPoints, pathIndex) => {
  1601. var pointCap = Array<Vector3>();
  1602. for (var i = 0; i < nbPoints; i++) {
  1603. pointCap.push(path[pathIndex]);
  1604. }
  1605. return pointCap;
  1606. };
  1607. switch (cap) {
  1608. case Mesh.NO_CAP:
  1609. break;
  1610. case Mesh.CAP_START:
  1611. circlePaths.unshift(capPath(tessellation + 1, 0));
  1612. break;
  1613. case Mesh.CAP_END:
  1614. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1615. break;
  1616. case Mesh.CAP_ALL:
  1617. circlePaths.unshift(capPath(tessellation + 1, 0));
  1618. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1619. break;
  1620. default:
  1621. break;
  1622. }
  1623. return circlePaths;
  1624. };
  1625. var path3D;
  1626. var pathArray;
  1627. if (instance) { // tube update
  1628. path3D = ((<any>instance).path3D).update(path);
  1629. pathArray = tubePathArray(path, path3D, (<any>instance).pathArray, radius, (<any>instance).tessellation, radiusFunction, (<any>instance).cap);
  1630. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  1631. (<any>instance).path3D = path3D;
  1632. (<any>instance).pathArray = pathArray;
  1633. return instance;
  1634. }
  1635. // tube creation
  1636. path3D = <any>new Path3D(path);
  1637. var newPathArray = new Array<Array<Vector3>>();
  1638. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1639. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1640. var tube = Mesh.CreateRibbon(name, {pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation}, scene);
  1641. (<any>tube).pathArray = pathArray;
  1642. (<any>tube).path3D = path3D;
  1643. (<any>tube).tessellation = tessellation;
  1644. (<any>tube).cap = cap;
  1645. return tube;
  1646. }
  1647. // Decals
  1648. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number = 0) {
  1649. var indices = sourceMesh.getIndices();
  1650. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  1651. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  1652. // Getting correct rotation
  1653. if (!normal) {
  1654. var target = new Vector3(0, 0, 1);
  1655. var camera = sourceMesh.getScene().activeCamera;
  1656. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1657. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1658. }
  1659. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1660. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1661. var pitch = Math.atan2(normal.y, len);
  1662. // Matrix
  1663. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1664. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1665. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1666. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1667. var vertexData = new VertexData();
  1668. vertexData.indices = [];
  1669. vertexData.positions = [];
  1670. vertexData.normals = [];
  1671. vertexData.uvs = [];
  1672. var currentVertexDataIndex = 0;
  1673. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1674. var vertexId = indices[indexId];
  1675. var result = new PositionNormalVertex();
  1676. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1677. // Send vector to decal local world
  1678. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1679. // Get normal
  1680. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1681. return result;
  1682. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1683. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  1684. if (vertices.length === 0) {
  1685. return vertices;
  1686. }
  1687. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1688. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1689. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1690. return new PositionNormalVertex(
  1691. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1692. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1693. );
  1694. };
  1695. var result = new Array<PositionNormalVertex>();
  1696. for (var index = 0; index < vertices.length; index += 3) {
  1697. var v1Out: boolean;
  1698. var v2Out: boolean;
  1699. var v3Out: boolean;
  1700. var total = 0;
  1701. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  1702. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1703. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1704. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1705. v1Out = d1 > 0;
  1706. v2Out = d2 > 0;
  1707. v3Out = d3 > 0;
  1708. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1709. switch (total) {
  1710. case 0:
  1711. result.push(vertices[index]);
  1712. result.push(vertices[index + 1]);
  1713. result.push(vertices[index + 2]);
  1714. break;
  1715. case 1:
  1716. if (v1Out) {
  1717. nV1 = vertices[index + 1];
  1718. nV2 = vertices[index + 2];
  1719. nV3 = clipVertices(vertices[index], nV1);
  1720. nV4 = clipVertices(vertices[index], nV2);
  1721. }
  1722. if (v2Out) {
  1723. nV1 = vertices[index];
  1724. nV2 = vertices[index + 2];
  1725. nV3 = clipVertices(vertices[index + 1], nV1);
  1726. nV4 = clipVertices(vertices[index + 1], nV2);
  1727. result.push(nV3);
  1728. result.push(nV2.clone());
  1729. result.push(nV1.clone());
  1730. result.push(nV2.clone());
  1731. result.push(nV3.clone());
  1732. result.push(nV4);
  1733. break;
  1734. }
  1735. if (v3Out) {
  1736. nV1 = vertices[index];
  1737. nV2 = vertices[index + 1];
  1738. nV3 = clipVertices(vertices[index + 2], nV1);
  1739. nV4 = clipVertices(vertices[index + 2], nV2);
  1740. }
  1741. result.push(nV1.clone());
  1742. result.push(nV2.clone());
  1743. result.push(nV3);
  1744. result.push(nV4);
  1745. result.push(nV3.clone());
  1746. result.push(nV2.clone());
  1747. break;
  1748. case 2:
  1749. if (!v1Out) {
  1750. nV1 = vertices[index].clone();
  1751. nV2 = clipVertices(nV1, vertices[index + 1]);
  1752. nV3 = clipVertices(nV1, vertices[index + 2]);
  1753. result.push(nV1);
  1754. result.push(nV2);
  1755. result.push(nV3);
  1756. }
  1757. if (!v2Out) {
  1758. nV1 = vertices[index + 1].clone();
  1759. nV2 = clipVertices(nV1, vertices[index + 2]);
  1760. nV3 = clipVertices(nV1, vertices[index]);
  1761. result.push(nV1);
  1762. result.push(nV2);
  1763. result.push(nV3);
  1764. }
  1765. if (!v3Out) {
  1766. nV1 = vertices[index + 2].clone();
  1767. nV2 = clipVertices(nV1, vertices[index]);
  1768. nV3 = clipVertices(nV1, vertices[index + 1]);
  1769. result.push(nV1);
  1770. result.push(nV2);
  1771. result.push(nV3);
  1772. }
  1773. break;
  1774. case 3:
  1775. break;
  1776. }
  1777. }
  1778. return result;
  1779. };
  1780. for (var index = 0; index < indices.length; index += 3) {
  1781. var faceVertices = new Array<PositionNormalVertex>();
  1782. faceVertices.push(extractDecalVector3(index));
  1783. faceVertices.push(extractDecalVector3(index + 1));
  1784. faceVertices.push(extractDecalVector3(index + 2));
  1785. // Clip
  1786. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1787. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1788. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1789. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1790. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1791. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1792. if (faceVertices.length === 0) {
  1793. continue;
  1794. }
  1795. // Add UVs and get back to world
  1796. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1797. var vertex = faceVertices[vIndex];
  1798. vertexData.indices.push(currentVertexDataIndex);
  1799. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1800. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1801. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1802. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1803. currentVertexDataIndex++;
  1804. }
  1805. }
  1806. // Return mesh
  1807. var decal = new Mesh(name, sourceMesh.getScene());
  1808. vertexData.applyToMesh(decal);
  1809. decal.position = position.clone();
  1810. decal.rotation = new Vector3(pitch, yaw, angle);
  1811. return decal;
  1812. }
  1813. // Skeletons
  1814. /**
  1815. * Update the vertex buffers by applying transformation from the bones
  1816. * @param {skeleton} skeleton to apply
  1817. */
  1818. public applySkeleton(skeleton: Skeleton): Mesh {
  1819. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1820. return this;
  1821. }
  1822. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1823. return this;
  1824. }
  1825. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  1826. return this;
  1827. }
  1828. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  1829. return this;
  1830. }
  1831. var source: number[];
  1832. if (!this._sourcePositions) {
  1833. source = this.getVerticesData(VertexBuffer.PositionKind);
  1834. this._sourcePositions = new Float32Array(source);
  1835. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  1836. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  1837. }
  1838. }
  1839. if (!this._sourceNormals) {
  1840. source = this.getVerticesData(VertexBuffer.NormalKind);
  1841. this._sourceNormals = new Float32Array(source);
  1842. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  1843. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  1844. }
  1845. }
  1846. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  1847. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  1848. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  1849. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  1850. var skeletonMatrices = skeleton.getTransformMatrices();
  1851. var tempVector3 = Vector3.Zero();
  1852. var finalMatrix = new Matrix();
  1853. var tempMatrix = new Matrix();
  1854. for (var index = 0; index < positionsData.length; index += 3) {
  1855. var index4 = (index / 3) * 4;
  1856. var matricesWeight0 = matricesWeightsData[index4];
  1857. var matricesWeight1 = matricesWeightsData[index4 + 1];
  1858. var matricesWeight2 = matricesWeightsData[index4 + 2];
  1859. var matricesWeight3 = matricesWeightsData[index4 + 3];
  1860. if (matricesWeight0 > 0) {
  1861. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  1862. finalMatrix.addToSelf(tempMatrix);
  1863. }
  1864. if (matricesWeight1 > 0) {
  1865. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  1866. finalMatrix.addToSelf(tempMatrix);
  1867. }
  1868. if (matricesWeight2 > 0) {
  1869. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  1870. finalMatrix.addToSelf(tempMatrix);
  1871. }
  1872. if (matricesWeight3 > 0) {
  1873. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  1874. finalMatrix.addToSelf(tempMatrix);
  1875. }
  1876. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  1877. tempVector3.toArray(positionsData, index);
  1878. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  1879. tempVector3.toArray(normalsData, index);
  1880. finalMatrix.reset();
  1881. }
  1882. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  1883. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  1884. return this;
  1885. }
  1886. // Tools
  1887. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1888. var minVector: Vector3 = null;
  1889. var maxVector: Vector3 = null;
  1890. for (var i in meshes) {
  1891. var mesh = meshes[i];
  1892. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1893. if (!minVector) {
  1894. minVector = boundingBox.minimumWorld;
  1895. maxVector = boundingBox.maximumWorld;
  1896. continue;
  1897. }
  1898. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1899. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1900. }
  1901. return {
  1902. min: minVector,
  1903. max: maxVector
  1904. };
  1905. }
  1906. public static Center(meshesOrMinMaxVector): Vector3 {
  1907. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1908. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1909. }
  1910. /**
  1911. * Merge the array of meshes into a single mesh for performance reasons.
  1912. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1913. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1914. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1915. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1916. */
  1917. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1918. var index: number;
  1919. if (!allow32BitsIndices) {
  1920. var totalVertices = 0;
  1921. // Counting vertices
  1922. for (index = 0; index < meshes.length; index++) {
  1923. if (meshes[index]) {
  1924. totalVertices += meshes[index].getTotalVertices();
  1925. if (totalVertices > 65536) {
  1926. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1927. return null;
  1928. }
  1929. }
  1930. }
  1931. }
  1932. // Merge
  1933. var vertexData: VertexData;
  1934. var otherVertexData: VertexData;
  1935. var source: Mesh;
  1936. for (index = 0; index < meshes.length; index++) {
  1937. if (meshes[index]) {
  1938. meshes[index].computeWorldMatrix(true);
  1939. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1940. otherVertexData.transform(meshes[index].getWorldMatrix());
  1941. if (vertexData) {
  1942. vertexData.merge(otherVertexData);
  1943. } else {
  1944. vertexData = otherVertexData;
  1945. source = meshes[index];
  1946. }
  1947. }
  1948. }
  1949. if (!meshSubclass) {
  1950. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1951. }
  1952. vertexData.applyToMesh(meshSubclass);
  1953. // Setting properties
  1954. meshSubclass.material = source.material;
  1955. meshSubclass.checkCollisions = source.checkCollisions;
  1956. // Cleaning
  1957. if (disposeSource) {
  1958. for (index = 0; index < meshes.length; index++) {
  1959. if (meshes[index]) {
  1960. meshes[index].dispose();
  1961. }
  1962. }
  1963. }
  1964. return meshSubclass;
  1965. }
  1966. }
  1967. }