babylon.mesh.ts 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  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. /**
  18. * Mesh side orientation : usually the external or front surface
  19. */
  20. public static get FRONTSIDE(): number {
  21. return Mesh._FRONTSIDE;
  22. }
  23. /**
  24. * Mesh side orientation : usually the internal or back surface
  25. */
  26. public static get BACKSIDE(): number {
  27. return Mesh._BACKSIDE;
  28. }
  29. /**
  30. * Mesh side orientation : both internal and external or front and back surfaces
  31. */
  32. public static get DOUBLESIDE(): number {
  33. return Mesh._DOUBLESIDE;
  34. }
  35. /**
  36. * Mesh side orientation : by default, `FRONTSIDE`
  37. */
  38. public static get DEFAULTSIDE(): number {
  39. return Mesh._DEFAULTSIDE;
  40. }
  41. /**
  42. * Mesh cap setting : no cap
  43. */
  44. public static get NO_CAP(): number {
  45. return Mesh._NO_CAP;
  46. }
  47. /**
  48. * Mesh cap setting : one cap at the beginning of the mesh
  49. */
  50. public static get CAP_START(): number {
  51. return Mesh._CAP_START;
  52. }
  53. /**
  54. * Mesh cap setting : one cap at the end of the mesh
  55. */
  56. public static get CAP_END(): number {
  57. return Mesh._CAP_END;
  58. }
  59. /**
  60. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  61. */
  62. public static get CAP_ALL(): number {
  63. return Mesh._CAP_ALL;
  64. }
  65. // Events
  66. /**
  67. * An event triggered before rendering the mesh
  68. * @type {BABYLON.Observable}
  69. */
  70. public onBeforeRenderObservable = new Observable<Mesh>();
  71. /**
  72. * An event triggered after rendering the mesh
  73. * @type {BABYLON.Observable}
  74. */
  75. public onAfterRenderObservable = new Observable<Mesh>();
  76. /**
  77. * An event triggered before drawing the mesh
  78. * @type {BABYLON.Observable}
  79. */
  80. public onBeforeDrawObservable = new Observable<Mesh>();
  81. private _onBeforeDrawObserver: Observer<Mesh>;
  82. public set onBeforeDraw(callback: () => void) {
  83. if (this._onBeforeDrawObserver) {
  84. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  85. }
  86. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  87. }
  88. // Members
  89. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  90. public instances = new Array<InstancedMesh>();
  91. public delayLoadingFile: string;
  92. public _binaryInfo: any;
  93. private _LODLevels = new Array<Internals.MeshLODLevel>();
  94. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  95. // Private
  96. public _geometry: Geometry;
  97. public _delayInfo; //ANY
  98. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  99. public _visibleInstances: any = {};
  100. private _renderIdForInstances = new Array<number>();
  101. private _batchCache = new _InstancesBatch();
  102. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  103. private _instancesBuffer: Buffer;
  104. private _instancesData: Float32Array;
  105. private _overridenInstanceCount: number;
  106. public _shouldGenerateFlatShading: boolean;
  107. private _preActivateId: number;
  108. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  109. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  110. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  111. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  112. /**
  113. * @constructor
  114. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  115. * @param {Scene} scene The scene to add this mesh to.
  116. * @param {Node} parent The parent of this mesh, if it has one
  117. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  118. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  119. * When false, achieved by calling a clone(), also passing False.
  120. * This will make creation of children, recursive.
  121. */
  122. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  123. super(name, scene);
  124. if (source) {
  125. // Geometry
  126. if (source._geometry) {
  127. source._geometry.applyToMesh(this);
  128. }
  129. // Deep copy
  130. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  131. // Parent
  132. this.parent = source.parent;
  133. // Pivot
  134. this.setPivotMatrix(source.getPivotMatrix());
  135. this.id = name + "." + source.id;
  136. // Material
  137. this.material = source.material;
  138. var index: number;
  139. if (!doNotCloneChildren) {
  140. // Children
  141. for (index = 0; index < scene.meshes.length; index++) {
  142. var mesh = scene.meshes[index];
  143. if (mesh.parent === source) {
  144. // doNotCloneChildren is always going to be False
  145. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  146. }
  147. }
  148. }
  149. // Physics clone
  150. var physicsEngine = this.getScene().getPhysicsEngine();
  151. if (clonePhysicsImpostor && physicsEngine) {
  152. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  153. if (impostor) {
  154. this.physicsImpostor = impostor.clone(this);
  155. }
  156. }
  157. // Particles
  158. for (index = 0; index < scene.particleSystems.length; index++) {
  159. var system = scene.particleSystems[index];
  160. if (system.emitter === source) {
  161. system.clone(system.name, this);
  162. }
  163. }
  164. this.computeWorldMatrix(true);
  165. }
  166. // Parent
  167. if (parent !== null) {
  168. this.parent = parent;
  169. }
  170. }
  171. // Methods
  172. public getClassName(): string {
  173. return "Mesh";
  174. }
  175. /**
  176. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  177. */
  178. public toString(fullDetails?: boolean): string {
  179. var ret = super.toString(fullDetails);
  180. ret += ", n vertices: " + this.getTotalVertices();
  181. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  182. if (this.animations) {
  183. for (var i = 0; i < this.animations.length; i++) {
  184. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  185. }
  186. }
  187. if (fullDetails) {
  188. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  189. }
  190. return ret;
  191. }
  192. public get hasLODLevels(): boolean {
  193. return this._LODLevels.length > 0;
  194. }
  195. private _sortLODLevels(): void {
  196. this._LODLevels.sort((a, b) => {
  197. if (a.distance < b.distance) {
  198. return 1;
  199. }
  200. if (a.distance > b.distance) {
  201. return -1;
  202. }
  203. return 0;
  204. });
  205. }
  206. /**
  207. * Add a mesh as LOD level triggered at the given distance.
  208. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  209. * @param {number} distance The distance from the center of the object to show this level
  210. * @param {Mesh} mesh The mesh to be added as LOD level
  211. * @return {Mesh} This mesh (for chaining)
  212. */
  213. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  214. if (mesh && mesh._masterMesh) {
  215. Tools.Warn("You cannot use a mesh as LOD level twice");
  216. return this;
  217. }
  218. var level = new Internals.MeshLODLevel(distance, mesh);
  219. this._LODLevels.push(level);
  220. if (mesh) {
  221. mesh._masterMesh = this;
  222. }
  223. this._sortLODLevels();
  224. return this;
  225. }
  226. /**
  227. * Returns the LOD level mesh at the passed distance or null if not found.
  228. * It is related to the method `addLODLevel(distance, mesh)`.
  229. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  230. */
  231. public getLODLevelAtDistance(distance: number): Mesh {
  232. for (var index = 0; index < this._LODLevels.length; index++) {
  233. var level = this._LODLevels[index];
  234. if (level.distance === distance) {
  235. return level.mesh;
  236. }
  237. }
  238. return null;
  239. }
  240. /**
  241. * Remove a mesh from the LOD array
  242. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  243. * @param {Mesh} mesh The mesh to be removed.
  244. * @return {Mesh} This mesh (for chaining)
  245. */
  246. public removeLODLevel(mesh: Mesh): Mesh {
  247. for (var index = 0; index < this._LODLevels.length; index++) {
  248. if (this._LODLevels[index].mesh === mesh) {
  249. this._LODLevels.splice(index, 1);
  250. if (mesh) {
  251. mesh._masterMesh = null;
  252. }
  253. }
  254. }
  255. this._sortLODLevels();
  256. return this;
  257. }
  258. /**
  259. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  260. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  261. */
  262. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  263. if (!this._LODLevels || this._LODLevels.length === 0) {
  264. return this;
  265. }
  266. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  267. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  268. if (this.onLODLevelSelection) {
  269. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  270. }
  271. return this;
  272. }
  273. for (var index = 0; index < this._LODLevels.length; index++) {
  274. var level = this._LODLevels[index];
  275. if (level.distance < distanceToCamera) {
  276. if (level.mesh) {
  277. level.mesh._preActivate();
  278. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  279. }
  280. if (this.onLODLevelSelection) {
  281. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  282. }
  283. return level.mesh;
  284. }
  285. }
  286. if (this.onLODLevelSelection) {
  287. this.onLODLevelSelection(distanceToCamera, this, this);
  288. }
  289. return this;
  290. }
  291. /**
  292. * Returns the mesh internal Geometry object.
  293. */
  294. public get geometry(): Geometry {
  295. return this._geometry;
  296. }
  297. /**
  298. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  299. */
  300. public getTotalVertices(): number {
  301. if (!this._geometry) {
  302. return 0;
  303. }
  304. return this._geometry.getTotalVertices();
  305. }
  306. /**
  307. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  308. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  309. * Returns null if the mesh has no geometry or no vertex buffer.
  310. * Possible `kind` values :
  311. * - BABYLON.VertexBuffer.PositionKind
  312. * - BABYLON.VertexBuffer.UVKind
  313. * - BABYLON.VertexBuffer.UV2Kind
  314. * - BABYLON.VertexBuffer.UV3Kind
  315. * - BABYLON.VertexBuffer.UV4Kind
  316. * - BABYLON.VertexBuffer.UV5Kind
  317. * - BABYLON.VertexBuffer.UV6Kind
  318. * - BABYLON.VertexBuffer.ColorKind
  319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  323. */
  324. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array {
  325. if (!this._geometry) {
  326. return null;
  327. }
  328. return this._geometry.getVerticesData(kind, copyWhenShared);
  329. }
  330. /**
  331. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  332. * Returns `undefined` if the mesh has no geometry.
  333. * Possible `kind` values :
  334. * - BABYLON.VertexBuffer.PositionKind
  335. * - BABYLON.VertexBuffer.UVKind
  336. * - BABYLON.VertexBuffer.UV2Kind
  337. * - BABYLON.VertexBuffer.UV3Kind
  338. * - BABYLON.VertexBuffer.UV4Kind
  339. * - BABYLON.VertexBuffer.UV5Kind
  340. * - BABYLON.VertexBuffer.UV6Kind
  341. * - BABYLON.VertexBuffer.ColorKind
  342. * - BABYLON.VertexBuffer.MatricesIndicesKind
  343. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  344. * - BABYLON.VertexBuffer.MatricesWeightsKind
  345. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  346. */
  347. public getVertexBuffer(kind): VertexBuffer {
  348. if (!this._geometry) {
  349. return undefined;
  350. }
  351. return this._geometry.getVertexBuffer(kind);
  352. }
  353. /**
  354. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  355. * Possible `kind` values :
  356. * - BABYLON.VertexBuffer.PositionKind
  357. * - BABYLON.VertexBuffer.UVKind
  358. * - BABYLON.VertexBuffer.UV2Kind
  359. * - BABYLON.VertexBuffer.UV3Kind
  360. * - BABYLON.VertexBuffer.UV4Kind
  361. * - BABYLON.VertexBuffer.UV5Kind
  362. * - BABYLON.VertexBuffer.UV6Kind
  363. * - BABYLON.VertexBuffer.ColorKind
  364. * - BABYLON.VertexBuffer.MatricesIndicesKind
  365. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  366. * - BABYLON.VertexBuffer.MatricesWeightsKind
  367. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  368. */
  369. public isVerticesDataPresent(kind: string): boolean {
  370. if (!this._geometry) {
  371. if (this._delayInfo) {
  372. return this._delayInfo.indexOf(kind) !== -1;
  373. }
  374. return false;
  375. }
  376. return this._geometry.isVerticesDataPresent(kind);
  377. }
  378. /**
  379. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  380. * Possible `kind` values :
  381. * - BABYLON.VertexBuffer.PositionKind
  382. * - BABYLON.VertexBuffer.UVKind
  383. * - BABYLON.VertexBuffer.UV2Kind
  384. * - BABYLON.VertexBuffer.UV3Kind
  385. * - BABYLON.VertexBuffer.UV4Kind
  386. * - BABYLON.VertexBuffer.UV5Kind
  387. * - BABYLON.VertexBuffer.UV6Kind
  388. * - BABYLON.VertexBuffer.ColorKind
  389. * - BABYLON.VertexBuffer.MatricesIndicesKind
  390. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  391. * - BABYLON.VertexBuffer.MatricesWeightsKind
  392. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  393. */
  394. public getVerticesDataKinds(): string[] {
  395. if (!this._geometry) {
  396. var result = [];
  397. if (this._delayInfo) {
  398. this._delayInfo.forEach(function (kind, index, array) {
  399. result.push(kind);
  400. });
  401. }
  402. return result;
  403. }
  404. return this._geometry.getVerticesDataKinds();
  405. }
  406. /**
  407. * Returns a positive integer : the total number of indices in this mesh geometry.
  408. * Returns zero if the mesh has no geometry.
  409. */
  410. public getTotalIndices(): number {
  411. if (!this._geometry) {
  412. return 0;
  413. }
  414. return this._geometry.getTotalIndices();
  415. }
  416. /**
  417. * Returns an array of integers or a Int32Array populated with the mesh indices.
  418. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  419. * Returns an empty array if the mesh has no geometry.
  420. */
  421. public getIndices(copyWhenShared?: boolean): number[] | Int32Array {
  422. if (!this._geometry) {
  423. return [];
  424. }
  425. return this._geometry.getIndices(copyWhenShared);
  426. }
  427. public get isBlocked(): boolean {
  428. return this._masterMesh !== null && this._masterMesh !== undefined;
  429. }
  430. /**
  431. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  432. */
  433. public isReady(): boolean {
  434. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  435. return false;
  436. }
  437. return super.isReady();
  438. }
  439. /**
  440. * Boolean : true if the mesh has been disposed.
  441. */
  442. public isDisposed(): boolean {
  443. return this._isDisposed;
  444. }
  445. public get sideOrientation(): number {
  446. return this._sideOrientation;
  447. }
  448. /**
  449. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  450. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  451. */
  452. public set sideOrientation(sideO: number) {
  453. this._sideOrientation = sideO;
  454. }
  455. /**
  456. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  457. * This property is pertinent only for updatable parametric shapes.
  458. */
  459. public get areNormalsFrozen(): boolean {
  460. return this._areNormalsFrozen;
  461. }
  462. /**
  463. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  464. * It has no effect at all on other shapes.
  465. * It prevents the mesh normals from being recomputed on next `positions` array update.
  466. */
  467. public freezeNormals(): void {
  468. this._areNormalsFrozen = true;
  469. }
  470. /**
  471. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  472. * It has no effect at all on other shapes.
  473. * It reactivates the mesh normals computation if it was previously frozen.
  474. */
  475. public unfreezeNormals(): void {
  476. this._areNormalsFrozen = false;
  477. }
  478. /**
  479. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  480. */
  481. public set overridenInstanceCount(count: number) {
  482. this._overridenInstanceCount = count;
  483. }
  484. // Methods
  485. public _preActivate(): void {
  486. var sceneRenderId = this.getScene().getRenderId();
  487. if (this._preActivateId === sceneRenderId) {
  488. return;
  489. }
  490. this._preActivateId = sceneRenderId;
  491. this._visibleInstances = null;
  492. }
  493. public _preActivateForIntermediateRendering(renderId: number): void {
  494. if (this._visibleInstances) {
  495. this._visibleInstances.intermediateDefaultRenderId = renderId;
  496. }
  497. }
  498. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  499. if (!this._visibleInstances) {
  500. this._visibleInstances = {};
  501. this._visibleInstances.defaultRenderId = renderId;
  502. this._visibleInstances.selfDefaultRenderId = this._renderId;
  503. }
  504. if (!this._visibleInstances[renderId]) {
  505. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  506. }
  507. this._visibleInstances[renderId].push(instance);
  508. }
  509. /**
  510. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  511. * This means the mesh underlying bounding box and sphere are recomputed.
  512. */
  513. public refreshBoundingInfo(): void {
  514. if (this._boundingInfo.isLocked) {
  515. return;
  516. }
  517. var data = this.getVerticesData(VertexBuffer.PositionKind);
  518. if (data) {
  519. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  520. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  521. }
  522. if (this.subMeshes) {
  523. for (var index = 0; index < this.subMeshes.length; index++) {
  524. this.subMeshes[index].refreshBoundingInfo();
  525. }
  526. }
  527. this._updateBoundingInfo();
  528. }
  529. public _createGlobalSubMesh(): SubMesh {
  530. var totalVertices = this.getTotalVertices();
  531. if (!totalVertices || !this.getIndices()) {
  532. return null;
  533. }
  534. this.releaseSubMeshes();
  535. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  536. }
  537. public subdivide(count: number): void {
  538. if (count < 1) {
  539. return;
  540. }
  541. var totalIndices = this.getTotalIndices();
  542. var subdivisionSize = (totalIndices / count) | 0;
  543. var offset = 0;
  544. // Ensure that subdivisionSize is a multiple of 3
  545. while (subdivisionSize % 3 !== 0) {
  546. subdivisionSize++;
  547. }
  548. this.releaseSubMeshes();
  549. for (var index = 0; index < count; index++) {
  550. if (offset >= totalIndices) {
  551. break;
  552. }
  553. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  554. offset += subdivisionSize;
  555. }
  556. this.synchronizeInstances();
  557. }
  558. /**
  559. * Sets the vertex data of the mesh geometry for the requested `kind`.
  560. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  561. * The `data` are either a numeric array either a Float32Array.
  562. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  563. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  564. * Note that a new underlying VertexBuffer object is created each call.
  565. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  566. *
  567. * Possible `kind` values :
  568. * - BABYLON.VertexBuffer.PositionKind
  569. * - BABYLON.VertexBuffer.UVKind
  570. * - BABYLON.VertexBuffer.UV2Kind
  571. * - BABYLON.VertexBuffer.UV3Kind
  572. * - BABYLON.VertexBuffer.UV4Kind
  573. * - BABYLON.VertexBuffer.UV5Kind
  574. * - BABYLON.VertexBuffer.UV6Kind
  575. * - BABYLON.VertexBuffer.ColorKind
  576. * - BABYLON.VertexBuffer.MatricesIndicesKind
  577. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  578. * - BABYLON.VertexBuffer.MatricesWeightsKind
  579. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  580. */
  581. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void {
  582. if (!this._geometry) {
  583. var vertexData = new VertexData();
  584. vertexData.set(data, kind);
  585. var scene = this.getScene();
  586. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  587. }
  588. else {
  589. this._geometry.setVerticesData(kind, data, updatable, stride);
  590. }
  591. }
  592. public setVerticesBuffer(buffer: VertexBuffer): void {
  593. if (!this._geometry) {
  594. var scene = this.getScene();
  595. new Geometry(Geometry.RandomId(), scene).applyToMesh(this);
  596. }
  597. this._geometry.setVerticesBuffer(buffer);
  598. }
  599. /**
  600. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  601. * If the mesh has no geometry, it is simply returned as it is.
  602. * The `data` are either a numeric array either a Float32Array.
  603. * No new underlying VertexBuffer object is created.
  604. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  605. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  606. *
  607. * Possible `kind` values :
  608. * - BABYLON.VertexBuffer.PositionKind
  609. * - BABYLON.VertexBuffer.UVKind
  610. * - BABYLON.VertexBuffer.UV2Kind
  611. * - BABYLON.VertexBuffer.UV3Kind
  612. * - BABYLON.VertexBuffer.UV4Kind
  613. * - BABYLON.VertexBuffer.UV5Kind
  614. * - BABYLON.VertexBuffer.UV6Kind
  615. * - BABYLON.VertexBuffer.ColorKind
  616. * - BABYLON.VertexBuffer.MatricesIndicesKind
  617. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  618. * - BABYLON.VertexBuffer.MatricesWeightsKind
  619. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  620. */
  621. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void {
  622. if (!this._geometry) {
  623. return;
  624. }
  625. if (!makeItUnique) {
  626. this._geometry.updateVerticesData(kind, data, updateExtends);
  627. }
  628. else {
  629. this.makeGeometryUnique();
  630. this.updateVerticesData(kind, data, updateExtends, false);
  631. }
  632. }
  633. /**
  634. * Deprecated since BabylonJS v2.3
  635. */
  636. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  637. Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  638. if (!this._geometry) {
  639. return;
  640. }
  641. if (!makeItUnique) {
  642. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  643. }
  644. else {
  645. this.makeGeometryUnique();
  646. this.updateVerticesDataDirectly(kind, data, offset, false);
  647. }
  648. }
  649. /**
  650. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  651. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  652. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  653. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  654. */
  655. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  656. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  657. positionFunction(positions);
  658. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  659. if (computeNormals) {
  660. var indices = this.getIndices();
  661. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  662. VertexData.ComputeNormals(positions, indices, normals);
  663. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  664. }
  665. }
  666. public makeGeometryUnique() {
  667. if (!this._geometry) {
  668. return;
  669. }
  670. var oldGeometry = this._geometry;
  671. var geometry = this._geometry.copy(Geometry.RandomId());
  672. oldGeometry.releaseForMesh(this, true);
  673. geometry.applyToMesh(this);
  674. }
  675. /**
  676. * Sets the mesh indices.
  677. * Expects an array populated with integers or a Int32Array.
  678. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  679. * This method creates a new index buffer each call.
  680. */
  681. public setIndices(indices: number[] | Int32Array, totalVertices?: number): void {
  682. if (!this._geometry) {
  683. var vertexData = new VertexData();
  684. vertexData.indices = indices;
  685. var scene = this.getScene();
  686. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  687. }
  688. else {
  689. this._geometry.setIndices(indices, totalVertices);
  690. }
  691. }
  692. /**
  693. * Invert the geometry to move from a right handed system to a left handed one.
  694. */
  695. public toLeftHanded(): void {
  696. if (!this._geometry) {
  697. return;
  698. }
  699. this._geometry.toLeftHanded();
  700. }
  701. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  702. var engine = this.getScene().getEngine();
  703. // Wireframe
  704. var indexToBind;
  705. if (this._unIndexed) {
  706. indexToBind = null;
  707. } else {
  708. switch (fillMode) {
  709. case Material.PointFillMode:
  710. indexToBind = null;
  711. break;
  712. case Material.WireFrameFillMode:
  713. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  714. break;
  715. default:
  716. case Material.TriangleFillMode:
  717. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  718. break;
  719. }
  720. }
  721. // VBOs
  722. this._geometry._bind(effect, indexToBind);
  723. }
  724. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  725. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  726. return;
  727. }
  728. this.onBeforeDrawObservable.notifyObservers(this);
  729. var engine = this.getScene().getEngine();
  730. // Draw order
  731. switch (fillMode) {
  732. case Material.PointFillMode:
  733. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  734. break;
  735. case Material.WireFrameFillMode:
  736. if (this._unIndexed) {
  737. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  738. } else {
  739. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  740. }
  741. break;
  742. default:
  743. if (this._unIndexed) {
  744. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  745. } else {
  746. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  747. }
  748. }
  749. }
  750. /**
  751. * Registers for this mesh a javascript function called just before the rendering process.
  752. * This function is passed the current mesh and doesn't return anything.
  753. */
  754. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  755. this.onBeforeRenderObservable.add(func);
  756. }
  757. /**
  758. * Disposes a previously registered javascript function called before the rendering.
  759. * This function is passed the current mesh and doesn't return anything.
  760. */
  761. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  762. this.onBeforeRenderObservable.removeCallback(func);
  763. }
  764. /**
  765. * Registers for this mesh a javascript function called just after the rendering is complete.
  766. * This function is passed the current mesh and doesn't return anything.
  767. */
  768. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  769. this.onAfterRenderObservable.add(func);
  770. }
  771. /**
  772. * Disposes a previously registered javascript function called after the rendering.
  773. * This function is passed the current mesh and doesn't return anything.
  774. */
  775. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  776. this.onAfterRenderObservable.removeCallback(func);
  777. }
  778. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  779. var scene = this.getScene();
  780. this._batchCache.mustReturn = false;
  781. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  782. this._batchCache.visibleInstances[subMeshId] = null;
  783. if (this._visibleInstances) {
  784. var currentRenderId = scene.getRenderId();
  785. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  786. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  787. var selfRenderId = this._renderId;
  788. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  789. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  790. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  791. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  792. }
  793. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  794. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  795. this._batchCache.mustReturn = true;
  796. return this._batchCache;
  797. }
  798. if (currentRenderId !== selfRenderId) {
  799. this._batchCache.renderSelf[subMeshId] = false;
  800. }
  801. }
  802. this._renderIdForInstances[subMeshId] = currentRenderId;
  803. }
  804. return this._batchCache;
  805. }
  806. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  807. var visibleInstances = batch.visibleInstances[subMesh._id];
  808. var matricesCount = visibleInstances.length + 1;
  809. var bufferSize = matricesCount * 16 * 4;
  810. var currentInstancesBufferSize = this._instancesBufferSize;
  811. var instancesBuffer = this._instancesBuffer;
  812. while (this._instancesBufferSize < bufferSize) {
  813. this._instancesBufferSize *= 2;
  814. }
  815. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  816. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  817. }
  818. var offset = 0;
  819. var instancesCount = 0;
  820. var world = this.getWorldMatrix();
  821. if (batch.renderSelf[subMesh._id]) {
  822. world.copyToArray(this._instancesData, offset);
  823. offset += 16;
  824. instancesCount++;
  825. }
  826. if (visibleInstances) {
  827. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  828. var instance = visibleInstances[instanceIndex];
  829. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  830. offset += 16;
  831. instancesCount++;
  832. }
  833. }
  834. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  835. if (instancesBuffer) {
  836. instancesBuffer.dispose();
  837. }
  838. instancesBuffer = new Buffer(engine, this._instancesData, true, 16, false, true);
  839. this._instancesBuffer = instancesBuffer;
  840. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  841. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  842. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  843. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  844. } else {
  845. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  846. }
  847. this.geometry._bind(effect);
  848. this._draw(subMesh, fillMode, instancesCount);
  849. engine.unbindInstanceAttributes();
  850. }
  851. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  852. onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material) {
  853. var scene = this.getScene();
  854. var engine = scene.getEngine();
  855. if (hardwareInstancedRendering) {
  856. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  857. } else {
  858. if (batch.renderSelf[subMesh._id]) {
  859. // Draw
  860. if (onBeforeDraw) {
  861. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  862. }
  863. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  864. }
  865. if (batch.visibleInstances[subMesh._id]) {
  866. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  867. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  868. // World
  869. var world = instance.getWorldMatrix();
  870. if (onBeforeDraw) {
  871. onBeforeDraw(true, world, effectiveMaterial);
  872. }
  873. // Draw
  874. this._draw(subMesh, fillMode);
  875. }
  876. }
  877. }
  878. }
  879. /**
  880. * Triggers the draw call for the mesh.
  881. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  882. */
  883. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  884. var scene = this.getScene();
  885. // Managing instances
  886. var batch = this._getInstancesRenderList(subMesh._id);
  887. if (batch.mustReturn) {
  888. return;
  889. }
  890. // Checking geometry state
  891. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  892. return;
  893. }
  894. var callbackIndex: number;
  895. this.onBeforeRenderObservable.notifyObservers(this);
  896. var engine = scene.getEngine();
  897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  898. // Material
  899. var effectiveMaterial = subMesh.getMaterial();
  900. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  901. return;
  902. }
  903. // Outline - step 1
  904. var savedDepthWrite = engine.getDepthWrite();
  905. if (this.renderOutline) {
  906. engine.setDepthWrite(false);
  907. scene.getOutlineRenderer().render(subMesh, batch);
  908. engine.setDepthWrite(savedDepthWrite);
  909. }
  910. effectiveMaterial._preBind();
  911. var effect = effectiveMaterial.getEffect();
  912. // Bind
  913. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  914. this._bind(subMesh, effect, fillMode);
  915. var world = this.getWorldMatrix();
  916. effectiveMaterial.bind(world, this);
  917. // Alpha mode
  918. if (enableAlphaMode) {
  919. engine.setAlphaMode(effectiveMaterial.alphaMode);
  920. }
  921. // Draw
  922. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  923. // Unbind
  924. effectiveMaterial.unbind();
  925. // Outline - step 2
  926. if (this.renderOutline && savedDepthWrite) {
  927. engine.setDepthWrite(true);
  928. engine.setColorWrite(false);
  929. scene.getOutlineRenderer().render(subMesh, batch);
  930. engine.setColorWrite(true);
  931. }
  932. // Overlay
  933. if (this.renderOverlay) {
  934. var currentMode = engine.getAlphaMode();
  935. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  936. scene.getOutlineRenderer().render(subMesh, batch, true);
  937. engine.setAlphaMode(currentMode);
  938. }
  939. this.onAfterRenderObservable.notifyObservers(this);
  940. }
  941. private _onBeforeDraw(isInstance: boolean, world: Matrix, effectiveMaterial: Material): void {
  942. if (isInstance) {
  943. effectiveMaterial.bindOnlyWorldMatrix(world);
  944. }
  945. }
  946. /**
  947. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  948. */
  949. public getEmittedParticleSystems(): ParticleSystem[] {
  950. var results = new Array<ParticleSystem>();
  951. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  952. var particleSystem = this.getScene().particleSystems[index];
  953. if (particleSystem.emitter === this) {
  954. results.push(particleSystem);
  955. }
  956. }
  957. return results;
  958. }
  959. /**
  960. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  961. */
  962. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  963. var results = new Array<ParticleSystem>();
  964. var descendants = this.getDescendants();
  965. descendants.push(this);
  966. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  967. var particleSystem = this.getScene().particleSystems[index];
  968. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  969. results.push(particleSystem);
  970. }
  971. }
  972. return results;
  973. }
  974. public _checkDelayState(): void {
  975. var scene = this.getScene();
  976. if (this._geometry) {
  977. this._geometry.load(scene);
  978. }
  979. else if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  980. this.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  981. this._queueLoad(this, scene);
  982. }
  983. }
  984. private _queueLoad(mesh: Mesh, scene: Scene): void {
  985. scene._addPendingData(mesh);
  986. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  987. Tools.LoadFile(this.delayLoadingFile, data => {
  988. if (data instanceof ArrayBuffer) {
  989. this._delayLoadingFunction(data, this);
  990. }
  991. else {
  992. this._delayLoadingFunction(JSON.parse(data), this);
  993. }
  994. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  995. scene._removePendingData(this);
  996. }, () => { }, scene.database, getBinaryData);
  997. }
  998. /**
  999. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  1000. */
  1001. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1002. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1003. return false;
  1004. }
  1005. if (!super.isInFrustum(frustumPlanes)) {
  1006. return false;
  1007. }
  1008. this._checkDelayState();
  1009. return true;
  1010. }
  1011. /**
  1012. * Sets the mesh material by the material or multiMaterial `id` property.
  1013. * The material `id` is a string identifying the material or the multiMaterial.
  1014. * This method returns nothing.
  1015. */
  1016. public setMaterialByID(id: string): void {
  1017. var materials = this.getScene().materials;
  1018. var index: number;
  1019. for (index = 0; index < materials.length; index++) {
  1020. if (materials[index].id === id) {
  1021. this.material = materials[index];
  1022. return;
  1023. }
  1024. }
  1025. // Multi
  1026. var multiMaterials = this.getScene().multiMaterials;
  1027. for (index = 0; index < multiMaterials.length; index++) {
  1028. if (multiMaterials[index].id === id) {
  1029. this.material = multiMaterials[index];
  1030. return;
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  1036. */
  1037. public getAnimatables(): IAnimatable[] {
  1038. var results = [];
  1039. if (this.material) {
  1040. results.push(this.material);
  1041. }
  1042. if (this.skeleton) {
  1043. results.push(this.skeleton);
  1044. }
  1045. return results;
  1046. }
  1047. /**
  1048. * Modifies the mesh geometry according to the passed transformation matrix.
  1049. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  1050. * The mesh normals are modified accordingly the same transformation.
  1051. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1052. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1053. */
  1054. public bakeTransformIntoVertices(transform: Matrix): void {
  1055. // Position
  1056. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1057. return;
  1058. }
  1059. var submeshes = this.subMeshes.splice(0);
  1060. this._resetPointsArrayCache();
  1061. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1062. var temp = [];
  1063. var index: number;
  1064. for (index = 0; index < data.length; index += 3) {
  1065. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1066. }
  1067. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  1068. // Normals
  1069. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1070. return;
  1071. }
  1072. data = this.getVerticesData(VertexBuffer.NormalKind);
  1073. temp = [];
  1074. for (index = 0; index < data.length; index += 3) {
  1075. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1076. }
  1077. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  1078. // flip faces?
  1079. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1080. // Restore submeshes
  1081. this.releaseSubMeshes();
  1082. this.subMeshes = submeshes;
  1083. }
  1084. /**
  1085. * Modifies the mesh geometry according to its own current World Matrix.
  1086. * The mesh World Matrix is then reset.
  1087. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  1088. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1089. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1090. */
  1091. public bakeCurrentTransformIntoVertices(): void {
  1092. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1093. this.scaling.copyFromFloats(1, 1, 1);
  1094. this.position.copyFromFloats(0, 0, 0);
  1095. this.rotation.copyFromFloats(0, 0, 0);
  1096. //only if quaternion is already set
  1097. if (this.rotationQuaternion) {
  1098. this.rotationQuaternion = Quaternion.Identity();
  1099. }
  1100. this._worldMatrix = Matrix.Identity();
  1101. }
  1102. // Cache
  1103. public _resetPointsArrayCache(): void {
  1104. this._positions = null;
  1105. }
  1106. public _generatePointsArray(): boolean {
  1107. if (this._positions)
  1108. return true;
  1109. this._positions = [];
  1110. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1111. if (!data) {
  1112. return false;
  1113. }
  1114. for (var index = 0; index < data.length; index += 3) {
  1115. this._positions.push(Vector3.FromArray(data, index));
  1116. }
  1117. return true;
  1118. }
  1119. /**
  1120. * Returns a new Mesh object generated from the current mesh properties.
  1121. * This method must not get confused with createInstance().
  1122. * The parameter `name` is a string, the name given to the new mesh.
  1123. * The optional parameter `newParent` can be any Node object (default `null`).
  1124. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  1125. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  1126. */
  1127. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1128. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1129. }
  1130. /**
  1131. * Disposes the mesh.
  1132. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  1133. */
  1134. public dispose(doNotRecurse?: boolean): void {
  1135. if (this._geometry) {
  1136. this._geometry.releaseForMesh(this, true);
  1137. }
  1138. // Instances
  1139. if (this._instancesBuffer) {
  1140. this._instancesBuffer.dispose();
  1141. this._instancesBuffer = null;
  1142. }
  1143. while (this.instances.length) {
  1144. this.instances[0].dispose();
  1145. }
  1146. // Highlight layers.
  1147. let highlightLayers = this.getScene().highlightLayers;
  1148. for (let i = 0; i < highlightLayers.length; i++) {
  1149. let highlightLayer = highlightLayers[i];
  1150. if (highlightLayer) {
  1151. highlightLayer.removeMesh(this);
  1152. highlightLayer.removeExcludedMesh(this);
  1153. }
  1154. }
  1155. super.dispose(doNotRecurse);
  1156. }
  1157. /**
  1158. * Modifies the mesh geometry according to a displacement map.
  1159. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1160. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1161. * This method returns nothing.
  1162. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  1163. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1164. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  1165. */
  1166. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  1167. var scene = this.getScene();
  1168. var onload = img => {
  1169. // Getting height map data
  1170. var canvas = document.createElement("canvas");
  1171. var context = canvas.getContext("2d");
  1172. var heightMapWidth = img.width;
  1173. var heightMapHeight = img.height;
  1174. canvas.width = heightMapWidth;
  1175. canvas.height = heightMapHeight;
  1176. context.drawImage(img, 0, 0);
  1177. // Create VertexData from map data
  1178. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1179. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1180. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  1181. //execute success callback, if set
  1182. if (onSuccess) {
  1183. onSuccess(this);
  1184. }
  1185. };
  1186. Tools.LoadImage(url, onload, () => { }, scene.database);
  1187. }
  1188. /**
  1189. * Modifies the mesh geometry according to a displacementMap buffer.
  1190. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1191. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1192. * This method returns nothing.
  1193. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  1194. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  1195. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1196. */
  1197. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  1198. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1199. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1200. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1201. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1202. return;
  1203. }
  1204. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1205. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1206. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  1207. var position = Vector3.Zero();
  1208. var normal = Vector3.Zero();
  1209. var uv = Vector2.Zero();
  1210. for (var index = 0; index < positions.length; index += 3) {
  1211. Vector3.FromArrayToRef(positions, index, position);
  1212. Vector3.FromArrayToRef(normals, index, normal);
  1213. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1214. // Compute height
  1215. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  1216. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  1217. var pos = (u + v * heightMapWidth) * 4;
  1218. var r = buffer[pos] / 255.0;
  1219. var g = buffer[pos + 1] / 255.0;
  1220. var b = buffer[pos + 2] / 255.0;
  1221. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1222. normal.normalize();
  1223. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1224. position = position.add(normal);
  1225. position.toArray(positions, index);
  1226. }
  1227. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1228. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1229. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1230. }
  1231. /**
  1232. * Modify the mesh to get a flat shading rendering.
  1233. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1234. * This method returns nothing.
  1235. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  1236. */
  1237. public convertToFlatShadedMesh(): void {
  1238. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  1239. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1240. var kinds = this.getVerticesDataKinds();
  1241. var vbs = [];
  1242. var data = [];
  1243. var newdata = [];
  1244. var updatableNormals = false;
  1245. var kindIndex: number;
  1246. var kind: string;
  1247. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1248. kind = kinds[kindIndex];
  1249. var vertexBuffer = this.getVertexBuffer(kind);
  1250. if (kind === VertexBuffer.NormalKind) {
  1251. updatableNormals = vertexBuffer.isUpdatable();
  1252. kinds.splice(kindIndex, 1);
  1253. kindIndex--;
  1254. continue;
  1255. }
  1256. vbs[kind] = vertexBuffer;
  1257. data[kind] = vbs[kind].getData();
  1258. newdata[kind] = [];
  1259. }
  1260. // Save previous submeshes
  1261. var previousSubmeshes = this.subMeshes.slice(0);
  1262. var indices = this.getIndices();
  1263. var totalIndices = this.getTotalIndices();
  1264. // Generating unique vertices per face
  1265. var index: number;
  1266. for (index = 0; index < totalIndices; index++) {
  1267. var vertexIndex = indices[index];
  1268. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1269. kind = kinds[kindIndex];
  1270. var stride = vbs[kind].getStrideSize();
  1271. for (var offset = 0; offset < stride; offset++) {
  1272. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1273. }
  1274. }
  1275. }
  1276. // Updating faces & normal
  1277. var normals = [];
  1278. var positions = newdata[VertexBuffer.PositionKind];
  1279. for (index = 0; index < totalIndices; index += 3) {
  1280. indices[index] = index;
  1281. indices[index + 1] = index + 1;
  1282. indices[index + 2] = index + 2;
  1283. var p1 = Vector3.FromArray(positions, index * 3);
  1284. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1285. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1286. var p1p2 = p1.subtract(p2);
  1287. var p3p2 = p3.subtract(p2);
  1288. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1289. // Store same normals for every vertex
  1290. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1291. normals.push(normal.x);
  1292. normals.push(normal.y);
  1293. normals.push(normal.z);
  1294. }
  1295. }
  1296. this.setIndices(indices);
  1297. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1298. // Updating vertex buffers
  1299. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1300. kind = kinds[kindIndex];
  1301. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1302. }
  1303. // Updating submeshes
  1304. this.releaseSubMeshes();
  1305. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1306. var previousOne = previousSubmeshes[submeshIndex];
  1307. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1308. }
  1309. this.synchronizeInstances();
  1310. }
  1311. /**
  1312. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1313. * In other words, more vertices, no more indices and a single bigger VBO.
  1314. * This method returns nothing.
  1315. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  1316. *
  1317. */
  1318. public convertToUnIndexedMesh(): void {
  1319. /// <summary>Remove indices by unfolding faces into buffers</summary>
  1320. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1321. var kinds = this.getVerticesDataKinds();
  1322. var vbs = [];
  1323. var data = [];
  1324. var newdata = [];
  1325. var updatableNormals = false;
  1326. var kindIndex: number;
  1327. var kind: string;
  1328. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1329. kind = kinds[kindIndex];
  1330. var vertexBuffer = this.getVertexBuffer(kind);
  1331. vbs[kind] = vertexBuffer;
  1332. data[kind] = vbs[kind].getData();
  1333. newdata[kind] = [];
  1334. }
  1335. // Save previous submeshes
  1336. var previousSubmeshes = this.subMeshes.slice(0);
  1337. var indices = this.getIndices();
  1338. var totalIndices = this.getTotalIndices();
  1339. // Generating unique vertices per face
  1340. var index: number;
  1341. for (index = 0; index < totalIndices; index++) {
  1342. var vertexIndex = indices[index];
  1343. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1344. kind = kinds[kindIndex];
  1345. var stride = vbs[kind].getStrideSize();
  1346. for (var offset = 0; offset < stride; offset++) {
  1347. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1348. }
  1349. }
  1350. }
  1351. // Updating indices
  1352. for (index = 0; index < totalIndices; index += 3) {
  1353. indices[index] = index;
  1354. indices[index + 1] = index + 1;
  1355. indices[index + 2] = index + 2;
  1356. }
  1357. this.setIndices(indices);
  1358. // Updating vertex buffers
  1359. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1360. kind = kinds[kindIndex];
  1361. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1362. }
  1363. // Updating submeshes
  1364. this.releaseSubMeshes();
  1365. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1366. var previousOne = previousSubmeshes[submeshIndex];
  1367. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1368. }
  1369. this._unIndexed = true;
  1370. this.synchronizeInstances();
  1371. }
  1372. /**
  1373. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  1374. * This method returns nothing.
  1375. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  1376. */
  1377. public flipFaces(flipNormals: boolean = false): void {
  1378. var vertex_data = VertexData.ExtractFromMesh(this);
  1379. var i: number;
  1380. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1381. for (i = 0; i < vertex_data.normals.length; i++) {
  1382. vertex_data.normals[i] *= -1;
  1383. }
  1384. }
  1385. var temp;
  1386. for (i = 0; i < vertex_data.indices.length; i += 3) {
  1387. // reassign indices
  1388. temp = vertex_data.indices[i + 1];
  1389. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  1390. vertex_data.indices[i + 2] = temp;
  1391. }
  1392. vertex_data.applyToMesh(this);
  1393. }
  1394. // Instances
  1395. /**
  1396. * Creates a new InstancedMesh object from the mesh model.
  1397. * An instance shares the same properties and the same material than its model.
  1398. * Only these properties of each instance can then be set individually :
  1399. * - position
  1400. * - rotation
  1401. * - rotationQuaternion
  1402. * - setPivotMatrix
  1403. * - scaling
  1404. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  1405. * Warning : this method is not supported for Line mesh and LineSystem
  1406. */
  1407. public createInstance(name: string): InstancedMesh {
  1408. return new InstancedMesh(name, this);
  1409. }
  1410. /**
  1411. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  1412. * After this call, all the mesh instances have the same submeshes than the current mesh.
  1413. * This method returns nothing.
  1414. */
  1415. public synchronizeInstances(): void {
  1416. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  1417. var instance = this.instances[instanceIndex];
  1418. instance._syncSubMeshes();
  1419. }
  1420. }
  1421. /**
  1422. * Simplify the mesh according to the given array of settings.
  1423. * Function will return immediately and will simplify async. It returns nothing.
  1424. * @param settings a collection of simplification settings.
  1425. * @param parallelProcessing should all levels calculate parallel or one after the other.
  1426. * @param type the type of simplification to run.
  1427. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  1428. */
  1429. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  1430. this.getScene().simplificationQueue.addTask({
  1431. settings: settings,
  1432. parallelProcessing: parallelProcessing,
  1433. mesh: this,
  1434. simplificationType: simplificationType,
  1435. successCallback: successCallback
  1436. });
  1437. }
  1438. /**
  1439. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  1440. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  1441. * This should be used together with the simplification to avoid disappearing triangles.
  1442. * @param successCallback an optional success callback to be called after the optimization finished.
  1443. */
  1444. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  1445. var indices = this.getIndices();
  1446. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1447. var vectorPositions = [];
  1448. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  1449. vectorPositions.push(Vector3.FromArray(positions, pos));
  1450. }
  1451. var dupes = [];
  1452. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  1453. var realPos = vectorPositions.length - 1 - iteration;
  1454. var testedPosition = vectorPositions[realPos];
  1455. for (var j = 0; j < realPos; ++j) {
  1456. var againstPosition = vectorPositions[j];
  1457. if (testedPosition.equals(againstPosition)) {
  1458. dupes[realPos] = j;
  1459. break;
  1460. }
  1461. }
  1462. }, () => {
  1463. for (var i = 0; i < indices.length; ++i) {
  1464. indices[i] = dupes[indices[i]] || indices[i];
  1465. }
  1466. //indices are now reordered
  1467. var originalSubMeshes = this.subMeshes.slice(0);
  1468. this.setIndices(indices);
  1469. this.subMeshes = originalSubMeshes;
  1470. if (successCallback) {
  1471. successCallback(this);
  1472. }
  1473. });
  1474. }
  1475. // Statics
  1476. /**
  1477. * Returns a new Mesh object what is a deep copy of the passed mesh.
  1478. * The parameter `parsedMesh` is the mesh to be copied.
  1479. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  1480. */
  1481. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  1482. var mesh = new Mesh(parsedMesh.name, scene);
  1483. mesh.id = parsedMesh.id;
  1484. Tags.AddTagsTo(mesh, parsedMesh.tags);
  1485. mesh.position = Vector3.FromArray(parsedMesh.position);
  1486. if (parsedMesh.metadata !== undefined) {
  1487. mesh.metadata = parsedMesh.metadata;
  1488. }
  1489. if (parsedMesh.rotationQuaternion) {
  1490. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  1491. } else if (parsedMesh.rotation) {
  1492. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  1493. }
  1494. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  1495. if (parsedMesh.localMatrix) {
  1496. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  1497. } else if (parsedMesh.pivotMatrix) {
  1498. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  1499. }
  1500. mesh.setEnabled(parsedMesh.isEnabled);
  1501. mesh.isVisible = parsedMesh.isVisible;
  1502. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  1503. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  1504. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  1505. if (parsedMesh.applyFog !== undefined) {
  1506. mesh.applyFog = parsedMesh.applyFog;
  1507. }
  1508. if (parsedMesh.pickable !== undefined) {
  1509. mesh.isPickable = parsedMesh.pickable;
  1510. }
  1511. if (parsedMesh.alphaIndex !== undefined) {
  1512. mesh.alphaIndex = parsedMesh.alphaIndex;
  1513. }
  1514. mesh.receiveShadows = parsedMesh.receiveShadows;
  1515. mesh.billboardMode = parsedMesh.billboardMode;
  1516. if (parsedMesh.visibility !== undefined) {
  1517. mesh.visibility = parsedMesh.visibility;
  1518. }
  1519. mesh.checkCollisions = parsedMesh.checkCollisions;
  1520. if (parsedMesh.isBlocker !== undefined) {
  1521. mesh.isBlocker = parsedMesh.isBlocker;
  1522. }
  1523. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  1524. // freezeWorldMatrix
  1525. if (parsedMesh.freezeWorldMatrix) {
  1526. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  1527. }
  1528. // Parent
  1529. if (parsedMesh.parentId) {
  1530. mesh._waitingParentId = parsedMesh.parentId;
  1531. }
  1532. // Actions
  1533. if (parsedMesh.actions !== undefined) {
  1534. mesh._waitingActions = parsedMesh.actions;
  1535. }
  1536. // Overlay
  1537. if (parsedMesh.overlayAlpha !== undefined) {
  1538. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  1539. }
  1540. if (parsedMesh.overlayColor !== undefined) {
  1541. mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
  1542. }
  1543. if (parsedMesh.renderOverlay !== undefined) {
  1544. mesh.renderOverlay = parsedMesh.renderOverlay;
  1545. }
  1546. // Geometry
  1547. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  1548. if (parsedMesh.delayLoadingFile) {
  1549. mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1550. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  1551. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  1552. if (parsedMesh._binaryInfo) {
  1553. mesh._binaryInfo = parsedMesh._binaryInfo;
  1554. }
  1555. mesh._delayInfo = [];
  1556. if (parsedMesh.hasUVs) {
  1557. mesh._delayInfo.push(VertexBuffer.UVKind);
  1558. }
  1559. if (parsedMesh.hasUVs2) {
  1560. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  1561. }
  1562. if (parsedMesh.hasUVs3) {
  1563. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  1564. }
  1565. if (parsedMesh.hasUVs4) {
  1566. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  1567. }
  1568. if (parsedMesh.hasUVs5) {
  1569. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  1570. }
  1571. if (parsedMesh.hasUVs6) {
  1572. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  1573. }
  1574. if (parsedMesh.hasColors) {
  1575. mesh._delayInfo.push(VertexBuffer.ColorKind);
  1576. }
  1577. if (parsedMesh.hasMatricesIndices) {
  1578. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1579. }
  1580. if (parsedMesh.hasMatricesWeights) {
  1581. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1582. }
  1583. mesh._delayLoadingFunction = Geometry.ImportGeometry;
  1584. if (SceneLoader.ForceFullSceneLoadingForIncremental) {
  1585. mesh._checkDelayState();
  1586. }
  1587. } else {
  1588. Geometry.ImportGeometry(parsedMesh, mesh);
  1589. }
  1590. // Material
  1591. if (parsedMesh.materialId) {
  1592. mesh.setMaterialByID(parsedMesh.materialId);
  1593. } else {
  1594. mesh.material = null;
  1595. }
  1596. // Skeleton
  1597. if (parsedMesh.skeletonId > -1) {
  1598. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  1599. if (parsedMesh.numBoneInfluencers) {
  1600. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  1601. }
  1602. }
  1603. // Animations
  1604. if (parsedMesh.animations) {
  1605. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1606. var parsedAnimation = parsedMesh.animations[animationIndex];
  1607. mesh.animations.push(Animation.Parse(parsedAnimation));
  1608. }
  1609. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  1610. }
  1611. if (parsedMesh.autoAnimate) {
  1612. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  1613. }
  1614. // Layer Mask
  1615. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  1616. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  1617. } else {
  1618. mesh.layerMask = 0x0FFFFFFF;
  1619. }
  1620. //(Deprecated) physics
  1621. if (parsedMesh.physicsImpostor) {
  1622. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  1623. mass: parsedMesh.physicsMass,
  1624. friction: parsedMesh.physicsFriction,
  1625. restitution: parsedMesh.physicsRestitution
  1626. }, scene);
  1627. }
  1628. // Instances
  1629. if (parsedMesh.instances) {
  1630. for (var index = 0; index < parsedMesh.instances.length; index++) {
  1631. var parsedInstance = parsedMesh.instances[index];
  1632. var instance = mesh.createInstance(parsedInstance.name);
  1633. Tags.AddTagsTo(instance, parsedInstance.tags);
  1634. instance.position = Vector3.FromArray(parsedInstance.position);
  1635. if (parsedInstance.parentId) {
  1636. instance._waitingParentId = parsedInstance.parentId;
  1637. }
  1638. if (parsedInstance.rotationQuaternion) {
  1639. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  1640. } else if (parsedInstance.rotation) {
  1641. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  1642. }
  1643. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  1644. instance.checkCollisions = mesh.checkCollisions;
  1645. if (parsedMesh.animations) {
  1646. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1647. parsedAnimation = parsedMesh.animations[animationIndex];
  1648. instance.animations.push(Animation.Parse(parsedAnimation));
  1649. }
  1650. Node.ParseAnimationRanges(instance, parsedMesh, scene);
  1651. }
  1652. }
  1653. }
  1654. return mesh;
  1655. }
  1656. /**
  1657. * Creates a ribbon mesh.
  1658. * Please consider using the same method from the MeshBuilder class instead.
  1659. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1660. *
  1661. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  1662. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  1663. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  1664. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  1665. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  1666. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  1667. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  1668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1671. */
  1672. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1673. return MeshBuilder.CreateRibbon(name, {
  1674. pathArray: pathArray,
  1675. closeArray: closeArray,
  1676. closePath: closePath,
  1677. offset: offset,
  1678. updatable: updatable,
  1679. sideOrientation: sideOrientation,
  1680. instance: instance
  1681. }, scene);
  1682. }
  1683. /**
  1684. * Creates a plane polygonal mesh. By default, this is a disc.
  1685. * Please consider using the same method from the MeshBuilder class instead.
  1686. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  1687. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  1688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1689. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1691. */
  1692. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1693. var options = {
  1694. radius: radius,
  1695. tessellation: tessellation,
  1696. sideOrientation: sideOrientation,
  1697. updatable: updatable
  1698. }
  1699. return MeshBuilder.CreateDisc(name, options, scene);
  1700. }
  1701. /**
  1702. * Creates a box mesh.
  1703. * Please consider using the same method from the MeshBuilder class instead.
  1704. * The parameter `size` sets the size (float) of each box side (default 1).
  1705. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1708. */
  1709. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1710. var options = {
  1711. size: size,
  1712. sideOrientation: sideOrientation,
  1713. updatable: updatable
  1714. };
  1715. return MeshBuilder.CreateBox(name, options, scene);
  1716. }
  1717. /**
  1718. * Creates a sphere mesh.
  1719. * Please consider using the same method from the MeshBuilder class instead.
  1720. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  1721. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  1722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1723. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1725. */
  1726. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1727. var options = {
  1728. segments: segments,
  1729. diameterX: diameter,
  1730. diameterY: diameter,
  1731. diameterZ: diameter,
  1732. sideOrientation: sideOrientation,
  1733. updatable: updatable
  1734. }
  1735. return MeshBuilder.CreateSphere(name, options, scene);
  1736. }
  1737. /**
  1738. * Creates a cylinder or a cone mesh.
  1739. * Please consider using the same method from the MeshBuilder class instead.
  1740. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  1741. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  1742. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  1743. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  1744. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  1745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1748. */
  1749. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh {
  1750. if (scene === undefined || !(scene instanceof Scene)) {
  1751. if (scene !== undefined) {
  1752. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  1753. updatable = scene;
  1754. }
  1755. scene = <Scene>subdivisions;
  1756. subdivisions = 1;
  1757. }
  1758. var options = {
  1759. height: height,
  1760. diameterTop: diameterTop,
  1761. diameterBottom: diameterBottom,
  1762. tessellation: tessellation,
  1763. subdivisions: subdivisions,
  1764. sideOrientation: sideOrientation,
  1765. updatable: updatable
  1766. }
  1767. return MeshBuilder.CreateCylinder(name, options, scene);
  1768. }
  1769. // Torus (Code from SharpDX.org)
  1770. /**
  1771. * Creates a torus mesh.
  1772. * Please consider using the same method from the MeshBuilder class instead.
  1773. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  1774. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  1775. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  1776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1777. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1779. */
  1780. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1781. var options = {
  1782. diameter: diameter,
  1783. thickness: thickness,
  1784. tessellation: tessellation,
  1785. sideOrientation: sideOrientation,
  1786. updatable: updatable
  1787. }
  1788. return MeshBuilder.CreateTorus(name, options, scene);
  1789. }
  1790. /**
  1791. * Creates a torus knot mesh.
  1792. * Please consider using the same method from the MeshBuilder class instead.
  1793. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  1794. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  1795. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  1796. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  1797. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1800. */
  1801. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1802. var options = {
  1803. radius: radius,
  1804. tube: tube,
  1805. radialSegments: radialSegments,
  1806. tubularSegments: tubularSegments,
  1807. p: p,
  1808. q: q,
  1809. sideOrientation: sideOrientation,
  1810. updatable: updatable
  1811. }
  1812. return MeshBuilder.CreateTorusKnot(name, options, scene);
  1813. }
  1814. /**
  1815. * Creates a line mesh.
  1816. * Please consider using the same method from the MeshBuilder class instead.
  1817. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1818. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1819. * The parameter `points` is an array successive Vector3.
  1820. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1821. * When updating an instance, remember that only point positions can change, not the number of points.
  1822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1823. */
  1824. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1825. var options = {
  1826. points: points,
  1827. updatable: updatable,
  1828. instance: instance
  1829. }
  1830. return MeshBuilder.CreateLines(name, options, scene);
  1831. }
  1832. /**
  1833. * Creates a dashed line mesh.
  1834. * Please consider using the same method from the MeshBuilder class instead.
  1835. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1836. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1837. * The parameter `points` is an array successive Vector3.
  1838. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  1839. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  1840. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  1841. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1842. * When updating an instance, remember that only point positions can change, not the number of points.
  1843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1844. */
  1845. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1846. var options = {
  1847. points: points,
  1848. dashSize: dashSize,
  1849. gapSize: gapSize,
  1850. dashNb: dashNb,
  1851. updatable: updatable,
  1852. instance: instance
  1853. }
  1854. return MeshBuilder.CreateDashedLines(name, options, scene);
  1855. }
  1856. /**
  1857. * Creates an extruded shape mesh.
  1858. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1859. * Please consider using the same method from the MeshBuilder class instead.
  1860. *
  1861. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1862. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1863. * extruded along the Z axis.
  1864. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1865. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  1866. * The parameter `scale` (float, default 1) is the value to scale the shape.
  1867. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1868. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1869. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1873. */
  1874. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1875. var options = {
  1876. shape: shape,
  1877. path: path,
  1878. scale: scale,
  1879. rotation: rotation,
  1880. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1881. sideOrientation: sideOrientation,
  1882. instance: instance,
  1883. updatable: updatable
  1884. }
  1885. return MeshBuilder.ExtrudeShape(name, options, scene);
  1886. }
  1887. /**
  1888. * Creates an custom extruded shape mesh.
  1889. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1890. * Please consider using the same method from the MeshBuilder class instead.
  1891. *
  1892. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1893. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1894. * extruded along the Z axis.
  1895. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1896. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1897. * and the distance of this point from the begining of the path :
  1898. * ```javascript
  1899. * var rotationFunction = function(i, distance) {
  1900. * // do things
  1901. * return rotationValue; }
  1902. * ```
  1903. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  1904. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1905. * and the distance of this point from the begining of the path :
  1906. * ```javascript
  1907. * var scaleFunction = function(i, distance) {
  1908. * // do things
  1909. * return scaleValue;}
  1910. * ```
  1911. * It must returns a float value that will be the scale value applied to the shape on each path point.
  1912. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  1913. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  1914. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1915. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1916. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1920. */
  1921. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1922. var options = {
  1923. shape: shape,
  1924. path: path,
  1925. scaleFunction: scaleFunction,
  1926. rotationFunction: rotationFunction,
  1927. ribbonCloseArray: ribbonCloseArray,
  1928. ribbonClosePath: ribbonClosePath,
  1929. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1930. sideOrientation: sideOrientation,
  1931. instance: instance,
  1932. updatable: updatable
  1933. }
  1934. return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  1935. }
  1936. /**
  1937. * Creates lathe mesh.
  1938. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  1939. * Please consider using the same method from the MeshBuilder class instead.
  1940. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  1941. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  1942. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  1943. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  1944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1947. */
  1948. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1949. var options = {
  1950. shape: shape,
  1951. radius: radius,
  1952. tessellation: tessellation,
  1953. sideOrientation: sideOrientation,
  1954. updatable: updatable
  1955. };
  1956. return MeshBuilder.CreateLathe(name, options, scene);
  1957. }
  1958. /**
  1959. * Creates a plane mesh.
  1960. * Please consider using the same method from the MeshBuilder class instead.
  1961. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  1962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1965. */
  1966. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1967. var options = {
  1968. size: size,
  1969. width: size,
  1970. height: size,
  1971. sideOrientation: sideOrientation,
  1972. updatable: updatable
  1973. }
  1974. return MeshBuilder.CreatePlane(name, options, scene);
  1975. }
  1976. /**
  1977. * Creates a ground mesh.
  1978. * Please consider using the same method from the MeshBuilder class instead.
  1979. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  1980. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  1981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1982. */
  1983. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1984. var options = {
  1985. width: width,
  1986. height: height,
  1987. subdivisions: subdivisions,
  1988. updatable: updatable
  1989. }
  1990. return MeshBuilder.CreateGround(name, options, scene);
  1991. }
  1992. /**
  1993. * Creates a tiled ground mesh.
  1994. * Please consider using the same method from the MeshBuilder class instead.
  1995. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  1996. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  1997. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  1998. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  1999. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  2000. * numbers of subdivisions on the ground width and height of each tile.
  2001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2002. */
  2003. 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 {
  2004. var options = {
  2005. xmin: xmin,
  2006. zmin: zmin,
  2007. xmax: xmax,
  2008. zmax: zmax,
  2009. subdivisions: subdivisions,
  2010. precision: precision,
  2011. updatable: updatable
  2012. }
  2013. return MeshBuilder.CreateTiledGround(name, options, scene);
  2014. }
  2015. /**
  2016. * Creates a ground mesh from a height map.
  2017. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  2018. * Please consider using the same method from the MeshBuilder class instead.
  2019. * The parameter `url` sets the URL of the height map image resource.
  2020. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  2021. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  2022. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  2023. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  2024. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  2025. * This function is passed the newly built mesh :
  2026. * ```javascript
  2027. * function(mesh) { // do things
  2028. * return; }
  2029. * ```
  2030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2031. */
  2032. 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 {
  2033. var options = {
  2034. width: width,
  2035. height: height,
  2036. subdivisions: subdivisions,
  2037. minHeight: minHeight,
  2038. maxHeight: maxHeight,
  2039. updatable: updatable,
  2040. onReady: onReady
  2041. };
  2042. return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  2043. }
  2044. /**
  2045. * Creates a tube mesh.
  2046. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  2047. * Please consider using the same method from the MeshBuilder class instead.
  2048. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  2049. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  2050. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  2051. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  2052. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  2053. * It must return a radius value (positive float) :
  2054. * ```javascript
  2055. * var radiusFunction = function(i, distance) {
  2056. * // do things
  2057. * return radius; }
  2058. * ```
  2059. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  2060. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  2061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2064. */
  2065. 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 {
  2066. var options = {
  2067. path: path,
  2068. radius: radius,
  2069. tessellation: tessellation,
  2070. radiusFunction: radiusFunction,
  2071. arc: 1,
  2072. cap: cap,
  2073. updatable: updatable,
  2074. sideOrientation: sideOrientation,
  2075. instance: instance
  2076. }
  2077. return MeshBuilder.CreateTube(name, options, scene);
  2078. }
  2079. /**
  2080. * Creates a polyhedron mesh.
  2081. * Please consider using the same method from the MeshBuilder class instead.
  2082. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  2083. * to choose the wanted type.
  2084. * The parameter `size` (positive float, default 1) sets the polygon size.
  2085. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  2086. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  2087. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  2088. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  2089. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  2090. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  2091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2094. */
  2095. 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 {
  2096. return MeshBuilder.CreatePolyhedron(name, options, scene);
  2097. }
  2098. /**
  2099. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  2100. * Please consider using the same method from the MeshBuilder class instead.
  2101. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  2102. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  2103. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  2104. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  2105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2108. */
  2109. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  2110. return MeshBuilder.CreateIcoSphere(name, options, scene);
  2111. }
  2112. /**
  2113. * Creates a decal mesh.
  2114. * Please consider using the same method from the MeshBuilder class instead.
  2115. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  2116. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  2117. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  2118. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  2119. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  2120. */
  2121. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  2122. var options = {
  2123. position: position,
  2124. normal: normal,
  2125. size: size,
  2126. angle: angle
  2127. }
  2128. return MeshBuilder.CreateDecal(name, sourceMesh, options);
  2129. }
  2130. // Skeletons
  2131. /**
  2132. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2133. */
  2134. public setPositionsForCPUSkinning(): Float32Array {
  2135. var source: number[] | Float32Array;
  2136. if (!this._sourcePositions) {
  2137. source = this.getVerticesData(VertexBuffer.PositionKind);
  2138. this._sourcePositions = new Float32Array(<any>source);
  2139. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  2140. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  2141. }
  2142. }
  2143. return this._sourcePositions;
  2144. }
  2145. /**
  2146. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2147. */
  2148. public setNormalsForCPUSkinning(): Float32Array {
  2149. var source: number[] | Float32Array;
  2150. if (!this._sourceNormals) {
  2151. source = this.getVerticesData(VertexBuffer.NormalKind);
  2152. this._sourceNormals = new Float32Array(<any>source);
  2153. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  2154. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  2155. }
  2156. }
  2157. return this._sourceNormals;
  2158. }
  2159. /**
  2160. * Update the vertex buffers by applying transformation from the bones
  2161. * @param {skeleton} skeleton to apply
  2162. */
  2163. public applySkeleton(skeleton: Skeleton): Mesh {
  2164. if (!this.geometry) {
  2165. return;
  2166. }
  2167. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  2168. return;
  2169. }
  2170. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  2171. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  2172. return this;
  2173. }
  2174. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  2175. return this;
  2176. }
  2177. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  2178. return this;
  2179. }
  2180. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  2181. return this;
  2182. }
  2183. if (!this._sourcePositions) {
  2184. var submeshes = this.subMeshes.slice();
  2185. this.setPositionsForCPUSkinning();
  2186. this.subMeshes = submeshes;
  2187. }
  2188. if (!this._sourceNormals) {
  2189. this.setNormalsForCPUSkinning();
  2190. }
  2191. // positionsData checks for not being Float32Array will only pass at most once
  2192. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  2193. if (!(positionsData instanceof Float32Array)) {
  2194. positionsData = new Float32Array(positionsData);
  2195. }
  2196. // normalsData checks for not being Float32Array will only pass at most once
  2197. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  2198. if (!(normalsData instanceof Float32Array)) {
  2199. normalsData = new Float32Array(normalsData);
  2200. }
  2201. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  2202. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  2203. var needExtras = this.numBoneInfluencers > 4;
  2204. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  2205. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  2206. var skeletonMatrices = skeleton.getTransformMatrices(this);
  2207. var tempVector3 = Vector3.Zero();
  2208. var finalMatrix = new Matrix();
  2209. var tempMatrix = new Matrix();
  2210. var matWeightIdx = 0;
  2211. var inf: number;
  2212. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  2213. var weight: number;
  2214. for (inf = 0; inf < 4; inf++) {
  2215. weight = matricesWeightsData[matWeightIdx + inf];
  2216. if (weight > 0) {
  2217. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2218. finalMatrix.addToSelf(tempMatrix);
  2219. } else break;
  2220. }
  2221. if (needExtras) {
  2222. for (inf = 0; inf < 4; inf++) {
  2223. weight = matricesWeightsExtraData[matWeightIdx + inf];
  2224. if (weight > 0) {
  2225. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2226. finalMatrix.addToSelf(tempMatrix);
  2227. } else break;
  2228. }
  2229. }
  2230. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  2231. tempVector3.toArray(positionsData, index);
  2232. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  2233. tempVector3.toArray(normalsData, index);
  2234. finalMatrix.reset();
  2235. }
  2236. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  2237. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  2238. return this;
  2239. }
  2240. // Tools
  2241. /**
  2242. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  2243. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  2244. */
  2245. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  2246. var minVector: Vector3 = null;
  2247. var maxVector: Vector3 = null;
  2248. meshes.forEach(function (mesh, index, array) {
  2249. var boundingBox = mesh.getBoundingInfo().boundingBox;
  2250. if (!minVector) {
  2251. minVector = boundingBox.minimumWorld;
  2252. maxVector = boundingBox.maximumWorld;
  2253. } else {
  2254. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  2255. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  2256. }
  2257. });
  2258. return {
  2259. min: minVector,
  2260. max: maxVector
  2261. };
  2262. }
  2263. /**
  2264. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  2265. */
  2266. public static Center(meshesOrMinMaxVector): Vector3 {
  2267. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  2268. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  2269. }
  2270. /**
  2271. * Merge the array of meshes into a single mesh for performance reasons.
  2272. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  2273. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  2274. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  2275. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  2276. */
  2277. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  2278. var index: number;
  2279. if (!allow32BitsIndices) {
  2280. var totalVertices = 0;
  2281. // Counting vertices
  2282. for (index = 0; index < meshes.length; index++) {
  2283. if (meshes[index]) {
  2284. totalVertices += meshes[index].getTotalVertices();
  2285. if (totalVertices > 65536) {
  2286. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  2287. return null;
  2288. }
  2289. }
  2290. }
  2291. }
  2292. // Merge
  2293. var vertexData: VertexData;
  2294. var otherVertexData: VertexData;
  2295. var source: Mesh;
  2296. for (index = 0; index < meshes.length; index++) {
  2297. if (meshes[index]) {
  2298. meshes[index].computeWorldMatrix(true);
  2299. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  2300. otherVertexData.transform(meshes[index].getWorldMatrix());
  2301. if (vertexData) {
  2302. vertexData.merge(otherVertexData);
  2303. } else {
  2304. vertexData = otherVertexData;
  2305. source = meshes[index];
  2306. }
  2307. }
  2308. }
  2309. if (!meshSubclass) {
  2310. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  2311. }
  2312. vertexData.applyToMesh(meshSubclass);
  2313. // Setting properties
  2314. meshSubclass.material = source.material;
  2315. meshSubclass.checkCollisions = source.checkCollisions;
  2316. // Cleaning
  2317. if (disposeSource) {
  2318. for (index = 0; index < meshes.length; index++) {
  2319. if (meshes[index]) {
  2320. meshes[index].dispose();
  2321. }
  2322. }
  2323. }
  2324. return meshSubclass;
  2325. }
  2326. }
  2327. }