babylon.mesh.ts 138 KB

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