babylon.mesh.ts 160 KB

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