babylon.mesh.ts 68 KB

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