babylon.glTFFileLoader.js 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Coordinate system mode that will be used when loading from the gltf file
  6. */
  7. var GLTFLoaderCoordinateSystemMode;
  8. (function (GLTFLoaderCoordinateSystemMode) {
  9. /**
  10. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  11. */
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  13. /**
  14. * Sets the useRightHandedSystem flag on the scene.
  15. */
  16. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  17. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  18. /**
  19. * Animation mode that determines which animations should be started when a file is loaded
  20. */
  21. var GLTFLoaderAnimationStartMode;
  22. (function (GLTFLoaderAnimationStartMode) {
  23. /**
  24. * No animation will start.
  25. */
  26. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  27. /**
  28. * The first animation will start.
  29. */
  30. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  31. /**
  32. * All animations will start.
  33. */
  34. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  35. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  36. /**
  37. * Loading state
  38. */
  39. var GLTFLoaderState;
  40. (function (GLTFLoaderState) {
  41. /**
  42. * The asset is loading.
  43. */
  44. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  45. /**
  46. * The asset is ready for rendering.
  47. */
  48. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  49. /**
  50. * The asset is completely loaded.
  51. */
  52. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  53. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  54. /** File loader to load gltf files into a babylon scene */
  55. var GLTFFileLoader = /** @class */ (function () {
  56. function GLTFFileLoader() {
  57. // #region Common options
  58. /**
  59. * Raised when the asset has been parsed.
  60. * The data.json property stores the glTF JSON.
  61. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  62. */
  63. this.onParsedObservable = new BABYLON.Observable();
  64. // #endregion
  65. // #region V2 options
  66. /**
  67. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED). Defaults to AUTO.
  68. * - AUTO - Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  69. * - FORCE_RIGHT_HANDED - Sets the useRightHandedSystem flag on the scene.
  70. */
  71. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72. /**
  73. * The animation start mode (NONE, FIRST, ALL). Defaults to FIRST.
  74. * - NONE - No animation will start.
  75. * - FIRST - The first animation will start.
  76. * - ALL - All animations will start.
  77. */
  78. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  79. /**
  80. * Set to true to compile materials before raising the success callback. Defaults to false.
  81. */
  82. this.compileMaterials = false;
  83. /**
  84. * Set to true to also compile materials with clip planes. Defaults to false.
  85. */
  86. this.useClipPlane = false;
  87. /**
  88. * Set to true to compile shadow generators before raising the success callback. Defaults to false.
  89. */
  90. this.compileShadowGenerators = false;
  91. /**
  92. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  93. */
  94. this.onMeshLoadedObservable = new BABYLON.Observable();
  95. /**
  96. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  97. */
  98. this.onTextureLoadedObservable = new BABYLON.Observable();
  99. /**
  100. * Raised when the loader creates a material after parsing the glTF properties of the material.
  101. */
  102. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103. /**
  104. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105. * For assets with LODs, raised when all of the LODs are complete.
  106. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107. */
  108. this.onCompleteObservable = new BABYLON.Observable();
  109. /**
  110. * Raised after the loader is disposed.
  111. */
  112. this.onDisposeObservable = new BABYLON.Observable();
  113. /**
  114. * Raised after a loader extension is created.
  115. * Set additional options for a loader extension in this event.
  116. */
  117. this.onExtensionLoadedObservable = new BABYLON.Observable();
  118. // #endregion
  119. this._loader = null;
  120. /**
  121. * Name of the loader ("gltf")
  122. */
  123. this.name = "gltf";
  124. /**
  125. * Supported file extensions of the loader (.gltf, .glb)
  126. */
  127. this.extensions = {
  128. ".gltf": { isBinary: false },
  129. ".glb": { isBinary: true }
  130. };
  131. }
  132. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  133. /** Raised when the asset has been parsed. */
  134. set: function (callback) {
  135. if (this._onParsedObserver) {
  136. this.onParsedObservable.remove(this._onParsedObserver);
  137. }
  138. this._onParsedObserver = this.onParsedObservable.add(callback);
  139. },
  140. enumerable: true,
  141. configurable: true
  142. });
  143. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  144. /**
  145. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh. (onMeshLoadedObservable is likely desired instead.)
  146. */
  147. set: function (callback) {
  148. if (this._onMeshLoadedObserver) {
  149. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  150. }
  151. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  157. /**
  158. * Method called when a texture has been loaded (onTextureLoadedObservable is likely desired instead.)
  159. */
  160. set: function (callback) {
  161. if (this._onTextureLoadedObserver) {
  162. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  163. }
  164. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  170. /**
  171. * Method when the loader creates a material after parsing the glTF properties of the material. (onMaterialLoadedObservable is likely desired instead.)
  172. */
  173. set: function (callback) {
  174. if (this._onMaterialLoadedObserver) {
  175. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  176. }
  177. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  183. /**
  184. * Raised when the asset is completely loaded, immediately before the loader is disposed. (onCompleteObservable is likely desired instead.)
  185. */
  186. set: function (callback) {
  187. if (this._onCompleteObserver) {
  188. this.onCompleteObservable.remove(this._onCompleteObserver);
  189. }
  190. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  196. /**
  197. * Raised after the loader is disposed. (onDisposeObservable is likely desired instead.)
  198. */
  199. set: function (callback) {
  200. if (this._onDisposeObserver) {
  201. this.onDisposeObservable.remove(this._onDisposeObserver);
  202. }
  203. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  209. /**
  210. * Raised after a loader extension is created. (onExtensionLoadedObservable is likely desired instead.)
  211. */
  212. set: function (callback) {
  213. if (this._onExtensionLoadedObserver) {
  214. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  215. }
  216. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  217. },
  218. enumerable: true,
  219. configurable: true
  220. });
  221. /**
  222. * Returns a promise that resolves when the asset is completely loaded.
  223. * @returns A promise that resolves when the asset is completely loaded.
  224. */
  225. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  226. var _this = this;
  227. return new Promise(function (resolve) {
  228. _this.onCompleteObservable.add(function () {
  229. resolve();
  230. }, undefined, undefined, undefined, true);
  231. });
  232. };
  233. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  234. /**
  235. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  236. */
  237. get: function () {
  238. return this._loader ? this._loader.state : null;
  239. },
  240. enumerable: true,
  241. configurable: true
  242. });
  243. /**
  244. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  245. */
  246. GLTFFileLoader.prototype.dispose = function () {
  247. if (this._loader) {
  248. this._loader.dispose();
  249. this._loader = null;
  250. }
  251. this.onMeshLoadedObservable.clear();
  252. this.onTextureLoadedObservable.clear();
  253. this.onMaterialLoadedObservable.clear();
  254. this.onDisposeObservable.notifyObservers(this);
  255. this.onDisposeObservable.clear();
  256. };
  257. /**
  258. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  259. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  260. * @param scene the scene the meshes should be added to
  261. * @param data gltf data containing information of the meshes in a loaded file
  262. * @param rootUrl root url to load from
  263. * @param onProgress event that fires when loading progress has occured
  264. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  265. */
  266. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  267. var _this = this;
  268. return Promise.resolve().then(function () {
  269. var loaderData = _this._parse(data);
  270. _this._loader = _this._getLoader(loaderData);
  271. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  272. });
  273. };
  274. /**
  275. * Imports all objects from a loaded gltf file and adds them to the scene
  276. * @param scene the scene the objects should be added to
  277. * @param data gltf data containing information of the meshes in a loaded file
  278. * @param rootUrl root url to load from
  279. * @param onProgress event that fires when loading progress has occured
  280. * @returns a promise which completes when objects have been loaded to the scene
  281. */
  282. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  283. var _this = this;
  284. return Promise.resolve().then(function () {
  285. var loaderData = _this._parse(data);
  286. _this._loader = _this._getLoader(loaderData);
  287. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  288. });
  289. };
  290. /**
  291. * Load into an asset container.
  292. * @param scene The scene to load into
  293. * @param data The data to import
  294. * @param rootUrl The root url for scene and resources
  295. * @param onProgress The callback when the load progresses
  296. * @returns The loaded asset container
  297. */
  298. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  299. var _this = this;
  300. return Promise.resolve().then(function () {
  301. var loaderData = _this._parse(data);
  302. _this._loader = _this._getLoader(loaderData);
  303. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  304. var container = new BABYLON.AssetContainer(scene);
  305. Array.prototype.push.apply(container.meshes, result.meshes);
  306. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  307. Array.prototype.push.apply(container.skeletons, result.skeletons);
  308. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  309. container.removeAllFromScene();
  310. return container;
  311. });
  312. });
  313. };
  314. /**
  315. * If the data string can be loaded directly
  316. * @param data string contianing the file data
  317. * @returns if the data can be loaded directly
  318. */
  319. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  320. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  321. };
  322. /**
  323. * Instantiates a gltf file loader plugin
  324. * @returns the created plugin
  325. */
  326. GLTFFileLoader.prototype.createPlugin = function () {
  327. return new GLTFFileLoader();
  328. };
  329. GLTFFileLoader.prototype._parse = function (data) {
  330. var parsedData;
  331. if (data instanceof ArrayBuffer) {
  332. parsedData = GLTFFileLoader._parseBinary(data);
  333. }
  334. else {
  335. parsedData = {
  336. json: JSON.parse(data),
  337. bin: null
  338. };
  339. }
  340. this.onParsedObservable.notifyObservers(parsedData);
  341. this.onParsedObservable.clear();
  342. return parsedData;
  343. };
  344. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  345. var _this = this;
  346. var loaderVersion = { major: 2, minor: 0 };
  347. var asset = loaderData.json.asset || {};
  348. var version = GLTFFileLoader._parseVersion(asset.version);
  349. if (!version) {
  350. throw new Error("Invalid version: " + asset.version);
  351. }
  352. if (asset.minVersion !== undefined) {
  353. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  354. if (!minVersion) {
  355. throw new Error("Invalid minimum version: " + asset.minVersion);
  356. }
  357. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  358. throw new Error("Incompatible minimum version: " + asset.minVersion);
  359. }
  360. }
  361. var createLoaders = {
  362. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  363. 2: GLTFFileLoader.CreateGLTFLoaderV2
  364. };
  365. var createLoader = createLoaders[version.major];
  366. if (!createLoader) {
  367. throw new Error("Unsupported version: " + asset.version);
  368. }
  369. var loader = createLoader();
  370. loader.coordinateSystemMode = this.coordinateSystemMode;
  371. loader.animationStartMode = this.animationStartMode;
  372. loader.compileMaterials = this.compileMaterials;
  373. loader.useClipPlane = this.useClipPlane;
  374. loader.compileShadowGenerators = this.compileShadowGenerators;
  375. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  376. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  377. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  378. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  379. loader.onCompleteObservable.add(function () {
  380. _this.onMeshLoadedObservable.clear();
  381. _this.onTextureLoadedObservable.clear();
  382. _this.onMaterialLoadedObservable.clear();
  383. _this.onCompleteObservable.notifyObservers(_this);
  384. _this.onCompleteObservable.clear();
  385. });
  386. return loader;
  387. };
  388. GLTFFileLoader._parseBinary = function (data) {
  389. var Binary = {
  390. Magic: 0x46546C67
  391. };
  392. var binaryReader = new BinaryReader(data);
  393. var magic = binaryReader.readUint32();
  394. if (magic !== Binary.Magic) {
  395. throw new Error("Unexpected magic: " + magic);
  396. }
  397. var version = binaryReader.readUint32();
  398. switch (version) {
  399. case 1: return GLTFFileLoader._parseV1(binaryReader);
  400. case 2: return GLTFFileLoader._parseV2(binaryReader);
  401. }
  402. throw new Error("Unsupported version: " + version);
  403. };
  404. GLTFFileLoader._parseV1 = function (binaryReader) {
  405. var ContentFormat = {
  406. JSON: 0
  407. };
  408. var length = binaryReader.readUint32();
  409. if (length != binaryReader.getLength()) {
  410. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  411. }
  412. var contentLength = binaryReader.readUint32();
  413. var contentFormat = binaryReader.readUint32();
  414. var content;
  415. switch (contentFormat) {
  416. case ContentFormat.JSON: {
  417. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  418. break;
  419. }
  420. default: {
  421. throw new Error("Unexpected content format: " + contentFormat);
  422. }
  423. }
  424. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  425. var body = binaryReader.readUint8Array(bytesRemaining);
  426. return {
  427. json: content,
  428. bin: body
  429. };
  430. };
  431. GLTFFileLoader._parseV2 = function (binaryReader) {
  432. var ChunkFormat = {
  433. JSON: 0x4E4F534A,
  434. BIN: 0x004E4942
  435. };
  436. var length = binaryReader.readUint32();
  437. if (length !== binaryReader.getLength()) {
  438. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  439. }
  440. // JSON chunk
  441. var chunkLength = binaryReader.readUint32();
  442. var chunkFormat = binaryReader.readUint32();
  443. if (chunkFormat !== ChunkFormat.JSON) {
  444. throw new Error("First chunk format is not JSON");
  445. }
  446. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  447. // Look for BIN chunk
  448. var bin = null;
  449. while (binaryReader.getPosition() < binaryReader.getLength()) {
  450. var chunkLength_1 = binaryReader.readUint32();
  451. var chunkFormat_1 = binaryReader.readUint32();
  452. switch (chunkFormat_1) {
  453. case ChunkFormat.JSON: {
  454. throw new Error("Unexpected JSON chunk");
  455. }
  456. case ChunkFormat.BIN: {
  457. bin = binaryReader.readUint8Array(chunkLength_1);
  458. break;
  459. }
  460. default: {
  461. // ignore unrecognized chunkFormat
  462. binaryReader.skipBytes(chunkLength_1);
  463. break;
  464. }
  465. }
  466. }
  467. return {
  468. json: json,
  469. bin: bin
  470. };
  471. };
  472. GLTFFileLoader._parseVersion = function (version) {
  473. if (version === "1.0" || version === "1.0.1") {
  474. return {
  475. major: 1,
  476. minor: 0
  477. };
  478. }
  479. var match = (version + "").match(/^(\d+)\.(\d+)/);
  480. if (!match) {
  481. return null;
  482. }
  483. return {
  484. major: parseInt(match[1]),
  485. minor: parseInt(match[2])
  486. };
  487. };
  488. GLTFFileLoader._compareVersion = function (a, b) {
  489. if (a.major > b.major)
  490. return 1;
  491. if (a.major < b.major)
  492. return -1;
  493. if (a.minor > b.minor)
  494. return 1;
  495. if (a.minor < b.minor)
  496. return -1;
  497. return 0;
  498. };
  499. GLTFFileLoader._decodeBufferToText = function (buffer) {
  500. var result = "";
  501. var length = buffer.byteLength;
  502. for (var i = 0; i < length; i++) {
  503. result += String.fromCharCode(buffer[i]);
  504. }
  505. return result;
  506. };
  507. // #endregion
  508. // #region V1 options
  509. /**
  510. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. Defaults to true.
  511. */
  512. GLTFFileLoader.IncrementalLoading = true;
  513. /**
  514. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates
  515. */
  516. GLTFFileLoader.HomogeneousCoordinates = false;
  517. return GLTFFileLoader;
  518. }());
  519. BABYLON.GLTFFileLoader = GLTFFileLoader;
  520. var BinaryReader = /** @class */ (function () {
  521. function BinaryReader(arrayBuffer) {
  522. this._arrayBuffer = arrayBuffer;
  523. this._dataView = new DataView(arrayBuffer);
  524. this._byteOffset = 0;
  525. }
  526. BinaryReader.prototype.getPosition = function () {
  527. return this._byteOffset;
  528. };
  529. BinaryReader.prototype.getLength = function () {
  530. return this._arrayBuffer.byteLength;
  531. };
  532. BinaryReader.prototype.readUint32 = function () {
  533. var value = this._dataView.getUint32(this._byteOffset, true);
  534. this._byteOffset += 4;
  535. return value;
  536. };
  537. BinaryReader.prototype.readUint8Array = function (length) {
  538. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  539. this._byteOffset += length;
  540. return value;
  541. };
  542. BinaryReader.prototype.skipBytes = function (length) {
  543. this._byteOffset += length;
  544. };
  545. return BinaryReader;
  546. }());
  547. if (BABYLON.SceneLoader) {
  548. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  549. }
  550. })(BABYLON || (BABYLON = {}));
  551. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  552. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  553. var BABYLON;
  554. (function (BABYLON) {
  555. var GLTF1;
  556. (function (GLTF1) {
  557. /**
  558. * Enums
  559. */
  560. var EComponentType;
  561. (function (EComponentType) {
  562. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  563. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  564. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  565. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  566. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  567. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  568. var EShaderType;
  569. (function (EShaderType) {
  570. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  571. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  572. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  573. var EParameterType;
  574. (function (EParameterType) {
  575. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  576. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  577. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  578. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  579. EParameterType[EParameterType["INT"] = 5124] = "INT";
  580. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  581. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  582. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  583. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  584. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  585. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  586. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  587. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  588. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  589. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  590. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  591. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  592. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  593. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  594. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  595. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  596. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  597. var ETextureWrapMode;
  598. (function (ETextureWrapMode) {
  599. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  600. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  601. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  602. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  603. var ETextureFilterType;
  604. (function (ETextureFilterType) {
  605. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  606. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  607. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  608. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  609. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  610. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  611. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  612. var ETextureFormat;
  613. (function (ETextureFormat) {
  614. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  615. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  616. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  617. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  618. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  619. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  620. var ECullingType;
  621. (function (ECullingType) {
  622. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  623. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  624. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  625. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  626. var EBlendingFunction;
  627. (function (EBlendingFunction) {
  628. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  629. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  630. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  631. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  632. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  633. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  634. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  635. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  636. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  637. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  638. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  639. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  640. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  641. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  642. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  643. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  644. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  645. })(BABYLON || (BABYLON = {}));
  646. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  647. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  648. var BABYLON;
  649. (function (BABYLON) {
  650. var GLTF1;
  651. (function (GLTF1) {
  652. /**
  653. * Tokenizer. Used for shaders compatibility
  654. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  655. */
  656. var ETokenType;
  657. (function (ETokenType) {
  658. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  659. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  660. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  661. })(ETokenType || (ETokenType = {}));
  662. var Tokenizer = /** @class */ (function () {
  663. function Tokenizer(toParse) {
  664. this._pos = 0;
  665. this.currentToken = ETokenType.UNKNOWN;
  666. this.currentIdentifier = "";
  667. this.currentString = "";
  668. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  669. this._toParse = toParse;
  670. this._maxPos = toParse.length;
  671. }
  672. Tokenizer.prototype.getNextToken = function () {
  673. if (this.isEnd())
  674. return ETokenType.END_OF_INPUT;
  675. this.currentString = this.read();
  676. this.currentToken = ETokenType.UNKNOWN;
  677. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  678. this.currentToken = ETokenType.IDENTIFIER;
  679. this.currentIdentifier = this.currentString;
  680. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  681. this.currentIdentifier += this.currentString;
  682. this.forward();
  683. }
  684. }
  685. return this.currentToken;
  686. };
  687. Tokenizer.prototype.peek = function () {
  688. return this._toParse[this._pos];
  689. };
  690. Tokenizer.prototype.read = function () {
  691. return this._toParse[this._pos++];
  692. };
  693. Tokenizer.prototype.forward = function () {
  694. this._pos++;
  695. };
  696. Tokenizer.prototype.isEnd = function () {
  697. return this._pos >= this._maxPos;
  698. };
  699. return Tokenizer;
  700. }());
  701. /**
  702. * Values
  703. */
  704. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  705. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  706. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  707. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  708. /**
  709. * Parse
  710. */
  711. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  712. for (var buf in parsedBuffers) {
  713. var parsedBuffer = parsedBuffers[buf];
  714. gltfRuntime.buffers[buf] = parsedBuffer;
  715. gltfRuntime.buffersCount++;
  716. }
  717. };
  718. var parseShaders = function (parsedShaders, gltfRuntime) {
  719. for (var sha in parsedShaders) {
  720. var parsedShader = parsedShaders[sha];
  721. gltfRuntime.shaders[sha] = parsedShader;
  722. gltfRuntime.shaderscount++;
  723. }
  724. };
  725. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  726. for (var object in parsedObjects) {
  727. var parsedObject = parsedObjects[object];
  728. gltfRuntime[runtimeProperty][object] = parsedObject;
  729. }
  730. };
  731. /**
  732. * Utils
  733. */
  734. var normalizeUVs = function (buffer) {
  735. if (!buffer) {
  736. return;
  737. }
  738. for (var i = 0; i < buffer.length / 2; i++) {
  739. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  740. }
  741. };
  742. var getAttribute = function (attributeParameter) {
  743. if (attributeParameter.semantic === "NORMAL") {
  744. return "normal";
  745. }
  746. else if (attributeParameter.semantic === "POSITION") {
  747. return "position";
  748. }
  749. else if (attributeParameter.semantic === "JOINT") {
  750. return "matricesIndices";
  751. }
  752. else if (attributeParameter.semantic === "WEIGHT") {
  753. return "matricesWeights";
  754. }
  755. else if (attributeParameter.semantic === "COLOR") {
  756. return "color";
  757. }
  758. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  759. var channel = Number(attributeParameter.semantic.split("_")[1]);
  760. return "uv" + (channel === 0 ? "" : channel + 1);
  761. }
  762. return null;
  763. };
  764. /**
  765. * Loads and creates animations
  766. */
  767. var loadAnimations = function (gltfRuntime) {
  768. for (var anim in gltfRuntime.animations) {
  769. var animation = gltfRuntime.animations[anim];
  770. if (!animation.channels || !animation.samplers) {
  771. continue;
  772. }
  773. var lastAnimation = null;
  774. for (var i = 0; i < animation.channels.length; i++) {
  775. // Get parameters and load buffers
  776. var channel = animation.channels[i];
  777. var sampler = animation.samplers[channel.sampler];
  778. if (!sampler) {
  779. continue;
  780. }
  781. var inputData = null;
  782. var outputData = null;
  783. if (animation.parameters) {
  784. inputData = animation.parameters[sampler.input];
  785. outputData = animation.parameters[sampler.output];
  786. }
  787. else {
  788. inputData = sampler.input;
  789. outputData = sampler.output;
  790. }
  791. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  792. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  793. var targetID = channel.target.id;
  794. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  795. if (targetNode === null) {
  796. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  797. }
  798. if (targetNode === null) {
  799. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  800. continue;
  801. }
  802. var isBone = targetNode instanceof BABYLON.Bone;
  803. // Get target path (position, rotation or scaling)
  804. var targetPath = channel.target.path;
  805. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  806. if (targetPathIndex !== -1) {
  807. targetPath = babylonAnimationPaths[targetPathIndex];
  808. }
  809. // Determine animation type
  810. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  811. if (!isBone) {
  812. if (targetPath === "rotationQuaternion") {
  813. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  814. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  815. }
  816. else {
  817. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  818. }
  819. }
  820. // Create animation and key frames
  821. var babylonAnimation = null;
  822. var keys = [];
  823. var arrayOffset = 0;
  824. var modifyKey = false;
  825. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  826. babylonAnimation = lastAnimation;
  827. modifyKey = true;
  828. }
  829. if (!modifyKey) {
  830. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  831. }
  832. // For each frame
  833. for (var j = 0; j < bufferInput.length; j++) {
  834. var value = null;
  835. if (targetPath === "rotationQuaternion") { // VEC4
  836. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  837. arrayOffset += 4;
  838. }
  839. else { // Position and scaling are VEC3
  840. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  841. arrayOffset += 3;
  842. }
  843. if (isBone) {
  844. var bone = targetNode;
  845. var translation = BABYLON.Vector3.Zero();
  846. var rotationQuaternion = new BABYLON.Quaternion();
  847. var scaling = BABYLON.Vector3.Zero();
  848. // Warning on decompose
  849. var mat = bone.getBaseMatrix();
  850. if (modifyKey && lastAnimation) {
  851. mat = lastAnimation.getKeys()[j].value;
  852. }
  853. mat.decompose(scaling, rotationQuaternion, translation);
  854. if (targetPath === "position") {
  855. translation = value;
  856. }
  857. else if (targetPath === "rotationQuaternion") {
  858. rotationQuaternion = value;
  859. }
  860. else {
  861. scaling = value;
  862. }
  863. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  864. }
  865. if (!modifyKey) {
  866. keys.push({
  867. frame: bufferInput[j],
  868. value: value
  869. });
  870. }
  871. else if (lastAnimation) {
  872. lastAnimation.getKeys()[j].value = value;
  873. }
  874. }
  875. // Finish
  876. if (!modifyKey && babylonAnimation) {
  877. babylonAnimation.setKeys(keys);
  878. targetNode.animations.push(babylonAnimation);
  879. }
  880. lastAnimation = babylonAnimation;
  881. gltfRuntime.scene.stopAnimation(targetNode);
  882. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  883. }
  884. }
  885. };
  886. /**
  887. * Returns the bones transformation matrix
  888. */
  889. var configureBoneTransformation = function (node) {
  890. var mat = null;
  891. if (node.translation || node.rotation || node.scale) {
  892. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  893. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  894. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  895. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  896. }
  897. else {
  898. mat = BABYLON.Matrix.FromArray(node.matrix);
  899. }
  900. return mat;
  901. };
  902. /**
  903. * Returns the parent bone
  904. */
  905. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  906. // Try to find
  907. for (var i = 0; i < newSkeleton.bones.length; i++) {
  908. if (newSkeleton.bones[i].name === jointName) {
  909. return newSkeleton.bones[i];
  910. }
  911. }
  912. // Not found, search in gltf nodes
  913. var nodes = gltfRuntime.nodes;
  914. for (var nde in nodes) {
  915. var node = nodes[nde];
  916. if (!node.jointName) {
  917. continue;
  918. }
  919. var children = node.children;
  920. for (var i = 0; i < children.length; i++) {
  921. var child = gltfRuntime.nodes[children[i]];
  922. if (!child.jointName) {
  923. continue;
  924. }
  925. if (child.jointName === jointName) {
  926. var mat = configureBoneTransformation(node);
  927. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  928. bone.id = nde;
  929. return bone;
  930. }
  931. }
  932. }
  933. return null;
  934. };
  935. /**
  936. * Returns the appropriate root node
  937. */
  938. var getNodeToRoot = function (nodesToRoot, id) {
  939. for (var i = 0; i < nodesToRoot.length; i++) {
  940. var nodeToRoot = nodesToRoot[i];
  941. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  942. var child = nodeToRoot.node.children[j];
  943. if (child === id) {
  944. return nodeToRoot.bone;
  945. }
  946. }
  947. }
  948. return null;
  949. };
  950. /**
  951. * Returns the node with the joint name
  952. */
  953. var getJointNode = function (gltfRuntime, jointName) {
  954. var nodes = gltfRuntime.nodes;
  955. var node = nodes[jointName];
  956. if (node) {
  957. return {
  958. node: node,
  959. id: jointName
  960. };
  961. }
  962. for (var nde in nodes) {
  963. node = nodes[nde];
  964. if (node.jointName === jointName) {
  965. return {
  966. node: node,
  967. id: nde
  968. };
  969. }
  970. }
  971. return null;
  972. };
  973. /**
  974. * Checks if a nodes is in joints
  975. */
  976. var nodeIsInJoints = function (skins, id) {
  977. for (var i = 0; i < skins.jointNames.length; i++) {
  978. if (skins.jointNames[i] === id) {
  979. return true;
  980. }
  981. }
  982. return false;
  983. };
  984. /**
  985. * Fills the nodes to root for bones and builds hierarchy
  986. */
  987. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  988. // Creates nodes for root
  989. for (var nde in gltfRuntime.nodes) {
  990. var node = gltfRuntime.nodes[nde];
  991. var id = nde;
  992. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  993. continue;
  994. }
  995. // Create node to root bone
  996. var mat = configureBoneTransformation(node);
  997. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  998. bone.id = id;
  999. nodesToRoot.push({ bone: bone, node: node, id: id });
  1000. }
  1001. // Parenting
  1002. for (var i = 0; i < nodesToRoot.length; i++) {
  1003. var nodeToRoot = nodesToRoot[i];
  1004. var children = nodeToRoot.node.children;
  1005. for (var j = 0; j < children.length; j++) {
  1006. var child = null;
  1007. for (var k = 0; k < nodesToRoot.length; k++) {
  1008. if (nodesToRoot[k].id === children[j]) {
  1009. child = nodesToRoot[k];
  1010. break;
  1011. }
  1012. }
  1013. if (child) {
  1014. child.bone._parent = nodeToRoot.bone;
  1015. nodeToRoot.bone.children.push(child.bone);
  1016. }
  1017. }
  1018. }
  1019. };
  1020. /**
  1021. * Imports a skeleton
  1022. */
  1023. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1024. if (!newSkeleton) {
  1025. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1026. }
  1027. if (!skins.babylonSkeleton) {
  1028. return newSkeleton;
  1029. }
  1030. // Find the root bones
  1031. var nodesToRoot = [];
  1032. var nodesToRootToAdd = [];
  1033. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1034. newSkeleton.bones = [];
  1035. // Joints
  1036. for (var i = 0; i < skins.jointNames.length; i++) {
  1037. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1038. if (!jointNode) {
  1039. continue;
  1040. }
  1041. var node = jointNode.node;
  1042. if (!node) {
  1043. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1044. continue;
  1045. }
  1046. var id = jointNode.id;
  1047. // Optimize, if the bone already exists...
  1048. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1049. if (existingBone) {
  1050. newSkeleton.bones.push(existingBone);
  1051. continue;
  1052. }
  1053. // Search for parent bone
  1054. var foundBone = false;
  1055. var parentBone = null;
  1056. for (var j = 0; j < i; j++) {
  1057. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1058. if (!jointNode_1) {
  1059. continue;
  1060. }
  1061. var joint = jointNode_1.node;
  1062. if (!joint) {
  1063. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1064. continue;
  1065. }
  1066. var children = joint.children;
  1067. if (!children) {
  1068. continue;
  1069. }
  1070. foundBone = false;
  1071. for (var k = 0; k < children.length; k++) {
  1072. if (children[k] === id) {
  1073. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1074. foundBone = true;
  1075. break;
  1076. }
  1077. }
  1078. if (foundBone) {
  1079. break;
  1080. }
  1081. }
  1082. // Create bone
  1083. var mat = configureBoneTransformation(node);
  1084. if (!parentBone && nodesToRoot.length > 0) {
  1085. parentBone = getNodeToRoot(nodesToRoot, id);
  1086. if (parentBone) {
  1087. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1088. nodesToRootToAdd.push(parentBone);
  1089. }
  1090. }
  1091. }
  1092. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1093. bone.id = id;
  1094. }
  1095. // Polish
  1096. var bones = newSkeleton.bones;
  1097. newSkeleton.bones = [];
  1098. for (var i = 0; i < skins.jointNames.length; i++) {
  1099. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1100. if (!jointNode) {
  1101. continue;
  1102. }
  1103. for (var j = 0; j < bones.length; j++) {
  1104. if (bones[j].id === jointNode.id) {
  1105. newSkeleton.bones.push(bones[j]);
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. newSkeleton.prepare();
  1111. // Finish
  1112. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1113. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1114. }
  1115. return newSkeleton;
  1116. };
  1117. /**
  1118. * Imports a mesh and its geometries
  1119. */
  1120. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1121. if (!newMesh) {
  1122. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1123. newMesh.id = id;
  1124. }
  1125. if (!node.babylonNode) {
  1126. return newMesh;
  1127. }
  1128. var subMaterials = [];
  1129. var vertexData = null;
  1130. var verticesStarts = new Array();
  1131. var verticesCounts = new Array();
  1132. var indexStarts = new Array();
  1133. var indexCounts = new Array();
  1134. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1135. var meshID = meshes[meshIndex];
  1136. var mesh = gltfRuntime.meshes[meshID];
  1137. if (!mesh) {
  1138. continue;
  1139. }
  1140. // Positions, normals and UVs
  1141. for (var i = 0; i < mesh.primitives.length; i++) {
  1142. // Temporary vertex data
  1143. var tempVertexData = new BABYLON.VertexData();
  1144. var primitive = mesh.primitives[i];
  1145. if (primitive.mode !== 4) {
  1146. // continue;
  1147. }
  1148. var attributes = primitive.attributes;
  1149. var accessor = null;
  1150. var buffer = null;
  1151. // Set positions, normal and uvs
  1152. for (var semantic in attributes) {
  1153. // Link accessor and buffer view
  1154. accessor = gltfRuntime.accessors[attributes[semantic]];
  1155. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1156. if (semantic === "NORMAL") {
  1157. tempVertexData.normals = new Float32Array(buffer.length);
  1158. tempVertexData.normals.set(buffer);
  1159. }
  1160. else if (semantic === "POSITION") {
  1161. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1162. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1163. for (var j = 0; j < buffer.length; j += 4) {
  1164. tempVertexData.positions[j] = buffer[j];
  1165. tempVertexData.positions[j + 1] = buffer[j + 1];
  1166. tempVertexData.positions[j + 2] = buffer[j + 2];
  1167. }
  1168. }
  1169. else {
  1170. tempVertexData.positions = new Float32Array(buffer.length);
  1171. tempVertexData.positions.set(buffer);
  1172. }
  1173. verticesCounts.push(tempVertexData.positions.length);
  1174. }
  1175. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1176. var channel = Number(semantic.split("_")[1]);
  1177. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1178. var uvs = new Float32Array(buffer.length);
  1179. uvs.set(buffer);
  1180. normalizeUVs(uvs);
  1181. tempVertexData.set(uvs, uvKind);
  1182. }
  1183. else if (semantic === "JOINT") {
  1184. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1185. tempVertexData.matricesIndices.set(buffer);
  1186. }
  1187. else if (semantic === "WEIGHT") {
  1188. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1189. tempVertexData.matricesWeights.set(buffer);
  1190. }
  1191. else if (semantic === "COLOR") {
  1192. tempVertexData.colors = new Float32Array(buffer.length);
  1193. tempVertexData.colors.set(buffer);
  1194. }
  1195. }
  1196. // Indices
  1197. accessor = gltfRuntime.accessors[primitive.indices];
  1198. if (accessor) {
  1199. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1200. tempVertexData.indices = new Int32Array(buffer.length);
  1201. tempVertexData.indices.set(buffer);
  1202. indexCounts.push(tempVertexData.indices.length);
  1203. }
  1204. else {
  1205. // Set indices on the fly
  1206. var indices = [];
  1207. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1208. indices.push(j);
  1209. }
  1210. tempVertexData.indices = new Int32Array(indices);
  1211. indexCounts.push(tempVertexData.indices.length);
  1212. }
  1213. if (!vertexData) {
  1214. vertexData = tempVertexData;
  1215. }
  1216. else {
  1217. vertexData.merge(tempVertexData);
  1218. }
  1219. // Sub material
  1220. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1221. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1222. // Update vertices start and index start
  1223. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1224. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1225. }
  1226. }
  1227. var material;
  1228. if (subMaterials.length > 1) {
  1229. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1230. material.subMaterials = subMaterials;
  1231. }
  1232. else {
  1233. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1234. }
  1235. if (subMaterials.length === 1) {
  1236. material = subMaterials[0];
  1237. }
  1238. if (!newMesh.material) {
  1239. newMesh.material = material;
  1240. }
  1241. // Apply geometry
  1242. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1243. newMesh.computeWorldMatrix(true);
  1244. // Apply submeshes
  1245. newMesh.subMeshes = [];
  1246. var index = 0;
  1247. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1248. var meshID = meshes[meshIndex];
  1249. var mesh = gltfRuntime.meshes[meshID];
  1250. if (!mesh) {
  1251. continue;
  1252. }
  1253. for (var i = 0; i < mesh.primitives.length; i++) {
  1254. if (mesh.primitives[i].mode !== 4) {
  1255. //continue;
  1256. }
  1257. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1258. index++;
  1259. }
  1260. }
  1261. // Finish
  1262. return newMesh;
  1263. };
  1264. /**
  1265. * Configure node transformation from position, rotation and scaling
  1266. */
  1267. var configureNode = function (newNode, position, rotation, scaling) {
  1268. if (newNode.position) {
  1269. newNode.position = position;
  1270. }
  1271. if (newNode.rotationQuaternion || newNode.rotation) {
  1272. newNode.rotationQuaternion = rotation;
  1273. }
  1274. if (newNode.scaling) {
  1275. newNode.scaling = scaling;
  1276. }
  1277. };
  1278. /**
  1279. * Configures node from transformation matrix
  1280. */
  1281. var configureNodeFromMatrix = function (newNode, node, parent) {
  1282. if (node.matrix) {
  1283. var position = new BABYLON.Vector3(0, 0, 0);
  1284. var rotation = new BABYLON.Quaternion();
  1285. var scaling = new BABYLON.Vector3(0, 0, 0);
  1286. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1287. mat.decompose(scaling, rotation, position);
  1288. configureNode(newNode, position, rotation, scaling);
  1289. }
  1290. else if (node.translation && node.rotation && node.scale) {
  1291. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1292. }
  1293. newNode.computeWorldMatrix(true);
  1294. };
  1295. /**
  1296. * Imports a node
  1297. */
  1298. var importNode = function (gltfRuntime, node, id, parent) {
  1299. var lastNode = null;
  1300. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1301. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1302. return null;
  1303. }
  1304. }
  1305. // Meshes
  1306. if (node.skin) {
  1307. if (node.meshes) {
  1308. var skin = gltfRuntime.skins[node.skin];
  1309. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1310. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1311. if (newMesh.skeleton === null) {
  1312. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1313. if (!skin.babylonSkeleton) {
  1314. skin.babylonSkeleton = newMesh.skeleton;
  1315. }
  1316. }
  1317. lastNode = newMesh;
  1318. }
  1319. }
  1320. else if (node.meshes) {
  1321. /**
  1322. * Improve meshes property
  1323. */
  1324. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1325. lastNode = newMesh;
  1326. }
  1327. // Lights
  1328. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1329. var light = gltfRuntime.lights[node.light];
  1330. if (light) {
  1331. if (light.type === "ambient") {
  1332. var ambienLight = light[light.type];
  1333. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1334. hemiLight.name = node.name || "";
  1335. if (ambienLight.color) {
  1336. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1337. }
  1338. lastNode = hemiLight;
  1339. }
  1340. else if (light.type === "directional") {
  1341. var directionalLight = light[light.type];
  1342. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1343. dirLight.name = node.name || "";
  1344. if (directionalLight.color) {
  1345. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1346. }
  1347. lastNode = dirLight;
  1348. }
  1349. else if (light.type === "point") {
  1350. var pointLight = light[light.type];
  1351. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1352. ptLight.name = node.name || "";
  1353. if (pointLight.color) {
  1354. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1355. }
  1356. lastNode = ptLight;
  1357. }
  1358. else if (light.type === "spot") {
  1359. var spotLight = light[light.type];
  1360. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1361. spLight.name = node.name || "";
  1362. if (spotLight.color) {
  1363. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1364. }
  1365. if (spotLight.fallOfAngle) {
  1366. spLight.angle = spotLight.fallOfAngle;
  1367. }
  1368. if (spotLight.fallOffExponent) {
  1369. spLight.exponent = spotLight.fallOffExponent;
  1370. }
  1371. lastNode = spLight;
  1372. }
  1373. }
  1374. }
  1375. // Cameras
  1376. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1377. var camera = gltfRuntime.cameras[node.camera];
  1378. if (camera) {
  1379. if (camera.type === "orthographic") {
  1380. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1381. orthoCamera.name = node.name || "";
  1382. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1383. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1384. lastNode = orthoCamera;
  1385. }
  1386. else if (camera.type === "perspective") {
  1387. var perspectiveCamera = camera[camera.type];
  1388. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1389. persCamera.name = node.name || "";
  1390. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1391. if (!perspectiveCamera.aspectRatio) {
  1392. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1393. }
  1394. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1395. persCamera.maxZ = perspectiveCamera.zfar;
  1396. persCamera.minZ = perspectiveCamera.znear;
  1397. }
  1398. lastNode = persCamera;
  1399. }
  1400. }
  1401. }
  1402. // Empty node
  1403. if (!node.jointName) {
  1404. if (node.babylonNode) {
  1405. return node.babylonNode;
  1406. }
  1407. else if (lastNode === null) {
  1408. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1409. node.babylonNode = dummy;
  1410. lastNode = dummy;
  1411. }
  1412. }
  1413. if (lastNode !== null) {
  1414. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1415. configureNodeFromMatrix(lastNode, node, parent);
  1416. }
  1417. else {
  1418. var translation = node.translation || [0, 0, 0];
  1419. var rotation = node.rotation || [0, 0, 0, 1];
  1420. var scale = node.scale || [1, 1, 1];
  1421. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1422. }
  1423. lastNode.updateCache(true);
  1424. node.babylonNode = lastNode;
  1425. }
  1426. return lastNode;
  1427. };
  1428. /**
  1429. * Traverses nodes and creates them
  1430. */
  1431. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1432. if (meshIncluded === void 0) { meshIncluded = false; }
  1433. var node = gltfRuntime.nodes[id];
  1434. var newNode = null;
  1435. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1436. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1437. meshIncluded = true;
  1438. }
  1439. else {
  1440. meshIncluded = false;
  1441. }
  1442. }
  1443. else {
  1444. meshIncluded = true;
  1445. }
  1446. if (!node.jointName && meshIncluded) {
  1447. newNode = importNode(gltfRuntime, node, id, parent);
  1448. if (newNode !== null) {
  1449. newNode.id = id;
  1450. newNode.parent = parent;
  1451. }
  1452. }
  1453. if (node.children) {
  1454. for (var i = 0; i < node.children.length; i++) {
  1455. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1456. }
  1457. }
  1458. };
  1459. /**
  1460. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1461. */
  1462. var postLoad = function (gltfRuntime) {
  1463. // Nodes
  1464. var currentScene = gltfRuntime.currentScene;
  1465. if (currentScene) {
  1466. for (var i = 0; i < currentScene.nodes.length; i++) {
  1467. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1468. }
  1469. }
  1470. else {
  1471. for (var thing in gltfRuntime.scenes) {
  1472. currentScene = gltfRuntime.scenes[thing];
  1473. for (var i = 0; i < currentScene.nodes.length; i++) {
  1474. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1475. }
  1476. }
  1477. }
  1478. // Set animations
  1479. loadAnimations(gltfRuntime);
  1480. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1481. var skeleton = gltfRuntime.scene.skeletons[i];
  1482. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1483. }
  1484. };
  1485. /**
  1486. * onBind shaderrs callback to set uniforms and matrices
  1487. */
  1488. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1489. var materialValues = material.values || technique.parameters;
  1490. for (var unif in unTreatedUniforms) {
  1491. var uniform = unTreatedUniforms[unif];
  1492. var type = uniform.type;
  1493. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1494. if (uniform.semantic && !uniform.source && !uniform.node) {
  1495. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1496. }
  1497. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1498. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1499. if (source === null) {
  1500. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1501. }
  1502. if (source === null) {
  1503. continue;
  1504. }
  1505. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1506. }
  1507. }
  1508. else {
  1509. var value = materialValues[technique.uniforms[unif]];
  1510. if (!value) {
  1511. continue;
  1512. }
  1513. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1514. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1515. if (texture === null || texture === undefined) {
  1516. continue;
  1517. }
  1518. shaderMaterial.getEffect().setTexture(unif, texture);
  1519. }
  1520. else {
  1521. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1522. }
  1523. }
  1524. }
  1525. onSuccess(shaderMaterial);
  1526. };
  1527. /**
  1528. * Prepare uniforms to send the only one time
  1529. * Loads the appropriate textures
  1530. */
  1531. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1532. var materialValues = material.values || technique.parameters;
  1533. var techniqueUniforms = technique.uniforms;
  1534. /**
  1535. * Prepare values here (not matrices)
  1536. */
  1537. for (var unif in unTreatedUniforms) {
  1538. var uniform = unTreatedUniforms[unif];
  1539. var type = uniform.type;
  1540. var value = materialValues[techniqueUniforms[unif]];
  1541. if (value === undefined) {
  1542. // In case the value is the same for all materials
  1543. value = uniform.value;
  1544. }
  1545. if (!value) {
  1546. continue;
  1547. }
  1548. var onLoadTexture = function (uniformName) {
  1549. return function (texture) {
  1550. if (uniform.value && uniformName) {
  1551. // Static uniform
  1552. shaderMaterial.setTexture(uniformName, texture);
  1553. delete unTreatedUniforms[uniformName];
  1554. }
  1555. };
  1556. };
  1557. // Texture (sampler2D)
  1558. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1559. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1560. }
  1561. // Others
  1562. else {
  1563. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1564. // Static uniform
  1565. delete unTreatedUniforms[unif];
  1566. }
  1567. }
  1568. }
  1569. };
  1570. /**
  1571. * Shader compilation failed
  1572. */
  1573. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1574. return function (effect, error) {
  1575. shaderMaterial.dispose(true);
  1576. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1577. };
  1578. };
  1579. /**
  1580. * Shader compilation success
  1581. */
  1582. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1583. return function (_) {
  1584. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1585. shaderMaterial.onBind = function (mesh) {
  1586. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1587. };
  1588. };
  1589. };
  1590. /**
  1591. * Returns the appropriate uniform if already handled by babylon
  1592. */
  1593. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1594. for (var unif in technique.uniforms) {
  1595. var uniform = technique.uniforms[unif];
  1596. var uniformParameter = technique.parameters[uniform];
  1597. if (tokenizer.currentIdentifier === unif) {
  1598. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1599. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1600. if (transformIndex !== -1) {
  1601. delete unTreatedUniforms[unif];
  1602. return babylonTransforms[transformIndex];
  1603. }
  1604. }
  1605. }
  1606. }
  1607. return tokenizer.currentIdentifier;
  1608. };
  1609. /**
  1610. * All shaders loaded. Create materials one by one
  1611. */
  1612. var importMaterials = function (gltfRuntime) {
  1613. // Create materials
  1614. for (var mat in gltfRuntime.materials) {
  1615. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1616. }
  1617. };
  1618. /**
  1619. * Implementation of the base glTF spec
  1620. */
  1621. var GLTFLoaderBase = /** @class */ (function () {
  1622. function GLTFLoaderBase() {
  1623. }
  1624. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1625. var gltfRuntime = {
  1626. extensions: {},
  1627. accessors: {},
  1628. buffers: {},
  1629. bufferViews: {},
  1630. meshes: {},
  1631. lights: {},
  1632. cameras: {},
  1633. nodes: {},
  1634. images: {},
  1635. textures: {},
  1636. shaders: {},
  1637. programs: {},
  1638. samplers: {},
  1639. techniques: {},
  1640. materials: {},
  1641. animations: {},
  1642. skins: {},
  1643. extensionsUsed: [],
  1644. scenes: {},
  1645. buffersCount: 0,
  1646. shaderscount: 0,
  1647. scene: scene,
  1648. rootUrl: rootUrl,
  1649. loadedBufferCount: 0,
  1650. loadedBufferViews: {},
  1651. loadedShaderCount: 0,
  1652. importOnlyMeshes: false,
  1653. dummyNodes: []
  1654. };
  1655. // Parse
  1656. if (parsedData.extensions) {
  1657. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1658. }
  1659. if (parsedData.extensionsUsed) {
  1660. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1661. }
  1662. if (parsedData.buffers) {
  1663. parseBuffers(parsedData.buffers, gltfRuntime);
  1664. }
  1665. if (parsedData.bufferViews) {
  1666. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1667. }
  1668. if (parsedData.accessors) {
  1669. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1670. }
  1671. if (parsedData.meshes) {
  1672. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1673. }
  1674. if (parsedData.lights) {
  1675. parseObject(parsedData.lights, "lights", gltfRuntime);
  1676. }
  1677. if (parsedData.cameras) {
  1678. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1679. }
  1680. if (parsedData.nodes) {
  1681. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1682. }
  1683. if (parsedData.images) {
  1684. parseObject(parsedData.images, "images", gltfRuntime);
  1685. }
  1686. if (parsedData.textures) {
  1687. parseObject(parsedData.textures, "textures", gltfRuntime);
  1688. }
  1689. if (parsedData.shaders) {
  1690. parseShaders(parsedData.shaders, gltfRuntime);
  1691. }
  1692. if (parsedData.programs) {
  1693. parseObject(parsedData.programs, "programs", gltfRuntime);
  1694. }
  1695. if (parsedData.samplers) {
  1696. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1697. }
  1698. if (parsedData.techniques) {
  1699. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1700. }
  1701. if (parsedData.materials) {
  1702. parseObject(parsedData.materials, "materials", gltfRuntime);
  1703. }
  1704. if (parsedData.animations) {
  1705. parseObject(parsedData.animations, "animations", gltfRuntime);
  1706. }
  1707. if (parsedData.skins) {
  1708. parseObject(parsedData.skins, "skins", gltfRuntime);
  1709. }
  1710. if (parsedData.scenes) {
  1711. gltfRuntime.scenes = parsedData.scenes;
  1712. }
  1713. if (parsedData.scene && parsedData.scenes) {
  1714. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1715. }
  1716. return gltfRuntime;
  1717. };
  1718. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1719. var buffer = gltfRuntime.buffers[id];
  1720. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1721. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1722. }
  1723. else {
  1724. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1725. if (request) {
  1726. onError(request.status + " " + request.statusText);
  1727. }
  1728. });
  1729. }
  1730. };
  1731. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1732. var texture = gltfRuntime.textures[id];
  1733. if (!texture || !texture.source) {
  1734. onError("");
  1735. return;
  1736. }
  1737. if (texture.babylonTexture) {
  1738. onSuccess(null);
  1739. return;
  1740. }
  1741. var source = gltfRuntime.images[texture.source];
  1742. if (BABYLON.Tools.IsBase64(source.uri)) {
  1743. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1744. }
  1745. else {
  1746. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1747. if (request) {
  1748. onError(request.status + " " + request.statusText);
  1749. }
  1750. });
  1751. }
  1752. };
  1753. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1754. var texture = gltfRuntime.textures[id];
  1755. if (texture.babylonTexture) {
  1756. onSuccess(texture.babylonTexture);
  1757. return;
  1758. }
  1759. var sampler = gltfRuntime.samplers[texture.sampler];
  1760. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1761. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1762. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1763. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1764. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1765. var blob = new Blob([buffer]);
  1766. var blobURL = URL.createObjectURL(blob);
  1767. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1768. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1769. if (sampler.wrapS !== undefined) {
  1770. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1771. }
  1772. if (sampler.wrapT !== undefined) {
  1773. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1774. }
  1775. newTexture.name = id;
  1776. texture.babylonTexture = newTexture;
  1777. onSuccess(newTexture);
  1778. };
  1779. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1780. var shader = gltfRuntime.shaders[id];
  1781. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1782. var shaderString = atob(shader.uri.split(",")[1]);
  1783. if (onSuccess) {
  1784. onSuccess(shaderString);
  1785. }
  1786. }
  1787. else {
  1788. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1789. if (request && onError) {
  1790. onError(request.status + " " + request.statusText);
  1791. }
  1792. });
  1793. }
  1794. };
  1795. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1796. var material = gltfRuntime.materials[id];
  1797. if (!material.technique) {
  1798. if (onError) {
  1799. onError("No technique found.");
  1800. }
  1801. return;
  1802. }
  1803. var technique = gltfRuntime.techniques[material.technique];
  1804. if (!technique) {
  1805. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1806. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1807. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1808. onSuccess(defaultMaterial);
  1809. return;
  1810. }
  1811. var program = gltfRuntime.programs[technique.program];
  1812. var states = technique.states;
  1813. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1814. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1815. var newVertexShader = "";
  1816. var newPixelShader = "";
  1817. var vertexTokenizer = new Tokenizer(vertexShader);
  1818. var pixelTokenizer = new Tokenizer(pixelShader);
  1819. var unTreatedUniforms = {};
  1820. var uniforms = [];
  1821. var attributes = [];
  1822. var samplers = [];
  1823. // Fill uniform, sampler2D and attributes
  1824. for (var unif in technique.uniforms) {
  1825. var uniform = technique.uniforms[unif];
  1826. var uniformParameter = technique.parameters[uniform];
  1827. unTreatedUniforms[unif] = uniformParameter;
  1828. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1829. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1830. if (transformIndex !== -1) {
  1831. uniforms.push(babylonTransforms[transformIndex]);
  1832. delete unTreatedUniforms[unif];
  1833. }
  1834. else {
  1835. uniforms.push(unif);
  1836. }
  1837. }
  1838. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1839. samplers.push(unif);
  1840. }
  1841. else {
  1842. uniforms.push(unif);
  1843. }
  1844. }
  1845. for (var attr in technique.attributes) {
  1846. var attribute = technique.attributes[attr];
  1847. var attributeParameter = technique.parameters[attribute];
  1848. if (attributeParameter.semantic) {
  1849. attributes.push(getAttribute(attributeParameter));
  1850. }
  1851. }
  1852. // Configure vertex shader
  1853. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1854. var tokenType = vertexTokenizer.currentToken;
  1855. if (tokenType !== ETokenType.IDENTIFIER) {
  1856. newVertexShader += vertexTokenizer.currentString;
  1857. continue;
  1858. }
  1859. var foundAttribute = false;
  1860. for (var attr in technique.attributes) {
  1861. var attribute = technique.attributes[attr];
  1862. var attributeParameter = technique.parameters[attribute];
  1863. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1864. newVertexShader += getAttribute(attributeParameter);
  1865. foundAttribute = true;
  1866. break;
  1867. }
  1868. }
  1869. if (foundAttribute) {
  1870. continue;
  1871. }
  1872. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1873. }
  1874. // Configure pixel shader
  1875. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1876. var tokenType = pixelTokenizer.currentToken;
  1877. if (tokenType !== ETokenType.IDENTIFIER) {
  1878. newPixelShader += pixelTokenizer.currentString;
  1879. continue;
  1880. }
  1881. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1882. }
  1883. // Create shader material
  1884. var shaderPath = {
  1885. vertex: program.vertexShader + id,
  1886. fragment: program.fragmentShader + id
  1887. };
  1888. var options = {
  1889. attributes: attributes,
  1890. uniforms: uniforms,
  1891. samplers: samplers,
  1892. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1893. };
  1894. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1895. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1896. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1897. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1898. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1899. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1900. if (states && states.functions) {
  1901. var functions = states.functions;
  1902. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1903. shaderMaterial.backFaceCulling = false;
  1904. }
  1905. var blendFunc = functions.blendFuncSeparate;
  1906. if (blendFunc) {
  1907. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1908. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1909. }
  1910. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1911. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1912. }
  1913. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1914. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1915. }
  1916. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1917. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1918. }
  1919. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1920. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1921. }
  1922. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1923. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1924. }
  1925. }
  1926. }
  1927. };
  1928. return GLTFLoaderBase;
  1929. }());
  1930. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1931. /**
  1932. * glTF V1 Loader
  1933. */
  1934. var GLTFLoader = /** @class */ (function () {
  1935. function GLTFLoader() {
  1936. // #region Stubs for IGLTFLoader interface
  1937. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1938. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1939. this.compileMaterials = false;
  1940. this.useClipPlane = false;
  1941. this.compileShadowGenerators = false;
  1942. this.onDisposeObservable = new BABYLON.Observable();
  1943. this.onMeshLoadedObservable = new BABYLON.Observable();
  1944. this.onTextureLoadedObservable = new BABYLON.Observable();
  1945. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1946. this.onCompleteObservable = new BABYLON.Observable();
  1947. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1948. /**
  1949. * State of the loader
  1950. */
  1951. this.state = null;
  1952. }
  1953. GLTFLoader.RegisterExtension = function (extension) {
  1954. if (GLTFLoader.Extensions[extension.name]) {
  1955. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1956. return;
  1957. }
  1958. GLTFLoader.Extensions[extension.name] = extension;
  1959. };
  1960. GLTFLoader.prototype.dispose = function () { };
  1961. // #endregion
  1962. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1963. var _this = this;
  1964. scene.useRightHandedSystem = true;
  1965. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1966. gltfRuntime.importOnlyMeshes = true;
  1967. if (meshesNames === "") {
  1968. gltfRuntime.importMeshesNames = [];
  1969. }
  1970. else if (typeof meshesNames === "string") {
  1971. gltfRuntime.importMeshesNames = [meshesNames];
  1972. }
  1973. else if (meshesNames && !(meshesNames instanceof Array)) {
  1974. gltfRuntime.importMeshesNames = [meshesNames];
  1975. }
  1976. else {
  1977. gltfRuntime.importMeshesNames = [];
  1978. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1979. }
  1980. // Create nodes
  1981. _this._createNodes(gltfRuntime);
  1982. var meshes = new Array();
  1983. var skeletons = new Array();
  1984. // Fill arrays of meshes and skeletons
  1985. for (var nde in gltfRuntime.nodes) {
  1986. var node = gltfRuntime.nodes[nde];
  1987. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1988. meshes.push(node.babylonNode);
  1989. }
  1990. }
  1991. for (var skl in gltfRuntime.skins) {
  1992. var skin = gltfRuntime.skins[skl];
  1993. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1994. skeletons.push(skin.babylonSkeleton);
  1995. }
  1996. }
  1997. // Load buffers, shaders, materials, etc.
  1998. _this._loadBuffersAsync(gltfRuntime, function () {
  1999. _this._loadShadersAsync(gltfRuntime, function () {
  2000. importMaterials(gltfRuntime);
  2001. postLoad(gltfRuntime);
  2002. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2003. onSuccess(meshes, skeletons);
  2004. }
  2005. });
  2006. }, onProgress);
  2007. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2008. onSuccess(meshes, skeletons);
  2009. }
  2010. }, onError);
  2011. return true;
  2012. };
  2013. /**
  2014. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2015. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2016. * @param scene the scene the meshes should be added to
  2017. * @param data gltf data containing information of the meshes in a loaded file
  2018. * @param rootUrl root url to load from
  2019. * @param onProgress event that fires when loading progress has occured
  2020. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2021. */
  2022. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2023. var _this = this;
  2024. return new Promise(function (resolve, reject) {
  2025. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  2026. resolve({
  2027. meshes: meshes,
  2028. particleSystems: [],
  2029. skeletons: skeletons,
  2030. animationGroups: []
  2031. });
  2032. }, onProgress, function (message) {
  2033. reject(new Error(message));
  2034. });
  2035. });
  2036. };
  2037. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2038. var _this = this;
  2039. scene.useRightHandedSystem = true;
  2040. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2041. // Load runtime extensios
  2042. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2043. // Create nodes
  2044. _this._createNodes(gltfRuntime);
  2045. // Load buffers, shaders, materials, etc.
  2046. _this._loadBuffersAsync(gltfRuntime, function () {
  2047. _this._loadShadersAsync(gltfRuntime, function () {
  2048. importMaterials(gltfRuntime);
  2049. postLoad(gltfRuntime);
  2050. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2051. onSuccess();
  2052. }
  2053. });
  2054. });
  2055. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2056. onSuccess();
  2057. }
  2058. }, onError);
  2059. }, onError);
  2060. };
  2061. /**
  2062. * Imports all objects from a loaded gltf file and adds them to the scene
  2063. * @param scene the scene the objects should be added to
  2064. * @param data gltf data containing information of the meshes in a loaded file
  2065. * @param rootUrl root url to load from
  2066. * @param onProgress event that fires when loading progress has occured
  2067. * @returns a promise which completes when objects have been loaded to the scene
  2068. */
  2069. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2070. var _this = this;
  2071. return new Promise(function (resolve, reject) {
  2072. _this._loadAsync(scene, data, rootUrl, function () {
  2073. resolve();
  2074. }, onProgress, function (message) {
  2075. reject(new Error(message));
  2076. });
  2077. });
  2078. };
  2079. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2080. var hasShaders = false;
  2081. var processShader = function (sha, shader) {
  2082. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2083. if (shaderString instanceof ArrayBuffer) {
  2084. return;
  2085. }
  2086. gltfRuntime.loadedShaderCount++;
  2087. if (shaderString) {
  2088. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2089. }
  2090. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2091. onload();
  2092. }
  2093. }, function () {
  2094. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2095. });
  2096. };
  2097. for (var sha in gltfRuntime.shaders) {
  2098. hasShaders = true;
  2099. var shader = gltfRuntime.shaders[sha];
  2100. if (shader) {
  2101. processShader.bind(this, sha, shader)();
  2102. }
  2103. else {
  2104. BABYLON.Tools.Error("No shader named: " + sha);
  2105. }
  2106. }
  2107. if (!hasShaders) {
  2108. onload();
  2109. }
  2110. };
  2111. ;
  2112. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2113. var hasBuffers = false;
  2114. var processBuffer = function (buf, buffer) {
  2115. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2116. gltfRuntime.loadedBufferCount++;
  2117. if (bufferView) {
  2118. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2119. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2120. }
  2121. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2122. }
  2123. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2124. onLoad();
  2125. }
  2126. }, function () {
  2127. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2128. });
  2129. };
  2130. for (var buf in gltfRuntime.buffers) {
  2131. hasBuffers = true;
  2132. var buffer = gltfRuntime.buffers[buf];
  2133. if (buffer) {
  2134. processBuffer.bind(this, buf, buffer)();
  2135. }
  2136. else {
  2137. BABYLON.Tools.Error("No buffer named: " + buf);
  2138. }
  2139. }
  2140. if (!hasBuffers) {
  2141. onLoad();
  2142. }
  2143. };
  2144. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2145. var currentScene = gltfRuntime.currentScene;
  2146. if (currentScene) {
  2147. // Only one scene even if multiple scenes are defined
  2148. for (var i = 0; i < currentScene.nodes.length; i++) {
  2149. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2150. }
  2151. }
  2152. else {
  2153. // Load all scenes
  2154. for (var thing in gltfRuntime.scenes) {
  2155. currentScene = gltfRuntime.scenes[thing];
  2156. for (var i = 0; i < currentScene.nodes.length; i++) {
  2157. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2158. }
  2159. }
  2160. }
  2161. };
  2162. GLTFLoader.Extensions = {};
  2163. return GLTFLoader;
  2164. }());
  2165. GLTF1.GLTFLoader = GLTFLoader;
  2166. ;
  2167. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2168. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2169. })(BABYLON || (BABYLON = {}));
  2170. //# sourceMappingURL=babylon.glTFLoader.js.map
  2171. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2172. var BABYLON;
  2173. (function (BABYLON) {
  2174. var GLTF1;
  2175. (function (GLTF1) {
  2176. /**
  2177. * Utils functions for GLTF
  2178. */
  2179. var GLTFUtils = /** @class */ (function () {
  2180. function GLTFUtils() {
  2181. }
  2182. /**
  2183. * Sets the given "parameter" matrix
  2184. * @param scene: the {BABYLON.Scene} object
  2185. * @param source: the source node where to pick the matrix
  2186. * @param parameter: the GLTF technique parameter
  2187. * @param uniformName: the name of the shader's uniform
  2188. * @param shaderMaterial: the shader material
  2189. */
  2190. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2191. var mat = null;
  2192. if (parameter.semantic === "MODEL") {
  2193. mat = source.getWorldMatrix();
  2194. }
  2195. else if (parameter.semantic === "PROJECTION") {
  2196. mat = scene.getProjectionMatrix();
  2197. }
  2198. else if (parameter.semantic === "VIEW") {
  2199. mat = scene.getViewMatrix();
  2200. }
  2201. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2202. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2203. }
  2204. else if (parameter.semantic === "MODELVIEW") {
  2205. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2206. }
  2207. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2208. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2209. }
  2210. else if (parameter.semantic === "MODELINVERSE") {
  2211. mat = source.getWorldMatrix().invert();
  2212. }
  2213. else if (parameter.semantic === "VIEWINVERSE") {
  2214. mat = scene.getViewMatrix().invert();
  2215. }
  2216. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2217. mat = scene.getProjectionMatrix().invert();
  2218. }
  2219. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2220. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2221. }
  2222. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2223. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2224. }
  2225. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2226. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2227. }
  2228. else {
  2229. debugger;
  2230. }
  2231. if (mat) {
  2232. switch (parameter.type) {
  2233. case GLTF1.EParameterType.FLOAT_MAT2:
  2234. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2235. break;
  2236. case GLTF1.EParameterType.FLOAT_MAT3:
  2237. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2238. break;
  2239. case GLTF1.EParameterType.FLOAT_MAT4:
  2240. shaderMaterial.setMatrix(uniformName, mat);
  2241. break;
  2242. default: break;
  2243. }
  2244. }
  2245. };
  2246. /**
  2247. * Sets the given "parameter" matrix
  2248. * @param shaderMaterial: the shader material
  2249. * @param uniform: the name of the shader's uniform
  2250. * @param value: the value of the uniform
  2251. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2252. */
  2253. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2254. switch (type) {
  2255. case GLTF1.EParameterType.FLOAT:
  2256. shaderMaterial.setFloat(uniform, value);
  2257. return true;
  2258. case GLTF1.EParameterType.FLOAT_VEC2:
  2259. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2260. return true;
  2261. case GLTF1.EParameterType.FLOAT_VEC3:
  2262. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2263. return true;
  2264. case GLTF1.EParameterType.FLOAT_VEC4:
  2265. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2266. return true;
  2267. default: return false;
  2268. }
  2269. };
  2270. /**
  2271. * Returns the wrap mode of the texture
  2272. * @param mode: the mode value
  2273. */
  2274. GLTFUtils.GetWrapMode = function (mode) {
  2275. switch (mode) {
  2276. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2277. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2278. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2279. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2280. }
  2281. };
  2282. /**
  2283. * Returns the byte stride giving an accessor
  2284. * @param accessor: the GLTF accessor objet
  2285. */
  2286. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2287. // Needs this function since "byteStride" isn't requiered in glTF format
  2288. var type = accessor.type;
  2289. switch (type) {
  2290. case "VEC2": return 2;
  2291. case "VEC3": return 3;
  2292. case "VEC4": return 4;
  2293. case "MAT2": return 4;
  2294. case "MAT3": return 9;
  2295. case "MAT4": return 16;
  2296. default: return 1;
  2297. }
  2298. };
  2299. /**
  2300. * Returns the texture filter mode giving a mode value
  2301. * @param mode: the filter mode value
  2302. */
  2303. GLTFUtils.GetTextureFilterMode = function (mode) {
  2304. switch (mode) {
  2305. case GLTF1.ETextureFilterType.LINEAR:
  2306. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2307. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2308. case GLTF1.ETextureFilterType.NEAREST:
  2309. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2310. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2311. }
  2312. };
  2313. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2314. var byteOffset = bufferView.byteOffset + byteOffset;
  2315. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2316. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2317. throw new Error("Buffer access is out of range");
  2318. }
  2319. var buffer = loadedBufferView.buffer;
  2320. byteOffset += loadedBufferView.byteOffset;
  2321. switch (componentType) {
  2322. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2323. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2324. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2325. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2326. default: return new Float32Array(buffer, byteOffset, byteLength);
  2327. }
  2328. };
  2329. /**
  2330. * Returns a buffer from its accessor
  2331. * @param gltfRuntime: the GLTF runtime
  2332. * @param accessor: the GLTF accessor
  2333. */
  2334. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2335. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2336. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2337. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2338. };
  2339. /**
  2340. * Decodes a buffer view into a string
  2341. * @param view: the buffer view
  2342. */
  2343. GLTFUtils.DecodeBufferToText = function (view) {
  2344. var result = "";
  2345. var length = view.byteLength;
  2346. for (var i = 0; i < length; ++i) {
  2347. result += String.fromCharCode(view[i]);
  2348. }
  2349. return result;
  2350. };
  2351. /**
  2352. * Returns the default material of gltf. Related to
  2353. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2354. * @param scene: the Babylon.js scene
  2355. */
  2356. GLTFUtils.GetDefaultMaterial = function (scene) {
  2357. if (!GLTFUtils._DefaultMaterial) {
  2358. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2359. "precision highp float;",
  2360. "",
  2361. "uniform mat4 worldView;",
  2362. "uniform mat4 projection;",
  2363. "",
  2364. "attribute vec3 position;",
  2365. "",
  2366. "void main(void)",
  2367. "{",
  2368. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2369. "}"
  2370. ].join("\n");
  2371. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2372. "precision highp float;",
  2373. "",
  2374. "uniform vec4 u_emission;",
  2375. "",
  2376. "void main(void)",
  2377. "{",
  2378. " gl_FragColor = u_emission;",
  2379. "}"
  2380. ].join("\n");
  2381. var shaderPath = {
  2382. vertex: "GLTFDefaultMaterial",
  2383. fragment: "GLTFDefaultMaterial"
  2384. };
  2385. var options = {
  2386. attributes: ["position"],
  2387. uniforms: ["worldView", "projection", "u_emission"],
  2388. samplers: new Array(),
  2389. needAlphaBlending: false
  2390. };
  2391. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2392. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2393. }
  2394. return GLTFUtils._DefaultMaterial;
  2395. };
  2396. // The GLTF default material
  2397. GLTFUtils._DefaultMaterial = null;
  2398. return GLTFUtils;
  2399. }());
  2400. GLTF1.GLTFUtils = GLTFUtils;
  2401. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2402. })(BABYLON || (BABYLON = {}));
  2403. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2404. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2405. var BABYLON;
  2406. (function (BABYLON) {
  2407. var GLTF1;
  2408. (function (GLTF1) {
  2409. var GLTFLoaderExtension = /** @class */ (function () {
  2410. function GLTFLoaderExtension(name) {
  2411. this._name = name;
  2412. }
  2413. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2414. get: function () {
  2415. return this._name;
  2416. },
  2417. enumerable: true,
  2418. configurable: true
  2419. });
  2420. /**
  2421. * Defines an override for loading the runtime
  2422. * Return true to stop further extensions from loading the runtime
  2423. */
  2424. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2425. return false;
  2426. };
  2427. /**
  2428. * Defines an onverride for creating gltf runtime
  2429. * Return true to stop further extensions from creating the runtime
  2430. */
  2431. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2432. return false;
  2433. };
  2434. /**
  2435. * Defines an override for loading buffers
  2436. * Return true to stop further extensions from loading this buffer
  2437. */
  2438. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2439. return false;
  2440. };
  2441. /**
  2442. * Defines an override for loading texture buffers
  2443. * Return true to stop further extensions from loading this texture data
  2444. */
  2445. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2446. return false;
  2447. };
  2448. /**
  2449. * Defines an override for creating textures
  2450. * Return true to stop further extensions from loading this texture
  2451. */
  2452. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2453. return false;
  2454. };
  2455. /**
  2456. * Defines an override for loading shader strings
  2457. * Return true to stop further extensions from loading this shader data
  2458. */
  2459. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2460. return false;
  2461. };
  2462. /**
  2463. * Defines an override for loading materials
  2464. * Return true to stop further extensions from loading this material
  2465. */
  2466. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2467. return false;
  2468. };
  2469. // ---------
  2470. // Utilities
  2471. // ---------
  2472. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2473. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2474. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2475. }, function () {
  2476. setTimeout(function () {
  2477. if (!onSuccess) {
  2478. return;
  2479. }
  2480. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2481. });
  2482. });
  2483. };
  2484. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2485. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2486. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2487. }, function () {
  2488. setTimeout(function () {
  2489. onSuccess();
  2490. });
  2491. });
  2492. };
  2493. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2494. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2495. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2496. }, function () {
  2497. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2498. });
  2499. };
  2500. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2501. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2502. if (buffer) {
  2503. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2504. }
  2505. }, onError);
  2506. };
  2507. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2508. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2509. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2510. }, function () {
  2511. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2512. });
  2513. };
  2514. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2515. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2516. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2517. }, function () {
  2518. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2519. });
  2520. };
  2521. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2522. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2523. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2524. }, function () {
  2525. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2526. });
  2527. };
  2528. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2529. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2530. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2531. }, function () {
  2532. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2533. });
  2534. };
  2535. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2536. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2537. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2538. if (func(loaderExtension)) {
  2539. return;
  2540. }
  2541. }
  2542. defaultFunc();
  2543. };
  2544. return GLTFLoaderExtension;
  2545. }());
  2546. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2547. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2548. })(BABYLON || (BABYLON = {}));
  2549. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2550. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2551. var __extends = (this && this.__extends) || (function () {
  2552. var extendStatics = Object.setPrototypeOf ||
  2553. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2554. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2555. return function (d, b) {
  2556. extendStatics(d, b);
  2557. function __() { this.constructor = d; }
  2558. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2559. };
  2560. })();
  2561. var BABYLON;
  2562. (function (BABYLON) {
  2563. var GLTF1;
  2564. (function (GLTF1) {
  2565. var BinaryExtensionBufferName = "binary_glTF";
  2566. ;
  2567. ;
  2568. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2569. __extends(GLTFBinaryExtension, _super);
  2570. function GLTFBinaryExtension() {
  2571. return _super.call(this, "KHR_binary_glTF") || this;
  2572. }
  2573. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2574. var extensionsUsed = data.json.extensionsUsed;
  2575. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2576. return false;
  2577. }
  2578. this._bin = data.bin;
  2579. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2580. return true;
  2581. };
  2582. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2583. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2584. return false;
  2585. }
  2586. if (id !== BinaryExtensionBufferName) {
  2587. return false;
  2588. }
  2589. onSuccess(this._bin);
  2590. return true;
  2591. };
  2592. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2593. var texture = gltfRuntime.textures[id];
  2594. var source = gltfRuntime.images[texture.source];
  2595. if (!source.extensions || !(this.name in source.extensions)) {
  2596. return false;
  2597. }
  2598. var sourceExt = source.extensions[this.name];
  2599. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2600. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2601. onSuccess(buffer);
  2602. return true;
  2603. };
  2604. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2605. var shader = gltfRuntime.shaders[id];
  2606. if (!shader.extensions || !(this.name in shader.extensions)) {
  2607. return false;
  2608. }
  2609. var binaryExtensionShader = shader.extensions[this.name];
  2610. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2611. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2612. setTimeout(function () {
  2613. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2614. onSuccess(shaderString);
  2615. });
  2616. return true;
  2617. };
  2618. return GLTFBinaryExtension;
  2619. }(GLTF1.GLTFLoaderExtension));
  2620. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2621. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2622. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2623. })(BABYLON || (BABYLON = {}));
  2624. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2625. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2626. var __extends = (this && this.__extends) || (function () {
  2627. var extendStatics = Object.setPrototypeOf ||
  2628. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2629. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2630. return function (d, b) {
  2631. extendStatics(d, b);
  2632. function __() { this.constructor = d; }
  2633. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2634. };
  2635. })();
  2636. var BABYLON;
  2637. (function (BABYLON) {
  2638. var GLTF1;
  2639. (function (GLTF1) {
  2640. ;
  2641. ;
  2642. ;
  2643. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2644. __extends(GLTFMaterialsCommonExtension, _super);
  2645. function GLTFMaterialsCommonExtension() {
  2646. return _super.call(this, "KHR_materials_common") || this;
  2647. }
  2648. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2649. if (!gltfRuntime.extensions)
  2650. return false;
  2651. var extension = gltfRuntime.extensions[this.name];
  2652. if (!extension)
  2653. return false;
  2654. // Create lights
  2655. var lights = extension.lights;
  2656. if (lights) {
  2657. for (var thing in lights) {
  2658. var light = lights[thing];
  2659. switch (light.type) {
  2660. case "ambient":
  2661. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2662. var ambient = light.ambient;
  2663. if (ambient) {
  2664. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2665. }
  2666. break;
  2667. case "point":
  2668. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2669. var point = light.point;
  2670. if (point) {
  2671. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2672. }
  2673. break;
  2674. case "directional":
  2675. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2676. var directional = light.directional;
  2677. if (directional) {
  2678. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2679. }
  2680. break;
  2681. case "spot":
  2682. var spot = light.spot;
  2683. if (spot) {
  2684. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2685. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2686. }
  2687. break;
  2688. default:
  2689. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2690. break;
  2691. }
  2692. }
  2693. }
  2694. return false;
  2695. };
  2696. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2697. var material = gltfRuntime.materials[id];
  2698. if (!material || !material.extensions)
  2699. return false;
  2700. var extension = material.extensions[this.name];
  2701. if (!extension)
  2702. return false;
  2703. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2704. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2705. if (extension.technique === "CONSTANT") {
  2706. standardMaterial.disableLighting = true;
  2707. }
  2708. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2709. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2710. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2711. // Ambient
  2712. if (typeof extension.values.ambient === "string") {
  2713. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2714. }
  2715. else {
  2716. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2717. }
  2718. // Diffuse
  2719. if (typeof extension.values.diffuse === "string") {
  2720. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2721. }
  2722. else {
  2723. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2724. }
  2725. // Emission
  2726. if (typeof extension.values.emission === "string") {
  2727. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2728. }
  2729. else {
  2730. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2731. }
  2732. // Specular
  2733. if (typeof extension.values.specular === "string") {
  2734. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2735. }
  2736. else {
  2737. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2738. }
  2739. return true;
  2740. };
  2741. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2742. // Create buffer from texture url
  2743. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2744. // Create texture from buffer
  2745. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2746. }, onError);
  2747. };
  2748. return GLTFMaterialsCommonExtension;
  2749. }(GLTF1.GLTFLoaderExtension));
  2750. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2751. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2752. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2753. })(BABYLON || (BABYLON = {}));
  2754. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2755. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2756. var BABYLON;
  2757. (function (BABYLON) {
  2758. var GLTF2;
  2759. (function (GLTF2) {
  2760. /** Array item helper methods */
  2761. var ArrayItem = /** @class */ (function () {
  2762. function ArrayItem() {
  2763. }
  2764. /** Sets the index of each array element to its index in the array */
  2765. ArrayItem.Assign = function (values) {
  2766. if (values) {
  2767. for (var index = 0; index < values.length; index++) {
  2768. values[index]._index = index;
  2769. }
  2770. }
  2771. };
  2772. return ArrayItem;
  2773. }());
  2774. GLTF2.ArrayItem = ArrayItem;
  2775. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2776. })(BABYLON || (BABYLON = {}));
  2777. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2778. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2779. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2780. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2781. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2782. /**
  2783. * Defines the GLTF2 module used to import/export GLTF 2.0 files
  2784. */
  2785. var BABYLON;
  2786. (function (BABYLON) {
  2787. var GLTF2;
  2788. (function (GLTF2) {
  2789. /**
  2790. * Used to load from a GLTF2 file
  2791. */
  2792. var GLTFLoader = /** @class */ (function () {
  2793. function GLTFLoader() {
  2794. /**
  2795. * @ignore
  2796. */
  2797. this._completePromises = new Array();
  2798. this._disposed = false;
  2799. this._state = null;
  2800. this._extensions = {};
  2801. this._defaultSampler = {};
  2802. this._defaultBabylonMaterials = {};
  2803. this._requests = new Array();
  2804. /**
  2805. * Coordinate system that will be used when loading from the gltf file
  2806. */
  2807. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2808. /**
  2809. * Animation mode that determines which animations should be started when a file is loaded
  2810. */
  2811. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2812. /**
  2813. * If the materials in the file should automatically be compiled
  2814. */
  2815. this.compileMaterials = false;
  2816. /**
  2817. * If a clip plane should be usede when loading meshes in the file
  2818. */
  2819. this.useClipPlane = false;
  2820. /**
  2821. * If shadow generators should automatically be compiled
  2822. */
  2823. this.compileShadowGenerators = false;
  2824. /**
  2825. * Observable that fires when the loader is disposed
  2826. */
  2827. this.onDisposeObservable = new BABYLON.Observable();
  2828. /**
  2829. * Observable that fires each time a mesh is loaded
  2830. */
  2831. this.onMeshLoadedObservable = new BABYLON.Observable();
  2832. /**
  2833. * Observable that fires each time a texture is loaded
  2834. */
  2835. this.onTextureLoadedObservable = new BABYLON.Observable();
  2836. /**
  2837. * Observable that fires each time a material is loaded
  2838. */
  2839. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2840. /**
  2841. * Observable that fires each time an extension is loaded
  2842. */
  2843. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2844. /**
  2845. * Observable that fires when the load has completed
  2846. */
  2847. this.onCompleteObservable = new BABYLON.Observable();
  2848. }
  2849. /**
  2850. * @ignore, registers the loader
  2851. * @param name name of the loader
  2852. * @param factory function that converts a loader to a loader extension
  2853. */
  2854. GLTFLoader._Register = function (name, factory) {
  2855. if (GLTFLoader._Factories[name]) {
  2856. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2857. return;
  2858. }
  2859. GLTFLoader._Factories[name] = factory;
  2860. // Keep the order of registration so that extensions registered first are called first.
  2861. GLTFLoader._Names.push(name);
  2862. };
  2863. Object.defineProperty(GLTFLoader.prototype, "state", {
  2864. /**
  2865. * The current state of the loader
  2866. */
  2867. get: function () {
  2868. return this._state;
  2869. },
  2870. enumerable: true,
  2871. configurable: true
  2872. });
  2873. /**
  2874. * Disposes of the loader
  2875. */
  2876. GLTFLoader.prototype.dispose = function () {
  2877. if (this._disposed) {
  2878. return;
  2879. }
  2880. this._disposed = true;
  2881. this.onDisposeObservable.notifyObservers(this);
  2882. this.onDisposeObservable.clear();
  2883. this._clear();
  2884. };
  2885. /**
  2886. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2887. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2888. * @param scene the scene the meshes should be added to
  2889. * @param data gltf data containing information of the meshes in a loaded file
  2890. * @param rootUrl root url to load from
  2891. * @param onProgress event that fires when loading progress has occured
  2892. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2893. */
  2894. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2895. var _this = this;
  2896. return Promise.resolve().then(function () {
  2897. var nodes = null;
  2898. if (meshesNames) {
  2899. var nodeMap_1 = {};
  2900. if (_this._gltf.nodes) {
  2901. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2902. var node = _a[_i];
  2903. if (node.name) {
  2904. nodeMap_1[node.name] = node;
  2905. }
  2906. }
  2907. }
  2908. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2909. nodes = names.map(function (name) {
  2910. var node = nodeMap_1[name];
  2911. if (!node) {
  2912. throw new Error("Failed to find node '" + name + "'");
  2913. }
  2914. return node;
  2915. });
  2916. }
  2917. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2918. return {
  2919. meshes: _this._getMeshes(),
  2920. particleSystems: [],
  2921. skeletons: _this._getSkeletons(),
  2922. animationGroups: _this._getAnimationGroups()
  2923. };
  2924. });
  2925. });
  2926. };
  2927. /**
  2928. * Imports all objects from a loaded gltf file and adds them to the scene
  2929. * @param scene the scene the objects should be added to
  2930. * @param data gltf data containing information of the meshes in a loaded file
  2931. * @param rootUrl root url to load from
  2932. * @param onProgress event that fires when loading progress has occured
  2933. * @returns a promise which completes when objects have been loaded to the scene
  2934. */
  2935. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2936. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2937. };
  2938. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2939. var _this = this;
  2940. return Promise.resolve().then(function () {
  2941. _this._loadExtensions();
  2942. _this._babylonScene = scene;
  2943. _this._rootUrl = rootUrl;
  2944. _this._progressCallback = onProgress;
  2945. _this._state = BABYLON.GLTFLoaderState.LOADING;
  2946. _this._loadData(data);
  2947. _this._checkExtensions();
  2948. var promises = new Array();
  2949. if (nodes) {
  2950. promises.push(_this._loadNodesAsync(nodes));
  2951. }
  2952. else {
  2953. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2954. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2955. }
  2956. if (_this.compileMaterials) {
  2957. promises.push(_this._compileMaterialsAsync());
  2958. }
  2959. if (_this.compileShadowGenerators) {
  2960. promises.push(_this._compileShadowGeneratorsAsync());
  2961. }
  2962. var resultPromise = Promise.all(promises).then(function () {
  2963. _this._state = BABYLON.GLTFLoaderState.READY;
  2964. _this._startAnimations();
  2965. });
  2966. resultPromise.then(function () {
  2967. _this._rootBabylonMesh.setEnabled(true);
  2968. BABYLON.Tools.SetImmediate(function () {
  2969. if (!_this._disposed) {
  2970. Promise.all(_this._completePromises).then(function () {
  2971. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  2972. _this.onCompleteObservable.notifyObservers(_this);
  2973. _this.onCompleteObservable.clear();
  2974. _this._clear();
  2975. }).catch(function (error) {
  2976. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2977. _this._clear();
  2978. });
  2979. }
  2980. });
  2981. });
  2982. return resultPromise;
  2983. }).catch(function (error) {
  2984. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2985. _this._clear();
  2986. throw error;
  2987. });
  2988. };
  2989. GLTFLoader.prototype._loadExtensions = function () {
  2990. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2991. var name_1 = _a[_i];
  2992. var extension = GLTFLoader._Factories[name_1](this);
  2993. this._extensions[name_1] = extension;
  2994. this.onExtensionLoadedObservable.notifyObservers(extension);
  2995. }
  2996. this.onExtensionLoadedObservable.clear();
  2997. };
  2998. GLTFLoader.prototype._loadData = function (data) {
  2999. this._gltf = data.json;
  3000. this._setupData();
  3001. if (data.bin) {
  3002. var buffers = this._gltf.buffers;
  3003. if (buffers && buffers[0] && !buffers[0].uri) {
  3004. var binaryBuffer = buffers[0];
  3005. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3006. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3007. }
  3008. binaryBuffer._data = Promise.resolve(data.bin);
  3009. }
  3010. else {
  3011. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3012. }
  3013. }
  3014. };
  3015. GLTFLoader.prototype._setupData = function () {
  3016. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  3017. GLTF2.ArrayItem.Assign(this._gltf.animations);
  3018. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  3019. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  3020. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  3021. GLTF2.ArrayItem.Assign(this._gltf.images);
  3022. GLTF2.ArrayItem.Assign(this._gltf.materials);
  3023. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  3024. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  3025. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  3026. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  3027. GLTF2.ArrayItem.Assign(this._gltf.skins);
  3028. GLTF2.ArrayItem.Assign(this._gltf.textures);
  3029. if (this._gltf.nodes) {
  3030. var nodeParents = {};
  3031. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  3032. var node = _a[_i];
  3033. if (node.children) {
  3034. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3035. var index = _c[_b];
  3036. nodeParents[index] = node._index;
  3037. }
  3038. }
  3039. }
  3040. var rootNode = this._createRootNode();
  3041. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  3042. var node = _e[_d];
  3043. var parentIndex = nodeParents[node._index];
  3044. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  3045. }
  3046. }
  3047. };
  3048. GLTFLoader.prototype._checkExtensions = function () {
  3049. if (this._gltf.extensionsRequired) {
  3050. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  3051. var name_2 = _a[_i];
  3052. var extension = this._extensions[name_2];
  3053. if (!extension || !extension.enabled) {
  3054. throw new Error("Require extension " + name_2 + " is not available");
  3055. }
  3056. }
  3057. }
  3058. };
  3059. GLTFLoader.prototype._createRootNode = function () {
  3060. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  3061. this._rootBabylonMesh.setEnabled(false);
  3062. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  3063. switch (this.coordinateSystemMode) {
  3064. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  3065. if (!this._babylonScene.useRightHandedSystem) {
  3066. rootNode.rotation = [0, 1, 0, 0];
  3067. rootNode.scale = [1, 1, -1];
  3068. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  3069. }
  3070. break;
  3071. }
  3072. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  3073. this._babylonScene.useRightHandedSystem = true;
  3074. break;
  3075. }
  3076. default: {
  3077. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  3078. }
  3079. }
  3080. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  3081. return rootNode;
  3082. };
  3083. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  3084. var promises = new Array();
  3085. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  3086. var node = nodes_1[_i];
  3087. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3088. }
  3089. promises.push(this._loadAnimationsAsync());
  3090. return Promise.all(promises).then(function () { });
  3091. };
  3092. /**
  3093. * @ignore
  3094. */
  3095. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  3096. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  3097. if (promise) {
  3098. return promise;
  3099. }
  3100. var promises = new Array();
  3101. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  3102. var index = _a[_i];
  3103. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  3104. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3105. }
  3106. promises.push(this._loadAnimationsAsync());
  3107. return Promise.all(promises).then(function () { });
  3108. };
  3109. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  3110. if (node._primitiveBabylonMeshes) {
  3111. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3112. var babylonMesh = _a[_i];
  3113. callback(babylonMesh);
  3114. }
  3115. }
  3116. else {
  3117. callback(node._babylonMesh);
  3118. }
  3119. };
  3120. GLTFLoader.prototype._getMeshes = function () {
  3121. var meshes = new Array();
  3122. // Root mesh is always first.
  3123. meshes.push(this._rootBabylonMesh);
  3124. var nodes = this._gltf.nodes;
  3125. if (nodes) {
  3126. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  3127. var node = nodes_2[_i];
  3128. if (node._babylonMesh) {
  3129. meshes.push(node._babylonMesh);
  3130. }
  3131. if (node._primitiveBabylonMeshes) {
  3132. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  3133. var babylonMesh = _b[_a];
  3134. meshes.push(babylonMesh);
  3135. }
  3136. }
  3137. }
  3138. }
  3139. return meshes;
  3140. };
  3141. GLTFLoader.prototype._getSkeletons = function () {
  3142. var skeletons = new Array();
  3143. var skins = this._gltf.skins;
  3144. if (skins) {
  3145. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  3146. var skin = skins_1[_i];
  3147. if (skin._babylonSkeleton) {
  3148. skeletons.push(skin._babylonSkeleton);
  3149. }
  3150. }
  3151. }
  3152. return skeletons;
  3153. };
  3154. GLTFLoader.prototype._getAnimationGroups = function () {
  3155. var animationGroups = new Array();
  3156. var animations = this._gltf.animations;
  3157. if (animations) {
  3158. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  3159. var animation = animations_1[_i];
  3160. if (animation._babylonAnimationGroup) {
  3161. animationGroups.push(animation._babylonAnimationGroup);
  3162. }
  3163. }
  3164. }
  3165. return animationGroups;
  3166. };
  3167. GLTFLoader.prototype._startAnimations = function () {
  3168. switch (this.animationStartMode) {
  3169. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  3170. // do nothing
  3171. break;
  3172. }
  3173. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  3174. var babylonAnimationGroups = this._getAnimationGroups();
  3175. if (babylonAnimationGroups.length !== 0) {
  3176. babylonAnimationGroups[0].start(true);
  3177. }
  3178. break;
  3179. }
  3180. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3181. var babylonAnimationGroups = this._getAnimationGroups();
  3182. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  3183. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  3184. babylonAnimationGroup.start(true);
  3185. }
  3186. break;
  3187. }
  3188. default: {
  3189. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  3190. return;
  3191. }
  3192. }
  3193. };
  3194. /**
  3195. * @ignore
  3196. */
  3197. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  3198. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  3199. if (promise) {
  3200. return promise;
  3201. }
  3202. if (node._babylonMesh) {
  3203. throw new Error(context + ": Invalid recursive node hierarchy");
  3204. }
  3205. var promises = new Array();
  3206. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3207. node._babylonMesh = babylonMesh;
  3208. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3209. node._babylonAnimationTargets.push(babylonMesh);
  3210. GLTFLoader._LoadTransform(node, babylonMesh);
  3211. if (node.mesh != undefined) {
  3212. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3213. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  3214. }
  3215. if (node.children) {
  3216. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3217. var index = _a[_i];
  3218. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3219. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3220. }
  3221. }
  3222. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3223. return Promise.all(promises).then(function () { });
  3224. };
  3225. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  3226. var _this = this;
  3227. var promises = new Array();
  3228. var primitives = mesh.primitives;
  3229. if (!primitives || primitives.length === 0) {
  3230. throw new Error(context + ": Primitives are missing");
  3231. }
  3232. GLTF2.ArrayItem.Assign(primitives);
  3233. if (primitives.length === 1) {
  3234. var primitive = primitives[0];
  3235. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  3236. }
  3237. else {
  3238. node._primitiveBabylonMeshes = [];
  3239. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3240. var primitive = primitives_1[_i];
  3241. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  3242. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  3243. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  3244. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3245. }
  3246. }
  3247. if (node.skin != undefined) {
  3248. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3249. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3250. }
  3251. return Promise.all(promises).then(function () {
  3252. _this._forEachPrimitive(node, function (babylonMesh) {
  3253. babylonMesh._refreshBoundingInfo(true);
  3254. });
  3255. });
  3256. };
  3257. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  3258. var _this = this;
  3259. var promises = new Array();
  3260. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3261. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  3262. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  3263. babylonGeometry.applyToMesh(babylonMesh);
  3264. });
  3265. }));
  3266. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  3267. if (primitive.material == undefined) {
  3268. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  3269. }
  3270. else {
  3271. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  3272. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3273. babylonMesh.material = babylonMaterial;
  3274. }));
  3275. }
  3276. return Promise.all(promises).then(function () { });
  3277. };
  3278. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3279. var _this = this;
  3280. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3281. if (promise) {
  3282. return promise;
  3283. }
  3284. var attributes = primitive.attributes;
  3285. if (!attributes) {
  3286. throw new Error(context + ": Attributes are missing");
  3287. }
  3288. var promises = new Array();
  3289. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  3290. if (primitive.indices == undefined) {
  3291. babylonMesh.isUnIndexed = true;
  3292. }
  3293. else {
  3294. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3295. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3296. babylonGeometry.setIndices(data);
  3297. }));
  3298. }
  3299. var loadAttribute = function (attribute, kind, callback) {
  3300. if (attributes[attribute] == undefined) {
  3301. return;
  3302. }
  3303. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3304. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3305. babylonMesh._delayInfo.push(kind);
  3306. }
  3307. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3308. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  3309. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  3310. }));
  3311. if (callback) {
  3312. callback(accessor);
  3313. }
  3314. };
  3315. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3316. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3317. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3318. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3319. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3320. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3321. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3322. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  3323. if (accessor.type === "VEC4" /* VEC4 */) {
  3324. babylonMesh.hasVertexAlpha = true;
  3325. }
  3326. });
  3327. return Promise.all(promises).then(function () {
  3328. return babylonGeometry;
  3329. });
  3330. };
  3331. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3332. if (!primitive.targets) {
  3333. return;
  3334. }
  3335. if (node._numMorphTargets == undefined) {
  3336. node._numMorphTargets = primitive.targets.length;
  3337. }
  3338. else if (primitive.targets.length !== node._numMorphTargets) {
  3339. throw new Error(context + ": Primitives do not have the same number of targets");
  3340. }
  3341. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3342. for (var index = 0; index < primitive.targets.length; index++) {
  3343. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3344. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3345. // TODO: tell the target whether it has positions, normals, tangents
  3346. }
  3347. };
  3348. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  3349. if (!primitive.targets) {
  3350. return Promise.resolve();
  3351. }
  3352. var promises = new Array();
  3353. var morphTargetManager = babylonMesh.morphTargetManager;
  3354. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3355. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3356. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  3357. }
  3358. return Promise.all(promises).then(function () { });
  3359. };
  3360. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  3361. var _this = this;
  3362. var promises = new Array();
  3363. var loadAttribute = function (attribute, kind, setData) {
  3364. if (attributes[attribute] == undefined) {
  3365. return;
  3366. }
  3367. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  3368. if (!babylonVertexBuffer) {
  3369. return;
  3370. }
  3371. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3372. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3373. if (!(data instanceof Float32Array)) {
  3374. throw new Error(context + ": Morph target accessor must have float data");
  3375. }
  3376. setData(babylonVertexBuffer, data);
  3377. }));
  3378. };
  3379. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  3380. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3381. data[index] += value;
  3382. });
  3383. babylonMorphTarget.setPositions(data);
  3384. });
  3385. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  3386. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3387. data[index] += value;
  3388. });
  3389. babylonMorphTarget.setNormals(data);
  3390. });
  3391. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  3392. var dataIndex = 0;
  3393. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3394. // Tangent data for morph targets is stored as xyz delta.
  3395. // The vertexData.tangent is stored as xyzw.
  3396. // So we need to skip every fourth vertexData.tangent.
  3397. if (((index + 1) % 4) !== 0) {
  3398. data[dataIndex++] += value;
  3399. }
  3400. });
  3401. babylonMorphTarget.setTangents(data);
  3402. });
  3403. return Promise.all(promises).then(function () { });
  3404. };
  3405. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3406. var position = BABYLON.Vector3.Zero();
  3407. var rotation = BABYLON.Quaternion.Identity();
  3408. var scaling = BABYLON.Vector3.One();
  3409. if (node.matrix) {
  3410. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3411. matrix.decompose(scaling, rotation, position);
  3412. }
  3413. else {
  3414. if (node.translation)
  3415. position = BABYLON.Vector3.FromArray(node.translation);
  3416. if (node.rotation)
  3417. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3418. if (node.scale)
  3419. scaling = BABYLON.Vector3.FromArray(node.scale);
  3420. }
  3421. babylonNode.position = position;
  3422. babylonNode.rotationQuaternion = rotation;
  3423. babylonNode.scaling = scaling;
  3424. };
  3425. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3426. var _this = this;
  3427. var assignSkeleton = function (skeleton) {
  3428. _this._forEachPrimitive(node, function (babylonMesh) {
  3429. babylonMesh.skeleton = skeleton;
  3430. });
  3431. // Ignore the TRS of skinned nodes.
  3432. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3433. node._babylonMesh.parent = _this._rootBabylonMesh;
  3434. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3435. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3436. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3437. };
  3438. if (skin._loaded) {
  3439. return skin._loaded.then(function () {
  3440. assignSkeleton(skin._babylonSkeleton);
  3441. });
  3442. }
  3443. var skeletonId = "skeleton" + skin._index;
  3444. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  3445. skin._babylonSkeleton = babylonSkeleton;
  3446. this._loadBones(context, skin);
  3447. assignSkeleton(babylonSkeleton);
  3448. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3449. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  3450. }));
  3451. };
  3452. GLTFLoader.prototype._loadBones = function (context, skin) {
  3453. var babylonBones = {};
  3454. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3455. var index = _a[_i];
  3456. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3457. this._loadBone(node, skin, babylonBones);
  3458. }
  3459. };
  3460. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  3461. var babylonBone = babylonBones[node._index];
  3462. if (babylonBone) {
  3463. return babylonBone;
  3464. }
  3465. var babylonParentBone = null;
  3466. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3467. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  3468. }
  3469. var boneIndex = skin.joints.indexOf(node._index);
  3470. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  3471. babylonBones[node._index] = babylonBone;
  3472. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3473. node._babylonAnimationTargets.push(babylonBone);
  3474. return babylonBone;
  3475. };
  3476. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3477. if (skin.inverseBindMatrices == undefined) {
  3478. return Promise.resolve(null);
  3479. }
  3480. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3481. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3482. return data;
  3483. });
  3484. };
  3485. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  3486. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  3487. var babylonBone = _a[_i];
  3488. var baseMatrix = BABYLON.Matrix.Identity();
  3489. var boneIndex = babylonBone._index;
  3490. if (inverseBindMatricesData && boneIndex !== -1) {
  3491. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  3492. baseMatrix.invertToRef(baseMatrix);
  3493. }
  3494. var babylonParentBone = babylonBone.getParent();
  3495. if (babylonParentBone) {
  3496. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3497. }
  3498. babylonBone.updateMatrix(baseMatrix, false, false);
  3499. babylonBone._updateDifferenceMatrix(undefined, false);
  3500. }
  3501. };
  3502. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3503. return node.matrix ?
  3504. BABYLON.Matrix.FromArray(node.matrix) :
  3505. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  3506. };
  3507. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3508. var animations = this._gltf.animations;
  3509. if (!animations) {
  3510. return Promise.resolve();
  3511. }
  3512. var promises = new Array();
  3513. for (var index = 0; index < animations.length; index++) {
  3514. var animation = animations[index];
  3515. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3516. }
  3517. return Promise.all(promises).then(function () { });
  3518. };
  3519. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3520. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3521. animation._babylonAnimationGroup = babylonAnimationGroup;
  3522. var promises = new Array();
  3523. GLTF2.ArrayItem.Assign(animation.channels);
  3524. GLTF2.ArrayItem.Assign(animation.samplers);
  3525. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3526. var channel = _a[_i];
  3527. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3528. }
  3529. return Promise.all(promises).then(function () {
  3530. babylonAnimationGroup.normalize();
  3531. });
  3532. };
  3533. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3534. var _this = this;
  3535. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3536. if (!targetNode._babylonMesh) {
  3537. return Promise.resolve();
  3538. }
  3539. // Ignore animations targeting TRS of skinned nodes.
  3540. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3541. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  3542. return Promise.resolve();
  3543. }
  3544. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3545. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3546. var targetPath;
  3547. var animationType;
  3548. switch (channel.target.path) {
  3549. case "translation" /* TRANSLATION */: {
  3550. targetPath = "position";
  3551. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3552. break;
  3553. }
  3554. case "rotation" /* ROTATION */: {
  3555. targetPath = "rotationQuaternion";
  3556. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3557. break;
  3558. }
  3559. case "scale" /* SCALE */: {
  3560. targetPath = "scaling";
  3561. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3562. break;
  3563. }
  3564. case "weights" /* WEIGHTS */: {
  3565. targetPath = "influence";
  3566. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3567. break;
  3568. }
  3569. default: {
  3570. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  3571. }
  3572. }
  3573. var outputBufferOffset = 0;
  3574. var getNextOutputValue;
  3575. switch (targetPath) {
  3576. case "position": {
  3577. getNextOutputValue = function () {
  3578. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3579. outputBufferOffset += 3;
  3580. return value;
  3581. };
  3582. break;
  3583. }
  3584. case "rotationQuaternion": {
  3585. getNextOutputValue = function () {
  3586. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3587. outputBufferOffset += 4;
  3588. return value;
  3589. };
  3590. break;
  3591. }
  3592. case "scaling": {
  3593. getNextOutputValue = function () {
  3594. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3595. outputBufferOffset += 3;
  3596. return value;
  3597. };
  3598. break;
  3599. }
  3600. case "influence": {
  3601. getNextOutputValue = function () {
  3602. var value = new Array(targetNode._numMorphTargets);
  3603. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3604. value[i] = data.output[outputBufferOffset++];
  3605. }
  3606. return value;
  3607. };
  3608. break;
  3609. }
  3610. }
  3611. var getNextKey;
  3612. switch (data.interpolation) {
  3613. case "STEP" /* STEP */: {
  3614. getNextKey = function (frameIndex) { return ({
  3615. frame: data.input[frameIndex],
  3616. value: getNextOutputValue(),
  3617. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3618. }); };
  3619. break;
  3620. }
  3621. case "LINEAR" /* LINEAR */: {
  3622. getNextKey = function (frameIndex) { return ({
  3623. frame: data.input[frameIndex],
  3624. value: getNextOutputValue()
  3625. }); };
  3626. break;
  3627. }
  3628. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3629. getNextKey = function (frameIndex) { return ({
  3630. frame: data.input[frameIndex],
  3631. inTangent: getNextOutputValue(),
  3632. value: getNextOutputValue(),
  3633. outTangent: getNextOutputValue()
  3634. }); };
  3635. break;
  3636. }
  3637. }
  3638. var keys = new Array(data.input.length);
  3639. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3640. keys[frameIndex] = getNextKey(frameIndex);
  3641. }
  3642. if (targetPath === "influence") {
  3643. var _loop_1 = function (targetIndex) {
  3644. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3645. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3646. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3647. frame: key.frame,
  3648. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3649. value: key.value[targetIndex],
  3650. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3651. }); }));
  3652. var morphTargets = new Array();
  3653. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  3654. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3655. morphTarget.animations.push(babylonAnimation);
  3656. morphTargets.push(morphTarget);
  3657. });
  3658. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  3659. };
  3660. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3661. _loop_1(targetIndex);
  3662. }
  3663. }
  3664. else {
  3665. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3666. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3667. babylonAnimation.setKeys(keys);
  3668. if (targetNode._babylonAnimationTargets) {
  3669. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3670. var babylonAnimationTarget = _a[_i];
  3671. babylonAnimationTarget.animations.push(babylonAnimation);
  3672. }
  3673. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  3674. }
  3675. }
  3676. });
  3677. };
  3678. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3679. if (sampler._data) {
  3680. return sampler._data;
  3681. }
  3682. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3683. switch (interpolation) {
  3684. case "STEP" /* STEP */:
  3685. case "LINEAR" /* LINEAR */:
  3686. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3687. break;
  3688. }
  3689. default: {
  3690. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  3691. }
  3692. }
  3693. var inputData;
  3694. var outputData;
  3695. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3696. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3697. sampler._data = Promise.all([
  3698. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3699. inputData = data;
  3700. }),
  3701. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3702. outputData = data;
  3703. })
  3704. ]).then(function () {
  3705. return {
  3706. input: inputData,
  3707. interpolation: interpolation,
  3708. output: outputData,
  3709. };
  3710. });
  3711. return sampler._data;
  3712. };
  3713. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3714. if (buffer._data) {
  3715. return buffer._data;
  3716. }
  3717. if (!buffer.uri) {
  3718. throw new Error(context + ": Uri is missing");
  3719. }
  3720. buffer._data = this._loadUriAsync(context, buffer.uri);
  3721. return buffer._data;
  3722. };
  3723. /**
  3724. * @ignore
  3725. */
  3726. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3727. if (bufferView._data) {
  3728. return bufferView._data;
  3729. }
  3730. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3731. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  3732. try {
  3733. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3734. }
  3735. catch (e) {
  3736. throw new Error(context + ": " + e.message);
  3737. }
  3738. });
  3739. return bufferView._data;
  3740. };
  3741. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3742. if (accessor.sparse) {
  3743. throw new Error(context + ": Sparse accessors are not currently supported");
  3744. }
  3745. if (accessor._data) {
  3746. return accessor._data;
  3747. }
  3748. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3749. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  3750. var buffer = data.buffer;
  3751. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  3752. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  3753. try {
  3754. switch (accessor.componentType) {
  3755. case 5120 /* BYTE */: {
  3756. return new Int8Array(buffer, byteOffset, length);
  3757. }
  3758. case 5121 /* UNSIGNED_BYTE */: {
  3759. return new Uint8Array(buffer, byteOffset, length);
  3760. }
  3761. case 5122 /* SHORT */: {
  3762. return new Int16Array(buffer, byteOffset, length);
  3763. }
  3764. case 5123 /* UNSIGNED_SHORT */: {
  3765. return new Uint16Array(buffer, byteOffset, length);
  3766. }
  3767. case 5125 /* UNSIGNED_INT */: {
  3768. return new Uint32Array(buffer, byteOffset, length);
  3769. }
  3770. case 5126 /* FLOAT */: {
  3771. return new Float32Array(buffer, byteOffset, length);
  3772. }
  3773. default: {
  3774. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  3775. }
  3776. }
  3777. }
  3778. catch (e) {
  3779. throw new Error(context + ": " + e);
  3780. }
  3781. });
  3782. return accessor._data;
  3783. };
  3784. /**
  3785. * @ignore
  3786. */
  3787. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  3788. var _this = this;
  3789. if (bufferView._babylonBuffer) {
  3790. return bufferView._babylonBuffer;
  3791. }
  3792. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  3793. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  3794. });
  3795. return bufferView._babylonBuffer;
  3796. };
  3797. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  3798. var _this = this;
  3799. if (accessor.sparse) {
  3800. throw new Error(context + ": Sparse accessors are not currently supported");
  3801. }
  3802. if (accessor._babylonVertexBuffer) {
  3803. return accessor._babylonVertexBuffer;
  3804. }
  3805. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3806. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  3807. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  3808. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  3809. });
  3810. return accessor._babylonVertexBuffer;
  3811. };
  3812. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  3813. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  3814. if (!babylonMaterial) {
  3815. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  3816. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3817. babylonMaterial.metallic = 1;
  3818. babylonMaterial.roughness = 1;
  3819. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3820. }
  3821. return babylonMaterial;
  3822. };
  3823. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  3824. var promises = new Array();
  3825. // Ensure metallic workflow
  3826. babylonMaterial.metallic = 1;
  3827. babylonMaterial.roughness = 1;
  3828. var properties = material.pbrMetallicRoughness;
  3829. if (properties) {
  3830. if (properties.baseColorFactor) {
  3831. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3832. babylonMaterial.alpha = properties.baseColorFactor[3];
  3833. }
  3834. else {
  3835. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3836. }
  3837. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3838. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3839. if (properties.baseColorTexture) {
  3840. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3841. babylonMaterial.albedoTexture = texture;
  3842. }));
  3843. }
  3844. if (properties.metallicRoughnessTexture) {
  3845. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3846. babylonMaterial.metallicTexture = texture;
  3847. }));
  3848. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3849. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3850. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3851. }
  3852. }
  3853. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3854. return Promise.all(promises).then(function () { });
  3855. };
  3856. /**
  3857. * @ignore
  3858. */
  3859. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  3860. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  3861. if (promise) {
  3862. return promise;
  3863. }
  3864. material._babylonData = material._babylonData || {};
  3865. var babylonData = material._babylonData[babylonDrawMode];
  3866. if (!babylonData) {
  3867. var promises = new Array();
  3868. var name_3 = material.name || "materialSG_" + material._index;
  3869. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  3870. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3871. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  3872. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3873. babylonData = {
  3874. material: babylonMaterial,
  3875. meshes: [],
  3876. loaded: Promise.all(promises).then(function () { })
  3877. };
  3878. material._babylonData[babylonDrawMode] = babylonData;
  3879. }
  3880. babylonData.meshes.push(babylonMesh);
  3881. assign(babylonData.material);
  3882. return babylonData.loaded;
  3883. };
  3884. /**
  3885. * @ignore
  3886. */
  3887. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  3888. var babylonMaterial = new type(name, this._babylonScene);
  3889. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3890. babylonMaterial.fillMode = drawMode;
  3891. return babylonMaterial;
  3892. };
  3893. /**
  3894. * @ignore
  3895. */
  3896. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  3897. var promises = new Array();
  3898. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3899. if (material.doubleSided) {
  3900. babylonMaterial.backFaceCulling = false;
  3901. babylonMaterial.twoSidedLighting = true;
  3902. }
  3903. if (material.normalTexture) {
  3904. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3905. babylonMaterial.bumpTexture = texture;
  3906. }));
  3907. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3908. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3909. if (material.normalTexture.scale != undefined) {
  3910. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3911. }
  3912. }
  3913. if (material.occlusionTexture) {
  3914. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3915. babylonMaterial.ambientTexture = texture;
  3916. }));
  3917. babylonMaterial.useAmbientInGrayScale = true;
  3918. if (material.occlusionTexture.strength != undefined) {
  3919. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3920. }
  3921. }
  3922. if (material.emissiveTexture) {
  3923. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3924. babylonMaterial.emissiveTexture = texture;
  3925. }));
  3926. }
  3927. return Promise.all(promises).then(function () { });
  3928. };
  3929. /**
  3930. * @ignore
  3931. */
  3932. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  3933. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3934. switch (alphaMode) {
  3935. case "OPAQUE" /* OPAQUE */: {
  3936. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3937. break;
  3938. }
  3939. case "MASK" /* MASK */: {
  3940. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3941. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3942. if (babylonMaterial.albedoTexture) {
  3943. babylonMaterial.albedoTexture.hasAlpha = true;
  3944. }
  3945. break;
  3946. }
  3947. case "BLEND" /* BLEND */: {
  3948. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3949. if (babylonMaterial.albedoTexture) {
  3950. babylonMaterial.albedoTexture.hasAlpha = true;
  3951. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3952. }
  3953. break;
  3954. }
  3955. default: {
  3956. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  3957. }
  3958. }
  3959. };
  3960. /**
  3961. * @ignore
  3962. */
  3963. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3964. var _this = this;
  3965. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3966. context = "#/textures/" + textureInfo.index;
  3967. var promises = new Array();
  3968. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3969. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3970. var deferred = new BABYLON.Deferred();
  3971. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3972. if (!_this._disposed) {
  3973. deferred.resolve();
  3974. }
  3975. }, function (message, exception) {
  3976. if (!_this._disposed) {
  3977. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  3978. }
  3979. });
  3980. promises.push(deferred.promise);
  3981. babylonTexture.name = texture.name || "texture" + texture._index;
  3982. babylonTexture.wrapU = samplerData.wrapU;
  3983. babylonTexture.wrapV = samplerData.wrapV;
  3984. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3985. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3986. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3987. babylonTexture.updateURL(objectURL);
  3988. }));
  3989. assign(babylonTexture);
  3990. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3991. return Promise.all(promises).then(function () { });
  3992. };
  3993. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3994. if (!sampler._data) {
  3995. sampler._data = {
  3996. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3997. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3998. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3999. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  4000. };
  4001. }
  4002. ;
  4003. return sampler._data;
  4004. };
  4005. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  4006. if (image._objectURL) {
  4007. return image._objectURL;
  4008. }
  4009. var promise;
  4010. if (image.uri) {
  4011. promise = this._loadUriAsync(context, image.uri);
  4012. }
  4013. else {
  4014. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  4015. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  4016. }
  4017. image._objectURL = promise.then(function (data) {
  4018. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  4019. });
  4020. return image._objectURL;
  4021. };
  4022. /**
  4023. * @ignore
  4024. */
  4025. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  4026. var _this = this;
  4027. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  4028. if (promise) {
  4029. return promise;
  4030. }
  4031. if (!GLTFLoader._ValidateUri(uri)) {
  4032. throw new Error(context + ": Uri '" + uri + "' is invalid");
  4033. }
  4034. if (BABYLON.Tools.IsBase64(uri)) {
  4035. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  4036. }
  4037. return new Promise(function (resolve, reject) {
  4038. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  4039. if (!_this._disposed) {
  4040. resolve(new Uint8Array(data));
  4041. }
  4042. }, function (event) {
  4043. if (!_this._disposed) {
  4044. try {
  4045. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  4046. request._lengthComputable = event.lengthComputable;
  4047. request._loaded = event.loaded;
  4048. request._total = event.total;
  4049. _this._onProgress();
  4050. }
  4051. }
  4052. catch (e) {
  4053. reject(e);
  4054. }
  4055. }
  4056. }, _this._babylonScene.database, true, function (request, exception) {
  4057. if (!_this._disposed) {
  4058. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  4059. }
  4060. });
  4061. _this._requests.push(request);
  4062. });
  4063. };
  4064. GLTFLoader.prototype._onProgress = function () {
  4065. if (!this._progressCallback) {
  4066. return;
  4067. }
  4068. var lengthComputable = true;
  4069. var loaded = 0;
  4070. var total = 0;
  4071. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4072. var request = _a[_i];
  4073. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  4074. return;
  4075. }
  4076. lengthComputable = lengthComputable && request._lengthComputable;
  4077. loaded += request._loaded;
  4078. total += request._total;
  4079. }
  4080. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  4081. };
  4082. /**
  4083. * @ignore
  4084. */
  4085. GLTFLoader._GetProperty = function (context, array, index) {
  4086. if (!array || index == undefined || !array[index]) {
  4087. throw new Error(context + ": Failed to find index (" + index + ")");
  4088. }
  4089. return array[index];
  4090. };
  4091. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  4092. // Set defaults if undefined
  4093. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  4094. switch (mode) {
  4095. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4096. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4097. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4098. default:
  4099. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  4100. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4101. }
  4102. };
  4103. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  4104. // Set defaults if undefined
  4105. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  4106. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  4107. if (magFilter === 9729 /* LINEAR */) {
  4108. switch (minFilter) {
  4109. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  4110. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  4111. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4112. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4113. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4114. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4115. default:
  4116. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  4117. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4118. }
  4119. }
  4120. else {
  4121. if (magFilter !== 9728 /* NEAREST */) {
  4122. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  4123. }
  4124. switch (minFilter) {
  4125. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  4126. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  4127. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4128. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4129. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4130. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4131. default:
  4132. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  4133. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4134. }
  4135. }
  4136. };
  4137. GLTFLoader._GetNumComponents = function (context, type) {
  4138. switch (type) {
  4139. case "SCALAR": return 1;
  4140. case "VEC2": return 2;
  4141. case "VEC3": return 3;
  4142. case "VEC4": return 4;
  4143. case "MAT2": return 4;
  4144. case "MAT3": return 9;
  4145. case "MAT4": return 16;
  4146. }
  4147. throw new Error(context + ": Invalid type (" + type + ")");
  4148. };
  4149. GLTFLoader._ValidateUri = function (uri) {
  4150. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  4151. };
  4152. GLTFLoader._GetDrawMode = function (context, mode) {
  4153. if (mode == undefined) {
  4154. mode = 4 /* TRIANGLES */;
  4155. }
  4156. switch (mode) {
  4157. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  4158. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  4159. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  4160. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  4161. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  4162. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  4163. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  4164. }
  4165. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  4166. };
  4167. GLTFLoader.prototype._compileMaterialsAsync = function () {
  4168. var promises = new Array();
  4169. if (this._gltf.materials) {
  4170. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  4171. var material = _a[_i];
  4172. if (material._babylonData) {
  4173. for (var babylonDrawMode in material._babylonData) {
  4174. var babylonData = material._babylonData[babylonDrawMode];
  4175. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  4176. var babylonMesh = _c[_b];
  4177. // Ensure nonUniformScaling is set if necessary.
  4178. babylonMesh.computeWorldMatrix(true);
  4179. var babylonMaterial = babylonData.material;
  4180. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  4181. if (this.useClipPlane) {
  4182. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  4183. }
  4184. }
  4185. }
  4186. }
  4187. }
  4188. }
  4189. return Promise.all(promises).then(function () { });
  4190. };
  4191. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  4192. var promises = new Array();
  4193. var lights = this._babylonScene.lights;
  4194. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  4195. var light = lights_1[_i];
  4196. var generator = light.getShadowGenerator();
  4197. if (generator) {
  4198. promises.push(generator.forceCompilationAsync());
  4199. }
  4200. }
  4201. return Promise.all(promises).then(function () { });
  4202. };
  4203. GLTFLoader.prototype._clear = function () {
  4204. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4205. var request = _a[_i];
  4206. request.abort();
  4207. }
  4208. this._requests.length = 0;
  4209. if (this._gltf && this._gltf.images) {
  4210. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  4211. var image = _c[_b];
  4212. if (image._objectURL) {
  4213. image._objectURL.then(function (value) {
  4214. URL.revokeObjectURL(value);
  4215. });
  4216. image._objectURL = undefined;
  4217. }
  4218. }
  4219. }
  4220. delete this._gltf;
  4221. delete this._babylonScene;
  4222. this._completePromises.length = 0;
  4223. for (var name_4 in this._extensions) {
  4224. this._extensions[name_4].dispose();
  4225. }
  4226. this._extensions = {};
  4227. delete this._rootBabylonMesh;
  4228. delete this._progressCallback;
  4229. this.onMeshLoadedObservable.clear();
  4230. this.onTextureLoadedObservable.clear();
  4231. this.onMaterialLoadedObservable.clear();
  4232. };
  4233. /**
  4234. * @ignore
  4235. */
  4236. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4237. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4238. var name_5 = _a[_i];
  4239. var extension = this._extensions[name_5];
  4240. if (extension.enabled) {
  4241. var promise = actionAsync(extension);
  4242. if (promise) {
  4243. return promise;
  4244. }
  4245. }
  4246. }
  4247. return null;
  4248. };
  4249. GLTFLoader._Names = new Array();
  4250. GLTFLoader._Factories = {};
  4251. return GLTFLoader;
  4252. }());
  4253. GLTF2.GLTFLoader = GLTFLoader;
  4254. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4255. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4256. })(BABYLON || (BABYLON = {}));
  4257. //# sourceMappingURL=babylon.glTFLoader.js.map
  4258. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4259. var BABYLON;
  4260. (function (BABYLON) {
  4261. var GLTF2;
  4262. (function (GLTF2) {
  4263. /**
  4264. * Abstract class that can be implemented to extend existing gltf loader behavior.
  4265. */
  4266. var GLTFLoaderExtension = /** @class */ (function () {
  4267. function GLTFLoaderExtension(loader) {
  4268. this.enabled = true;
  4269. this._loader = loader;
  4270. }
  4271. GLTFLoaderExtension.prototype.dispose = function () {
  4272. delete this._loader;
  4273. };
  4274. // #region Overridable Methods
  4275. /** Override this method to modify the default behavior for loading scenes. */
  4276. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4277. /** Override this method to modify the default behavior for loading nodes. */
  4278. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4279. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4280. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4281. /** Override this method to modify the default behavior for loading materials. */
  4282. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  4283. /** Override this method to modify the default behavior for loading uris. */
  4284. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4285. // #endregion
  4286. /** Helper method called by a loader extension to load an glTF extension. */
  4287. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4288. if (!property.extensions) {
  4289. return null;
  4290. }
  4291. var extensions = property.extensions;
  4292. var extension = extensions[this.name];
  4293. if (!extension) {
  4294. return null;
  4295. }
  4296. // Clear out the extension before executing the action to avoid recursing into the same property.
  4297. delete extensions[this.name];
  4298. try {
  4299. return actionAsync(context + "/extensions/" + this.name, extension);
  4300. }
  4301. finally {
  4302. // Restore the extension after executing the action.
  4303. extensions[this.name] = extension;
  4304. }
  4305. };
  4306. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4307. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4308. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4309. };
  4310. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4311. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4312. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4313. };
  4314. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  4315. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  4316. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4317. };
  4318. /** Helper method called by the loader to allow extensions to override loading materials. */
  4319. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  4320. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  4321. };
  4322. /** Helper method called by the loader to allow extensions to override loading uris. */
  4323. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4324. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4325. };
  4326. return GLTFLoaderExtension;
  4327. }());
  4328. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4329. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4332. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4333. var __extends = (this && this.__extends) || (function () {
  4334. var extendStatics = Object.setPrototypeOf ||
  4335. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4336. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4337. return function (d, b) {
  4338. extendStatics(d, b);
  4339. function __() { this.constructor = d; }
  4340. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4341. };
  4342. })();
  4343. var BABYLON;
  4344. (function (BABYLON) {
  4345. var GLTF2;
  4346. (function (GLTF2) {
  4347. var Extensions;
  4348. (function (Extensions) {
  4349. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  4350. var NAME = "MSFT_lod";
  4351. var MSFT_lod = /** @class */ (function (_super) {
  4352. __extends(MSFT_lod, _super);
  4353. function MSFT_lod() {
  4354. var _this = _super !== null && _super.apply(this, arguments) || this;
  4355. _this.name = NAME;
  4356. /**
  4357. * Maximum number of LODs to load, starting from the lowest LOD.
  4358. */
  4359. _this.maxLODsToLoad = Number.MAX_VALUE;
  4360. _this._loadingNodeLOD = null;
  4361. _this._loadNodeSignals = {};
  4362. _this._loadingMaterialLOD = null;
  4363. _this._loadMaterialSignals = {};
  4364. return _this;
  4365. }
  4366. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4367. var _this = this;
  4368. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4369. var firstPromise;
  4370. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  4371. var _loop_1 = function (indexLOD) {
  4372. var nodeLOD = nodeLODs[indexLOD];
  4373. if (indexLOD !== 0) {
  4374. _this._loadingNodeLOD = nodeLOD;
  4375. if (!_this._loadNodeSignals[nodeLOD._index]) {
  4376. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4377. }
  4378. }
  4379. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4380. if (indexLOD !== 0) {
  4381. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4382. if (previousNodeLOD._babylonMesh) {
  4383. previousNodeLOD._babylonMesh.dispose(false, true);
  4384. delete previousNodeLOD._babylonMesh;
  4385. }
  4386. }
  4387. if (indexLOD !== nodeLODs.length - 1) {
  4388. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4389. if (_this._loadNodeSignals[nodeIndex]) {
  4390. _this._loadNodeSignals[nodeIndex].resolve();
  4391. delete _this._loadNodeSignals[nodeIndex];
  4392. }
  4393. }
  4394. });
  4395. if (indexLOD === 0) {
  4396. firstPromise = promise;
  4397. }
  4398. else {
  4399. _this._loader._completePromises.push(promise);
  4400. _this._loadingNodeLOD = null;
  4401. }
  4402. };
  4403. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4404. _loop_1(indexLOD);
  4405. }
  4406. return firstPromise;
  4407. });
  4408. };
  4409. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4410. var _this = this;
  4411. // Don't load material LODs if already loading a node LOD.
  4412. if (this._loadingNodeLOD) {
  4413. return null;
  4414. }
  4415. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4416. var firstPromise;
  4417. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  4418. var _loop_2 = function (indexLOD) {
  4419. var materialLOD = materialLODs[indexLOD];
  4420. if (indexLOD !== 0) {
  4421. _this._loadingMaterialLOD = materialLOD;
  4422. if (!_this._loadMaterialSignals[materialLOD._index]) {
  4423. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4424. }
  4425. }
  4426. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  4427. if (indexLOD !== 0) {
  4428. var babylonDataLOD = materialLOD._babylonData;
  4429. assign(babylonDataLOD[babylonDrawMode].material);
  4430. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4431. if (previousBabylonDataLOD[babylonDrawMode]) {
  4432. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4433. delete previousBabylonDataLOD[babylonDrawMode];
  4434. }
  4435. }
  4436. if (indexLOD !== materialLODs.length - 1) {
  4437. var materialIndex = materialLODs[indexLOD + 1]._index;
  4438. if (_this._loadMaterialSignals[materialIndex]) {
  4439. _this._loadMaterialSignals[materialIndex].resolve();
  4440. delete _this._loadMaterialSignals[materialIndex];
  4441. }
  4442. }
  4443. });
  4444. if (indexLOD === 0) {
  4445. firstPromise = promise;
  4446. }
  4447. else {
  4448. _this._loader._completePromises.push(promise);
  4449. _this._loadingMaterialLOD = null;
  4450. }
  4451. };
  4452. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4453. _loop_2(indexLOD);
  4454. }
  4455. return firstPromise;
  4456. });
  4457. };
  4458. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4459. var _this = this;
  4460. // Defer the loading of uris if loading a material or node LOD.
  4461. if (this._loadingMaterialLOD) {
  4462. var index = this._loadingMaterialLOD._index;
  4463. return this._loadMaterialSignals[index].promise.then(function () {
  4464. return _this._loader._loadUriAsync(context, uri);
  4465. });
  4466. }
  4467. else if (this._loadingNodeLOD) {
  4468. var index = this._loadingNodeLOD._index;
  4469. return this._loadNodeSignals[index].promise.then(function () {
  4470. return _this._loader._loadUriAsync(context, uri);
  4471. });
  4472. }
  4473. return null;
  4474. };
  4475. /**
  4476. * Gets an array of LOD properties from lowest to highest.
  4477. */
  4478. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4479. if (this.maxLODsToLoad <= 0) {
  4480. throw new Error("maxLODsToLoad must be greater than zero");
  4481. }
  4482. var properties = new Array();
  4483. for (var i = ids.length - 1; i >= 0; i--) {
  4484. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4485. if (properties.length === this.maxLODsToLoad) {
  4486. return properties;
  4487. }
  4488. }
  4489. properties.push(property);
  4490. return properties;
  4491. };
  4492. return MSFT_lod;
  4493. }(GLTF2.GLTFLoaderExtension));
  4494. Extensions.MSFT_lod = MSFT_lod;
  4495. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4496. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4497. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4498. })(BABYLON || (BABYLON = {}));
  4499. //# sourceMappingURL=MSFT_lod.js.map
  4500. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4501. var __extends = (this && this.__extends) || (function () {
  4502. var extendStatics = Object.setPrototypeOf ||
  4503. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4504. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4505. return function (d, b) {
  4506. extendStatics(d, b);
  4507. function __() { this.constructor = d; }
  4508. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4509. };
  4510. })();
  4511. /** Module defining extensions to gltf */
  4512. var BABYLON;
  4513. (function (BABYLON) {
  4514. var GLTF2;
  4515. (function (GLTF2) {
  4516. var Extensions;
  4517. (function (Extensions) {
  4518. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  4519. var NAME = "KHR_draco_mesh_compression";
  4520. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  4521. __extends(KHR_draco_mesh_compression, _super);
  4522. function KHR_draco_mesh_compression(loader) {
  4523. var _this = _super.call(this, loader) || this;
  4524. _this.name = NAME;
  4525. _this._dracoCompression = null;
  4526. // Disable extension if decoder is not available.
  4527. if (!BABYLON.DracoCompression.DecoderAvailable) {
  4528. _this.enabled = false;
  4529. }
  4530. return _this;
  4531. }
  4532. KHR_draco_mesh_compression.prototype.dispose = function () {
  4533. if (this._dracoCompression) {
  4534. this._dracoCompression.dispose();
  4535. }
  4536. _super.prototype.dispose.call(this);
  4537. };
  4538. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4539. var _this = this;
  4540. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  4541. if (primitive.mode != undefined) {
  4542. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  4543. primitive.mode !== 4 /* TRIANGLES */) {
  4544. throw new Error(context + ": Unsupported mode " + primitive.mode);
  4545. }
  4546. // TODO: handle triangle strips
  4547. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  4548. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  4549. }
  4550. }
  4551. var attributes = {};
  4552. var loadAttribute = function (name, kind) {
  4553. var uniqueId = extension.attributes[name];
  4554. if (uniqueId == undefined) {
  4555. return;
  4556. }
  4557. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4558. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4559. babylonMesh._delayInfo.push(kind);
  4560. }
  4561. attributes[kind] = uniqueId;
  4562. };
  4563. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4564. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4565. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4566. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4567. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4568. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4569. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4570. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4571. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  4572. if (!bufferView._dracoBabylonGeometry) {
  4573. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4574. if (!_this._dracoCompression) {
  4575. _this._dracoCompression = new BABYLON.DracoCompression();
  4576. }
  4577. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  4578. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  4579. babylonVertexData.applyToGeometry(babylonGeometry);
  4580. return babylonGeometry;
  4581. }).catch(function (error) {
  4582. throw new Error(context + ": " + error.message);
  4583. });
  4584. });
  4585. }
  4586. return bufferView._dracoBabylonGeometry;
  4587. });
  4588. };
  4589. return KHR_draco_mesh_compression;
  4590. }(GLTF2.GLTFLoaderExtension));
  4591. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  4592. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  4593. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4594. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4595. })(BABYLON || (BABYLON = {}));
  4596. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  4597. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4598. var __extends = (this && this.__extends) || (function () {
  4599. var extendStatics = Object.setPrototypeOf ||
  4600. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4601. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4602. return function (d, b) {
  4603. extendStatics(d, b);
  4604. function __() { this.constructor = d; }
  4605. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4606. };
  4607. })();
  4608. var BABYLON;
  4609. (function (BABYLON) {
  4610. var GLTF2;
  4611. (function (GLTF2) {
  4612. var Extensions;
  4613. (function (Extensions) {
  4614. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4615. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4616. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4617. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4618. function KHR_materials_pbrSpecularGlossiness() {
  4619. var _this = _super !== null && _super.apply(this, arguments) || this;
  4620. _this.name = NAME;
  4621. return _this;
  4622. }
  4623. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4624. var _this = this;
  4625. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4626. material._babylonData = material._babylonData || {};
  4627. var babylonData = material._babylonData[babylonDrawMode];
  4628. if (!babylonData) {
  4629. var promises = new Array();
  4630. var name_1 = material.name || "materialSG_" + material._index;
  4631. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4632. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4633. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  4634. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4635. babylonData = {
  4636. material: babylonMaterial,
  4637. meshes: [],
  4638. loaded: Promise.all(promises).then(function () { })
  4639. };
  4640. material._babylonData[babylonDrawMode] = babylonData;
  4641. }
  4642. babylonData.meshes.push(babylonMesh);
  4643. assign(babylonData.material);
  4644. return babylonData.loaded;
  4645. });
  4646. };
  4647. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  4648. var promises = new Array();
  4649. if (properties.diffuseFactor) {
  4650. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4651. babylonMaterial.alpha = properties.diffuseFactor[3];
  4652. }
  4653. else {
  4654. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4655. }
  4656. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4657. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4658. if (properties.diffuseTexture) {
  4659. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4660. babylonMaterial.albedoTexture = texture;
  4661. }));
  4662. }
  4663. if (properties.specularGlossinessTexture) {
  4664. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4665. babylonMaterial.reflectivityTexture = texture;
  4666. }));
  4667. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4668. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4669. }
  4670. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4671. return Promise.all(promises).then(function () { });
  4672. };
  4673. return KHR_materials_pbrSpecularGlossiness;
  4674. }(GLTF2.GLTFLoaderExtension));
  4675. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4676. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4677. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4678. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4679. })(BABYLON || (BABYLON = {}));
  4680. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4681. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4682. var __extends = (this && this.__extends) || (function () {
  4683. var extendStatics = Object.setPrototypeOf ||
  4684. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4685. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4686. return function (d, b) {
  4687. extendStatics(d, b);
  4688. function __() { this.constructor = d; }
  4689. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4690. };
  4691. })();
  4692. var BABYLON;
  4693. (function (BABYLON) {
  4694. var GLTF2;
  4695. (function (GLTF2) {
  4696. var Extensions;
  4697. (function (Extensions) {
  4698. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  4699. var NAME = "KHR_materials_unlit";
  4700. var KHR_materials_unlit = /** @class */ (function (_super) {
  4701. __extends(KHR_materials_unlit, _super);
  4702. function KHR_materials_unlit() {
  4703. var _this = _super !== null && _super.apply(this, arguments) || this;
  4704. _this.name = NAME;
  4705. return _this;
  4706. }
  4707. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4708. var _this = this;
  4709. return this._loadExtensionAsync(context, material, function () {
  4710. material._babylonData = material._babylonData || {};
  4711. var babylonData = material._babylonData[babylonDrawMode];
  4712. if (!babylonData) {
  4713. var name_1 = material.name || "materialUnlit_" + material._index;
  4714. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4715. babylonMaterial.unlit = true;
  4716. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  4717. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4718. babylonData = {
  4719. material: babylonMaterial,
  4720. meshes: [],
  4721. loaded: promise
  4722. };
  4723. material._babylonData[babylonDrawMode] = babylonData;
  4724. }
  4725. babylonData.meshes.push(babylonMesh);
  4726. assign(babylonData.material);
  4727. return babylonData.loaded;
  4728. });
  4729. };
  4730. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  4731. var promises = new Array();
  4732. // Ensure metallic workflow
  4733. babylonMaterial.metallic = 1;
  4734. babylonMaterial.roughness = 1;
  4735. var properties = material.pbrMetallicRoughness;
  4736. if (properties) {
  4737. if (properties.baseColorFactor) {
  4738. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4739. babylonMaterial.alpha = properties.baseColorFactor[3];
  4740. }
  4741. else {
  4742. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4743. }
  4744. if (properties.baseColorTexture) {
  4745. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4746. babylonMaterial.albedoTexture = texture;
  4747. }));
  4748. }
  4749. }
  4750. if (material.doubleSided) {
  4751. babylonMaterial.backFaceCulling = false;
  4752. babylonMaterial.twoSidedLighting = true;
  4753. }
  4754. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4755. return Promise.all(promises).then(function () { });
  4756. };
  4757. return KHR_materials_unlit;
  4758. }(GLTF2.GLTFLoaderExtension));
  4759. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  4760. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  4761. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4762. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4763. })(BABYLON || (BABYLON = {}));
  4764. //# sourceMappingURL=KHR_materials_unlit.js.map
  4765. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4766. var __extends = (this && this.__extends) || (function () {
  4767. var extendStatics = Object.setPrototypeOf ||
  4768. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4769. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4770. return function (d, b) {
  4771. extendStatics(d, b);
  4772. function __() { this.constructor = d; }
  4773. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4774. };
  4775. })();
  4776. var BABYLON;
  4777. (function (BABYLON) {
  4778. var GLTF2;
  4779. (function (GLTF2) {
  4780. var Extensions;
  4781. (function (Extensions) {
  4782. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4783. var NAME = "KHR_lights";
  4784. var LightType;
  4785. (function (LightType) {
  4786. LightType["AMBIENT"] = "ambient";
  4787. LightType["DIRECTIONAL"] = "directional";
  4788. LightType["POINT"] = "point";
  4789. LightType["SPOT"] = "spot";
  4790. })(LightType || (LightType = {}));
  4791. var KHR_lights = /** @class */ (function (_super) {
  4792. __extends(KHR_lights, _super);
  4793. function KHR_lights() {
  4794. var _this = _super !== null && _super.apply(this, arguments) || this;
  4795. _this.name = NAME;
  4796. return _this;
  4797. }
  4798. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4799. var _this = this;
  4800. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  4801. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  4802. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4803. if (light.type !== LightType.AMBIENT) {
  4804. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  4805. }
  4806. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4807. return promise;
  4808. });
  4809. };
  4810. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4811. var _this = this;
  4812. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4813. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  4814. var babylonLight;
  4815. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4816. var name = node._babylonMesh.name;
  4817. switch (light.type) {
  4818. case LightType.AMBIENT: {
  4819. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  4820. }
  4821. case LightType.DIRECTIONAL: {
  4822. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4823. break;
  4824. }
  4825. case LightType.POINT: {
  4826. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4827. break;
  4828. }
  4829. case LightType.SPOT: {
  4830. var spotLight = light;
  4831. // TODO: support inner and outer cone angles
  4832. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4833. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4834. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4835. break;
  4836. }
  4837. default: {
  4838. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  4839. }
  4840. }
  4841. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4842. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4843. babylonLight.parent = node._babylonMesh;
  4844. return promise;
  4845. });
  4846. };
  4847. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4848. get: function () {
  4849. var extensions = this._loader._gltf.extensions;
  4850. if (!extensions || !extensions[this.name]) {
  4851. throw new Error("#/extensions: '" + this.name + "' not found");
  4852. }
  4853. var extension = extensions[this.name];
  4854. return extension.lights;
  4855. },
  4856. enumerable: true,
  4857. configurable: true
  4858. });
  4859. return KHR_lights;
  4860. }(GLTF2.GLTFLoaderExtension));
  4861. Extensions.KHR_lights = KHR_lights;
  4862. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4863. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4864. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4865. })(BABYLON || (BABYLON = {}));
  4866. //# sourceMappingURL=KHR_lights.js.map