babylon.mesh.ts 143 KB

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