babylon.mesh.ts 77 KB

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