babylon.mesh.ts 80 KB

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