babylon.mesh.ts 79 KB

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