babylonjs.loaders.js 343 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("babylonjs"));
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-loaders", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  8. else
  9. root["LOADERS"] = factory(root["BABYLON"]);
  10. })(window, function(__WEBPACK_EXTERNAL_MODULE_babylonjs__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "../node_modules/webpack/buildin/global.js":
  99. /*!*************************************************!*\
  100. !*** ../node_modules/webpack/buildin/global.js ***!
  101. \*************************************************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports) {
  104. var g;
  105. // This works in non-strict mode
  106. g = (function() {
  107. return this;
  108. })();
  109. try {
  110. // This works if eval is allowed (see CSP)
  111. g = g || Function("return this")() || (1, eval)("this");
  112. } catch (e) {
  113. // This works if the window reference is available
  114. if (typeof window === "object") g = window;
  115. }
  116. // g can still be undefined, but nothing to do about it...
  117. // We return undefined, instead of nothing here, so it's
  118. // easier to handle this case. if(!global) { ...}
  119. module.exports = g;
  120. /***/ }),
  121. /***/ "./legacy/legacy-glTF.ts":
  122. /*!*******************************!*\
  123. !*** ./legacy/legacy-glTF.ts ***!
  124. \*******************************/
  125. /*! no static exports found */
  126. /***/ (function(module, exports, __webpack_require__) {
  127. "use strict";
  128. /* WEBPACK VAR INJECTION */(function(global) {
  129. function __export(m) {
  130. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  131. }
  132. Object.defineProperty(exports, "__esModule", { value: true });
  133. var FileLoader = __webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  134. /**
  135. * This is the entry point for the UMD module.
  136. * The entry point for a future ESM package should be index.ts
  137. */
  138. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  139. if (typeof globalObject !== "undefined") {
  140. globalObject.BABYLON = globalObject.BABYLON || {};
  141. for (var key in FileLoader) {
  142. globalObject.BABYLON[key] = FileLoader[key];
  143. }
  144. }
  145. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  146. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  147. /***/ }),
  148. /***/ "./legacy/legacy-glTF1.ts":
  149. /*!********************************!*\
  150. !*** ./legacy/legacy-glTF1.ts ***!
  151. \********************************/
  152. /*! no static exports found */
  153. /***/ (function(module, exports, __webpack_require__) {
  154. "use strict";
  155. /* WEBPACK VAR INJECTION */(function(global) {
  156. Object.defineProperty(exports, "__esModule", { value: true });
  157. var GLTF1 = __webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.ts");
  158. exports.GLTF1 = GLTF1;
  159. /**
  160. * This is the entry point for the UMD module.
  161. * The entry point for a future ESM package should be index.ts
  162. */
  163. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  164. if (typeof globalObject !== "undefined") {
  165. globalObject.BABYLON = globalObject.BABYLON || {};
  166. globalObject.BABYLON.GLTF1 = globalObject.BABYLON.GLTF1 || {};
  167. for (var key in GLTF1) {
  168. globalObject.BABYLON.GLTF1[key] = GLTF1[key];
  169. }
  170. }
  171. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  172. /***/ }),
  173. /***/ "./legacy/legacy-glTF2.ts":
  174. /*!********************************!*\
  175. !*** ./legacy/legacy-glTF2.ts ***!
  176. \********************************/
  177. /*! no static exports found */
  178. /***/ (function(module, exports, __webpack_require__) {
  179. "use strict";
  180. /* WEBPACK VAR INJECTION */(function(global) {
  181. Object.defineProperty(exports, "__esModule", { value: true });
  182. var Extensions = __webpack_require__(/*! ../src/glTF/2.0/Extensions */ "./src/glTF/2.0/Extensions/index.ts");
  183. var Interfaces = __webpack_require__(/*! ../src/glTF/2.0/glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts");
  184. var GLTF2 = __webpack_require__(/*! ../src/glTF/2.0 */ "./src/glTF/2.0/index.ts");
  185. exports.GLTF2 = GLTF2;
  186. /**
  187. * This is the entry point for the UMD module.
  188. * The entry point for a future ESM package should be index.ts
  189. */
  190. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  191. if (typeof globalObject !== "undefined") {
  192. globalObject.BABYLON = globalObject.BABYLON || {};
  193. var BABYLON = globalObject.BABYLON;
  194. BABYLON.GLTF2 = BABYLON.GLTF2 || {};
  195. BABYLON.GLTF2.Loader = BABYLON.GLTF2.Loader || {};
  196. BABYLON.GLTF2.Loader.Extensions = BABYLON.GLTF2.Loader.Extensions || {};
  197. var keys = [];
  198. for (var key in Extensions) {
  199. BABYLON.GLTF2.Loader.Extensions[key] = Extensions[key];
  200. keys.push(key);
  201. }
  202. for (var key in Interfaces) {
  203. BABYLON.GLTF2.Loader[key] = Interfaces[key];
  204. keys.push(key);
  205. }
  206. for (var key in GLTF2) {
  207. // Prevent Reassignment.
  208. if (keys.indexOf(key) > -1) {
  209. continue;
  210. }
  211. BABYLON.GLTF2[key] = GLTF2[key];
  212. }
  213. }
  214. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  215. /***/ }),
  216. /***/ "./legacy/legacy-objFileLoader.ts":
  217. /*!****************************************!*\
  218. !*** ./legacy/legacy-objFileLoader.ts ***!
  219. \****************************************/
  220. /*! no static exports found */
  221. /***/ (function(module, exports, __webpack_require__) {
  222. "use strict";
  223. /* WEBPACK VAR INJECTION */(function(global) {
  224. function __export(m) {
  225. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  226. }
  227. Object.defineProperty(exports, "__esModule", { value: true });
  228. var Loaders = __webpack_require__(/*! ../src/OBJ */ "./src/OBJ/index.ts");
  229. /**
  230. * This is the entry point for the UMD module.
  231. * The entry point for a future ESM package should be index.ts
  232. */
  233. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  234. if (typeof globalObject !== "undefined") {
  235. for (var key in Loaders) {
  236. globalObject.BABYLON[key] = Loaders[key];
  237. }
  238. }
  239. __export(__webpack_require__(/*! ../src/OBJ */ "./src/OBJ/index.ts"));
  240. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  241. /***/ }),
  242. /***/ "./legacy/legacy-stlFileLoader.ts":
  243. /*!****************************************!*\
  244. !*** ./legacy/legacy-stlFileLoader.ts ***!
  245. \****************************************/
  246. /*! no static exports found */
  247. /***/ (function(module, exports, __webpack_require__) {
  248. "use strict";
  249. /* WEBPACK VAR INJECTION */(function(global) {
  250. function __export(m) {
  251. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  252. }
  253. Object.defineProperty(exports, "__esModule", { value: true });
  254. var Loaders = __webpack_require__(/*! ../src/STL */ "./src/STL/index.ts");
  255. /**
  256. * This is the entry point for the UMD module.
  257. * The entry point for a future ESM package should be index.ts
  258. */
  259. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  260. if (typeof globalObject !== "undefined") {
  261. for (var key in Loaders) {
  262. globalObject.BABYLON[key] = Loaders[key];
  263. }
  264. }
  265. __export(__webpack_require__(/*! ../src/STL */ "./src/STL/index.ts"));
  266. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  267. /***/ }),
  268. /***/ "./legacy/legacy.ts":
  269. /*!**************************!*\
  270. !*** ./legacy/legacy.ts ***!
  271. \**************************/
  272. /*! no static exports found */
  273. /***/ (function(module, exports, __webpack_require__) {
  274. "use strict";
  275. function __export(m) {
  276. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  277. }
  278. Object.defineProperty(exports, "__esModule", { value: true });
  279. __webpack_require__(/*! ../src */ "./src/index.ts");
  280. __export(__webpack_require__(/*! ./legacy-glTF */ "./legacy/legacy-glTF.ts"));
  281. __export(__webpack_require__(/*! ./legacy-glTF1 */ "./legacy/legacy-glTF1.ts"));
  282. __export(__webpack_require__(/*! ./legacy-glTF2 */ "./legacy/legacy-glTF2.ts"));
  283. __export(__webpack_require__(/*! ./legacy-objFileLoader */ "./legacy/legacy-objFileLoader.ts"));
  284. __export(__webpack_require__(/*! ./legacy-stlFileLoader */ "./legacy/legacy-stlFileLoader.ts"));
  285. /***/ }),
  286. /***/ "./src/OBJ/index.ts":
  287. /*!**************************!*\
  288. !*** ./src/OBJ/index.ts ***!
  289. \**************************/
  290. /*! no static exports found */
  291. /***/ (function(module, exports, __webpack_require__) {
  292. "use strict";
  293. function __export(m) {
  294. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  295. }
  296. Object.defineProperty(exports, "__esModule", { value: true });
  297. __export(__webpack_require__(/*! ./objFileLoader */ "./src/OBJ/objFileLoader.ts"));
  298. /***/ }),
  299. /***/ "./src/OBJ/objFileLoader.ts":
  300. /*!**********************************!*\
  301. !*** ./src/OBJ/objFileLoader.ts ***!
  302. \**********************************/
  303. /*! no static exports found */
  304. /***/ (function(module, exports, __webpack_require__) {
  305. "use strict";
  306. Object.defineProperty(exports, "__esModule", { value: true });
  307. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  308. /**
  309. * Class reading and parsing the MTL file bundled with the obj file.
  310. */
  311. var MTLFileLoader = /** @class */ (function () {
  312. function MTLFileLoader() {
  313. /**
  314. * All material loaded from the mtl will be set here
  315. */
  316. this.materials = [];
  317. }
  318. /**
  319. * This function will read the mtl file and create each material described inside
  320. * This function could be improve by adding :
  321. * -some component missing (Ni, Tf...)
  322. * -including the specific options available
  323. *
  324. * @param scene defines the scene the material will be created in
  325. * @param data defines the mtl data to parse
  326. * @param rootUrl defines the rooturl to use in order to load relative dependencies
  327. */
  328. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  329. if (data instanceof ArrayBuffer) {
  330. return;
  331. }
  332. //Split the lines from the file
  333. var lines = data.split('\n');
  334. //Space char
  335. var delimiter_pattern = /\s+/;
  336. //Array with RGB colors
  337. var color;
  338. //New material
  339. var material = null;
  340. //Look at each line
  341. for (var i = 0; i < lines.length; i++) {
  342. var line = lines[i].trim();
  343. // Blank line or comment
  344. if (line.length === 0 || line.charAt(0) === '#') {
  345. continue;
  346. }
  347. //Get the first parameter (keyword)
  348. var pos = line.indexOf(' ');
  349. var key = (pos >= 0) ? line.substring(0, pos) : line;
  350. key = key.toLowerCase();
  351. //Get the data following the key
  352. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  353. //This mtl keyword will create the new material
  354. if (key === "newmtl") {
  355. //Check if it is the first material.
  356. // Materials specifications are described after this keyword.
  357. if (material) {
  358. //Add the previous material in the material array.
  359. this.materials.push(material);
  360. }
  361. //Create a new material.
  362. // value is the name of the material read in the mtl file
  363. material = new babylonjs_1.StandardMaterial(value, scene);
  364. }
  365. else if (key === "kd" && material) {
  366. // Diffuse color (color under white light) using RGB values
  367. //value = "r g b"
  368. color = value.split(delimiter_pattern, 3).map(parseFloat);
  369. //color = [r,g,b]
  370. //Set tghe color into the material
  371. material.diffuseColor = babylonjs_1.Color3.FromArray(color);
  372. }
  373. else if (key === "ka" && material) {
  374. // Ambient color (color under shadow) using RGB values
  375. //value = "r g b"
  376. color = value.split(delimiter_pattern, 3).map(parseFloat);
  377. //color = [r,g,b]
  378. //Set tghe color into the material
  379. material.ambientColor = babylonjs_1.Color3.FromArray(color);
  380. }
  381. else if (key === "ks" && material) {
  382. // Specular color (color when light is reflected from shiny surface) using RGB values
  383. //value = "r g b"
  384. color = value.split(delimiter_pattern, 3).map(parseFloat);
  385. //color = [r,g,b]
  386. //Set the color into the material
  387. material.specularColor = babylonjs_1.Color3.FromArray(color);
  388. }
  389. else if (key === "ke" && material) {
  390. // Emissive color using RGB values
  391. color = value.split(delimiter_pattern, 3).map(parseFloat);
  392. material.emissiveColor = babylonjs_1.Color3.FromArray(color);
  393. }
  394. else if (key === "ns" && material) {
  395. //value = "Integer"
  396. material.specularPower = parseFloat(value);
  397. }
  398. else if (key === "d" && material) {
  399. //d is dissolve for current material. It mean alpha for BABYLON
  400. material.alpha = parseFloat(value);
  401. //Texture
  402. //This part can be improved by adding the possible options of texture
  403. }
  404. else if (key === "map_ka" && material) {
  405. // ambient texture map with a loaded image
  406. //We must first get the folder of the image
  407. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  408. }
  409. else if (key === "map_kd" && material) {
  410. // Diffuse texture map with a loaded image
  411. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  412. }
  413. else if (key === "map_ks" && material) {
  414. // Specular texture map with a loaded image
  415. //We must first get the folder of the image
  416. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  417. }
  418. else if (key === "map_ns") {
  419. //Specular
  420. //Specular highlight component
  421. //We must first get the folder of the image
  422. //
  423. //Not supported by BABYLON
  424. //
  425. // continue;
  426. }
  427. else if (key === "map_bump" && material) {
  428. //The bump texture
  429. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  430. }
  431. else if (key === "map_d" && material) {
  432. // The dissolve of the material
  433. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  434. //Options for illumination
  435. }
  436. else if (key === "illum") {
  437. //Illumination
  438. if (value === "0") {
  439. //That mean Kd == Kd
  440. }
  441. else if (value === "1") {
  442. //Color on and Ambient on
  443. }
  444. else if (value === "2") {
  445. //Highlight on
  446. }
  447. else if (value === "3") {
  448. //Reflection on and Ray trace on
  449. }
  450. else if (value === "4") {
  451. //Transparency: Glass on, Reflection: Ray trace on
  452. }
  453. else if (value === "5") {
  454. //Reflection: Fresnel on and Ray trace on
  455. }
  456. else if (value === "6") {
  457. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  458. }
  459. else if (value === "7") {
  460. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  461. }
  462. else if (value === "8") {
  463. //Reflection on and Ray trace off
  464. }
  465. else if (value === "9") {
  466. //Transparency: Glass on, Reflection: Ray trace off
  467. }
  468. else if (value === "10") {
  469. //Casts shadows onto invisible surfaces
  470. }
  471. }
  472. else {
  473. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  474. }
  475. }
  476. //At the end of the file, add the last material
  477. if (material) {
  478. this.materials.push(material);
  479. }
  480. };
  481. /**
  482. * Gets the texture for the material.
  483. *
  484. * If the material is imported from input file,
  485. * We sanitize the url to ensure it takes the textre from aside the material.
  486. *
  487. * @param rootUrl The root url to load from
  488. * @param value The value stored in the mtl
  489. * @return The Texture
  490. */
  491. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  492. if (!value) {
  493. return null;
  494. }
  495. var url = rootUrl;
  496. // Load from input file.
  497. if (rootUrl === "file:") {
  498. var lastDelimiter = value.lastIndexOf("\\");
  499. if (lastDelimiter === -1) {
  500. lastDelimiter = value.lastIndexOf("/");
  501. }
  502. if (lastDelimiter > -1) {
  503. url += value.substr(lastDelimiter + 1);
  504. }
  505. else {
  506. url += value;
  507. }
  508. }
  509. // Not from input file.
  510. else {
  511. url += value;
  512. }
  513. return new babylonjs_1.Texture(url, scene);
  514. };
  515. return MTLFileLoader;
  516. }());
  517. exports.MTLFileLoader = MTLFileLoader;
  518. /**
  519. * OBJ file type loader.
  520. * This is a babylon scene loader plugin.
  521. */
  522. var OBJFileLoader = /** @class */ (function () {
  523. function OBJFileLoader() {
  524. /**
  525. * Defines the name of the plugin.
  526. */
  527. this.name = "obj";
  528. /**
  529. * Defines the extension the plugin is able to load.
  530. */
  531. this.extensions = ".obj";
  532. /** @hidden */
  533. this.obj = /^o/;
  534. /** @hidden */
  535. this.group = /^g/;
  536. /** @hidden */
  537. this.mtllib = /^mtllib /;
  538. /** @hidden */
  539. this.usemtl = /^usemtl /;
  540. /** @hidden */
  541. this.smooth = /^s /;
  542. /** @hidden */
  543. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  544. // vn float float float
  545. /** @hidden */
  546. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  547. // vt float float
  548. /** @hidden */
  549. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  550. // f vertex vertex vertex ...
  551. /** @hidden */
  552. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  553. // f vertex/uvs vertex/uvs vertex/uvs ...
  554. /** @hidden */
  555. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  556. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  557. /** @hidden */
  558. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  559. // f vertex//normal vertex//normal vertex//normal ...
  560. /** @hidden */
  561. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  562. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  563. /** @hidden */
  564. this.facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  565. }
  566. /**
  567. * Calls synchronously the MTL file attached to this obj.
  568. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  569. * Without this function materials are not displayed in the first frame (but displayed after).
  570. * In consequence it is impossible to get material information in your HTML file
  571. *
  572. * @param url The URL of the MTL file
  573. * @param rootUrl
  574. * @param onSuccess Callback function to be called when the MTL file is loaded
  575. * @private
  576. */
  577. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  578. //The complete path to the mtl file
  579. var pathOfFile = babylonjs_1.Tools.BaseUrl + rootUrl + url;
  580. // Loads through the babylon tools to allow fileInput search.
  581. babylonjs_1.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  582. };
  583. /**
  584. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  585. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  586. * @param scene the scene the meshes should be added to
  587. * @param data the glTF data to load
  588. * @param rootUrl root url to load from
  589. * @param onProgress event that fires when loading progress has occured
  590. * @param fileName Defines the name of the file to load
  591. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  592. */
  593. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  594. //get the meshes from OBJ file
  595. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  596. return {
  597. meshes: meshes,
  598. particleSystems: [],
  599. skeletons: [],
  600. animationGroups: []
  601. };
  602. });
  603. };
  604. /**
  605. * Imports all objects from the loaded glTF data and adds them to the scene
  606. * @param scene the scene the objects should be added to
  607. * @param data the glTF data to load
  608. * @param rootUrl root url to load from
  609. * @param onProgress event that fires when loading progress has occured
  610. * @param fileName Defines the name of the file to load
  611. * @returns a promise which completes when objects have been loaded to the scene
  612. */
  613. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  614. //Get the 3D model
  615. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  616. // return void
  617. });
  618. };
  619. /**
  620. * Load into an asset container.
  621. * @param scene The scene to load into
  622. * @param data The data to import
  623. * @param rootUrl The root url for scene and resources
  624. * @param onProgress The callback when the load progresses
  625. * @param fileName Defines the name of the file to load
  626. * @returns The loaded asset container
  627. */
  628. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  629. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  630. var container = new babylonjs_1.AssetContainer(scene);
  631. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  632. container.removeAllFromScene();
  633. return container;
  634. });
  635. };
  636. /**
  637. * Read the OBJ file and create an Array of meshes.
  638. * Each mesh contains all information given by the OBJ and the MTL file.
  639. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  640. *
  641. * @param meshesNames
  642. * @param scene Scene The scene where are displayed the data
  643. * @param data String The content of the obj file
  644. * @param rootUrl String The path to the folder
  645. * @returns Array<AbstractMesh>
  646. * @private
  647. */
  648. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  649. var _this = this;
  650. var positions = []; //values for the positions of vertices
  651. var normals = []; //Values for the normals
  652. var uvs = []; //Values for the textures
  653. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  654. var handledMesh; //The current mesh of meshes array
  655. var indicesForBabylon = []; //The list of indices for VertexData
  656. var wrappedPositionForBabylon = []; //The list of position in vectors
  657. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  658. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  659. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  660. var curPositionInIndices = 0;
  661. var hasMeshes = false; //Meshes are defined in the file
  662. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  663. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  664. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  665. var triangles = []; //Indices from new triangles coming from polygons
  666. var materialNameFromObj = ""; //The name of the current material
  667. var fileToLoad = ""; //The name of the mtlFile to load
  668. var materialsFromMTLFile = new MTLFileLoader();
  669. var objMeshName = ""; //The name of the current obj mesh
  670. var increment = 1; //Id for meshes created by the multimaterial
  671. var isFirstMaterial = true;
  672. /**
  673. * Search for obj in the given array.
  674. * This function is called to check if a couple of data already exists in an array.
  675. *
  676. * If found, returns the index of the founded tuple index. Returns -1 if not found
  677. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  678. * @param obj Array<number>
  679. * @returns {boolean}
  680. */
  681. var isInArray = function (arr, obj) {
  682. if (!arr[obj[0]]) {
  683. arr[obj[0]] = { normals: [], idx: [] };
  684. }
  685. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  686. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  687. };
  688. var isInArrayUV = function (arr, obj) {
  689. if (!arr[obj[0]]) {
  690. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  691. }
  692. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  693. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  694. return arr[obj[0]].idx[idx];
  695. }
  696. return -1;
  697. };
  698. /**
  699. * This function set the data for each triangle.
  700. * Data are position, normals and uvs
  701. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  702. * If the tuple already exist, add only their indice
  703. *
  704. * @param indicePositionFromObj Integer The index in positions array
  705. * @param indiceUvsFromObj Integer The index in uvs array
  706. * @param indiceNormalFromObj Integer The index in normals array
  707. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  708. * @param textureVectorFromOBJ Vector3 The value of uvs
  709. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  710. */
  711. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  712. //Check if this tuple already exists in the list of tuples
  713. var _index;
  714. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  715. _index = isInArrayUV(tuplePosNorm, [
  716. indicePositionFromObj,
  717. indiceNormalFromObj,
  718. indiceUvsFromObj
  719. ]);
  720. }
  721. else {
  722. _index = isInArray(tuplePosNorm, [
  723. indicePositionFromObj,
  724. indiceNormalFromObj
  725. ]);
  726. }
  727. //If it not exists
  728. if (_index == -1) {
  729. //Add an new indice.
  730. //The array of indices is only an array with his length equal to the number of triangles - 1.
  731. //We add vertices data in this order
  732. indicesForBabylon.push(wrappedPositionForBabylon.length);
  733. //Push the position of vertice for Babylon
  734. //Each element is a Vector3(x,y,z)
  735. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  736. //Push the uvs for Babylon
  737. //Each element is a Vector3(u,v)
  738. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  739. //Push the normals for Babylon
  740. //Each element is a Vector3(x,y,z)
  741. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  742. //Add the tuple in the comparison list
  743. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  744. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  745. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  746. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  747. }
  748. }
  749. else {
  750. //The tuple already exists
  751. //Add the index of the already existing tuple
  752. //At this index we can get the value of position, normal and uvs of vertex
  753. indicesForBabylon.push(_index);
  754. }
  755. };
  756. /**
  757. * Transform Vector() object onto 3 digits in an array
  758. */
  759. var unwrapData = function () {
  760. //Every array has the same length
  761. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  762. //Push the x, y, z values of each element in the unwrapped array
  763. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  764. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  765. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  766. }
  767. // Reset arrays for the next new meshes
  768. wrappedPositionForBabylon = [];
  769. wrappedNormalsForBabylon = [];
  770. wrappedUvsForBabylon = [];
  771. tuplePosNorm = [];
  772. curPositionInIndices = 0;
  773. };
  774. /**
  775. * Create triangles from polygons by recursion
  776. * The best to understand how it works is to draw it in the same time you get the recursion.
  777. * It is important to notice that a triangle is a polygon
  778. * We get 5 patterns of face defined in OBJ File :
  779. * facePattern1 = ["1","2","3","4","5","6"]
  780. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  781. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  782. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  783. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  784. * Each pattern is divided by the same method
  785. * @param face Array[String] The indices of elements
  786. * @param v Integer The variable to increment
  787. */
  788. var getTriangles = function (face, v) {
  789. //Work for each element of the array
  790. if (v + 1 < face.length) {
  791. //Add on the triangle variable the indexes to obtain triangles
  792. triangles.push(face[0], face[v], face[v + 1]);
  793. //Incrementation for recursion
  794. v += 1;
  795. //Recursion
  796. getTriangles(face, v);
  797. }
  798. //Result obtained after 2 iterations:
  799. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  800. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  801. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  802. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  803. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  804. };
  805. /**
  806. * Create triangles and push the data for each polygon for the pattern 1
  807. * In this pattern we get vertice positions
  808. * @param face
  809. * @param v
  810. */
  811. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  812. //Get the indices of triangles for each polygon
  813. getTriangles(face, v);
  814. //For each element in the triangles array.
  815. //This var could contains 1 to an infinity of triangles
  816. for (var k = 0; k < triangles.length; k++) {
  817. // Set position indice
  818. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  819. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  820. positions[indicePositionFromObj], //Get the vectors data
  821. babylonjs_1.Vector2.Zero(), babylonjs_1.Vector3.Up() //Create default vectors
  822. );
  823. }
  824. //Reset variable for the next line
  825. triangles = [];
  826. };
  827. /**
  828. * Create triangles and push the data for each polygon for the pattern 2
  829. * In this pattern we get vertice positions and uvsu
  830. * @param face
  831. * @param v
  832. */
  833. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  834. //Get the indices of triangles for each polygon
  835. getTriangles(face, v);
  836. for (var k = 0; k < triangles.length; k++) {
  837. //triangle[k] = "1/1"
  838. //Split the data for getting position and uv
  839. var point = triangles[k].split("/"); // ["1", "1"]
  840. //Set position indice
  841. var indicePositionFromObj = parseInt(point[0]) - 1;
  842. //Set uv indice
  843. var indiceUvsFromObj = parseInt(point[1]) - 1;
  844. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  845. positions[indicePositionFromObj], //Get the values for each element
  846. uvs[indiceUvsFromObj], babylonjs_1.Vector3.Up() //Default value for normals
  847. );
  848. }
  849. //Reset variable for the next line
  850. triangles = [];
  851. };
  852. /**
  853. * Create triangles and push the data for each polygon for the pattern 3
  854. * In this pattern we get vertice positions, uvs and normals
  855. * @param face
  856. * @param v
  857. */
  858. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  859. //Get the indices of triangles for each polygon
  860. getTriangles(face, v);
  861. for (var k = 0; k < triangles.length; k++) {
  862. //triangle[k] = "1/1/1"
  863. //Split the data for getting position, uv, and normals
  864. var point = triangles[k].split("/"); // ["1", "1", "1"]
  865. // Set position indice
  866. var indicePositionFromObj = parseInt(point[0]) - 1;
  867. // Set uv indice
  868. var indiceUvsFromObj = parseInt(point[1]) - 1;
  869. // Set normal indice
  870. var indiceNormalFromObj = parseInt(point[2]) - 1;
  871. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  872. );
  873. }
  874. //Reset variable for the next line
  875. triangles = [];
  876. };
  877. /**
  878. * Create triangles and push the data for each polygon for the pattern 4
  879. * In this pattern we get vertice positions and normals
  880. * @param face
  881. * @param v
  882. */
  883. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  884. getTriangles(face, v);
  885. for (var k = 0; k < triangles.length; k++) {
  886. //triangle[k] = "1//1"
  887. //Split the data for getting position and normals
  888. var point = triangles[k].split("//"); // ["1", "1"]
  889. // We check indices, and normals
  890. var indicePositionFromObj = parseInt(point[0]) - 1;
  891. var indiceNormalFromObj = parseInt(point[1]) - 1;
  892. setData(indicePositionFromObj, 1, //Default value for uv
  893. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  894. babylonjs_1.Vector2.Zero(), normals[indiceNormalFromObj]);
  895. }
  896. //Reset variable for the next line
  897. triangles = [];
  898. };
  899. /**
  900. * Create triangles and push the data for each polygon for the pattern 3
  901. * In this pattern we get vertice positions, uvs and normals
  902. * @param face
  903. * @param v
  904. */
  905. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  906. //Get the indices of triangles for each polygon
  907. getTriangles(face, v);
  908. for (var k = 0; k < triangles.length; k++) {
  909. //triangle[k] = "-1/-1/-1"
  910. //Split the data for getting position, uv, and normals
  911. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  912. // Set position indice
  913. var indicePositionFromObj = positions.length + parseInt(point[0]);
  914. // Set uv indice
  915. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  916. // Set normal indice
  917. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  918. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  919. );
  920. }
  921. //Reset variable for the next line
  922. triangles = [];
  923. };
  924. var addPreviousObjMesh = function () {
  925. //Check if it is not the first mesh. Otherwise we don't have data.
  926. if (meshesFromObj.length > 0) {
  927. //Get the previous mesh for applying the data about the faces
  928. //=> in obj file, faces definition append after the name of the mesh
  929. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  930. //Set the data into Array for the mesh
  931. unwrapData();
  932. // Reverse tab. Otherwise face are displayed in the wrong sens
  933. indicesForBabylon.reverse();
  934. //Set the information for the mesh
  935. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  936. handledMesh.indices = indicesForBabylon.slice();
  937. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  938. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  939. handledMesh.uvs = unwrappedUVForBabylon.slice();
  940. //Reset the array for the next mesh
  941. indicesForBabylon = [];
  942. unwrappedPositionsForBabylon = [];
  943. unwrappedNormalsForBabylon = [];
  944. unwrappedUVForBabylon = [];
  945. }
  946. };
  947. //Main function
  948. //Split the file into lines
  949. var lines = data.split('\n');
  950. //Look at each line
  951. for (var i = 0; i < lines.length; i++) {
  952. var line = lines[i].trim();
  953. var result;
  954. //Comment or newLine
  955. if (line.length === 0 || line.charAt(0) === '#') {
  956. continue;
  957. //Get information about one position possible for the vertices
  958. }
  959. else if ((result = this.vertexPattern.exec(line)) !== null) {
  960. //Create a Vector3 with the position x, y, z
  961. //Value of result:
  962. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  963. //Add the Vector in the list of positions
  964. positions.push(new babylonjs_1.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  965. }
  966. else if ((result = this.normalPattern.exec(line)) !== null) {
  967. //Create a Vector3 with the normals x, y, z
  968. //Value of result
  969. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  970. //Add the Vector in the list of normals
  971. normals.push(new babylonjs_1.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  972. }
  973. else if ((result = this.uvPattern.exec(line)) !== null) {
  974. //Create a Vector2 with the normals u, v
  975. //Value of result
  976. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  977. //Add the Vector in the list of uvs
  978. uvs.push(new babylonjs_1.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  979. //Identify patterns of faces
  980. //Face could be defined in different type of pattern
  981. }
  982. else if ((result = this.facePattern3.exec(line)) !== null) {
  983. //Value of result:
  984. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  985. //Set the data for this face
  986. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  987. 1);
  988. }
  989. else if ((result = this.facePattern4.exec(line)) !== null) {
  990. //Value of result:
  991. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  992. //Set the data for this face
  993. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  994. 1);
  995. }
  996. else if ((result = this.facePattern5.exec(line)) !== null) {
  997. //Value of result:
  998. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  999. //Set the data for this face
  1000. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  1001. 1);
  1002. }
  1003. else if ((result = this.facePattern2.exec(line)) !== null) {
  1004. //Value of result:
  1005. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  1006. //Set the data for this face
  1007. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  1008. 1);
  1009. }
  1010. else if ((result = this.facePattern1.exec(line)) !== null) {
  1011. //Value of result
  1012. //["f 1 2 3", "1 2 3"...]
  1013. //Set the data for this face
  1014. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  1015. 1);
  1016. //Define a mesh or an object
  1017. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  1018. }
  1019. else if (this.group.test(line) || this.obj.test(line)) {
  1020. //Create a new mesh corresponding to the name of the group.
  1021. //Definition of the mesh
  1022. var objMesh =
  1023. //Set the name of the current obj mesh
  1024. {
  1025. name: line.substring(2).trim(),
  1026. indices: undefined,
  1027. positions: undefined,
  1028. normals: undefined,
  1029. uvs: undefined,
  1030. materialName: ""
  1031. };
  1032. addPreviousObjMesh();
  1033. //Push the last mesh created with only the name
  1034. meshesFromObj.push(objMesh);
  1035. //Set this variable to indicate that now meshesFromObj has objects defined inside
  1036. hasMeshes = true;
  1037. isFirstMaterial = true;
  1038. increment = 1;
  1039. //Keyword for applying a material
  1040. }
  1041. else if (this.usemtl.test(line)) {
  1042. //Get the name of the material
  1043. materialNameFromObj = line.substring(7).trim();
  1044. //If this new material is in the same mesh
  1045. if (!isFirstMaterial) {
  1046. //Set the data for the previous mesh
  1047. addPreviousObjMesh();
  1048. //Create a new mesh
  1049. var objMesh =
  1050. //Set the name of the current obj mesh
  1051. {
  1052. name: objMeshName + "_mm" + increment.toString(),
  1053. indices: undefined,
  1054. positions: undefined,
  1055. normals: undefined,
  1056. uvs: undefined,
  1057. materialName: materialNameFromObj
  1058. };
  1059. increment++;
  1060. //If meshes are already defined
  1061. meshesFromObj.push(objMesh);
  1062. }
  1063. //Set the material name if the previous line define a mesh
  1064. if (hasMeshes && isFirstMaterial) {
  1065. //Set the material name to the previous mesh (1 material per mesh)
  1066. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  1067. isFirstMaterial = false;
  1068. }
  1069. //Keyword for loading the mtl file
  1070. }
  1071. else if (this.mtllib.test(line)) {
  1072. //Get the name of mtl file
  1073. fileToLoad = line.substring(7).trim();
  1074. //Apply smoothing
  1075. }
  1076. else if (this.smooth.test(line)) {
  1077. // smooth shading => apply smoothing
  1078. //Toda y I don't know it work with babylon and with obj.
  1079. //With the obj file an integer is set
  1080. }
  1081. else {
  1082. //If there is another possibility
  1083. console.log("Unhandled expression at line : " + line);
  1084. }
  1085. }
  1086. //At the end of the file, add the last mesh into the meshesFromObj array
  1087. if (hasMeshes) {
  1088. //Set the data for the last mesh
  1089. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  1090. //Reverse indices for displaying faces in the good sens
  1091. indicesForBabylon.reverse();
  1092. //Get the good array
  1093. unwrapData();
  1094. //Set array
  1095. handledMesh.indices = indicesForBabylon;
  1096. handledMesh.positions = unwrappedPositionsForBabylon;
  1097. handledMesh.normals = unwrappedNormalsForBabylon;
  1098. handledMesh.uvs = unwrappedUVForBabylon;
  1099. }
  1100. //If any o or g keyword found, create a mesj with a random id
  1101. if (!hasMeshes) {
  1102. // reverse tab of indices
  1103. indicesForBabylon.reverse();
  1104. //Get positions normals uvs
  1105. unwrapData();
  1106. //Set data for one mesh
  1107. meshesFromObj.push({
  1108. name: babylonjs_1.Geometry.RandomId(),
  1109. indices: indicesForBabylon,
  1110. positions: unwrappedPositionsForBabylon,
  1111. normals: unwrappedNormalsForBabylon,
  1112. uvs: unwrappedUVForBabylon,
  1113. materialName: materialNameFromObj
  1114. });
  1115. }
  1116. //Create a Mesh list
  1117. var babylonMeshesArray = []; //The mesh for babylon
  1118. var materialToUse = new Array();
  1119. //Set data for each mesh
  1120. for (var j = 0; j < meshesFromObj.length; j++) {
  1121. //check meshesNames (stlFileLoader)
  1122. if (meshesNames && meshesFromObj[j].name) {
  1123. if (meshesNames instanceof Array) {
  1124. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  1125. continue;
  1126. }
  1127. }
  1128. else {
  1129. if (meshesFromObj[j].name !== meshesNames) {
  1130. continue;
  1131. }
  1132. }
  1133. }
  1134. //Get the current mesh
  1135. //Set the data with VertexBuffer for each mesh
  1136. handledMesh = meshesFromObj[j];
  1137. //Create a Mesh with the name of the obj mesh
  1138. var babylonMesh = new babylonjs_1.Mesh(meshesFromObj[j].name, scene);
  1139. //Push the name of the material to an array
  1140. //This is indispensable for the importMesh function
  1141. materialToUse.push(meshesFromObj[j].materialName);
  1142. var vertexData = new babylonjs_1.VertexData(); //The container for the values
  1143. //Set the data for the babylonMesh
  1144. vertexData.positions = handledMesh.positions;
  1145. vertexData.normals = handledMesh.normals;
  1146. vertexData.uvs = handledMesh.uvs;
  1147. vertexData.indices = handledMesh.indices;
  1148. //Set the data from the VertexBuffer to the current Mesh
  1149. vertexData.applyToMesh(babylonMesh);
  1150. if (OBJFileLoader.INVERT_Y) {
  1151. babylonMesh.scaling.y *= -1;
  1152. }
  1153. //Push the mesh into an array
  1154. babylonMeshesArray.push(babylonMesh);
  1155. }
  1156. var mtlPromises = [];
  1157. //load the materials
  1158. //Check if we have a file to load
  1159. if (fileToLoad !== "") {
  1160. //Load the file synchronously
  1161. mtlPromises.push(new Promise(function (resolve, reject) {
  1162. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  1163. try {
  1164. //Create materials thanks MTLLoader function
  1165. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  1166. //Look at each material loaded in the mtl file
  1167. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1168. //Three variables to get all meshes with the same material
  1169. var startIndex = 0;
  1170. var _indices = [];
  1171. var _index;
  1172. //The material from MTL file is used in the meshes loaded
  1173. //Push the indice in an array
  1174. //Check if the material is not used for another mesh
  1175. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1176. _indices.push(_index);
  1177. startIndex = _index + 1;
  1178. }
  1179. //If the material is not used dispose it
  1180. if (_index == -1 && _indices.length == 0) {
  1181. //If the material is not needed, remove it
  1182. materialsFromMTLFile.materials[n].dispose();
  1183. }
  1184. else {
  1185. for (var o = 0; o < _indices.length; o++) {
  1186. //Apply the material to the Mesh for each mesh with the material
  1187. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1188. }
  1189. }
  1190. }
  1191. resolve();
  1192. }
  1193. catch (e) {
  1194. reject(e);
  1195. }
  1196. });
  1197. }));
  1198. }
  1199. //Return an array with all Mesh
  1200. return Promise.all(mtlPromises).then(function () {
  1201. return babylonMeshesArray;
  1202. });
  1203. };
  1204. /**
  1205. * Defines if UVs are optimized by default during load.
  1206. */
  1207. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  1208. /**
  1209. * Defines if Y is inverted by default during load.
  1210. */
  1211. OBJFileLoader.INVERT_Y = false;
  1212. return OBJFileLoader;
  1213. }());
  1214. exports.OBJFileLoader = OBJFileLoader;
  1215. if (babylonjs_1.SceneLoader) {
  1216. //Add this loader into the register plugin
  1217. babylonjs_1.SceneLoader.RegisterPlugin(new OBJFileLoader());
  1218. }
  1219. /***/ }),
  1220. /***/ "./src/STL/index.ts":
  1221. /*!**************************!*\
  1222. !*** ./src/STL/index.ts ***!
  1223. \**************************/
  1224. /*! no static exports found */
  1225. /***/ (function(module, exports, __webpack_require__) {
  1226. "use strict";
  1227. function __export(m) {
  1228. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  1229. }
  1230. Object.defineProperty(exports, "__esModule", { value: true });
  1231. __export(__webpack_require__(/*! ./stlFileLoader */ "./src/STL/stlFileLoader.ts"));
  1232. /***/ }),
  1233. /***/ "./src/STL/stlFileLoader.ts":
  1234. /*!**********************************!*\
  1235. !*** ./src/STL/stlFileLoader.ts ***!
  1236. \**********************************/
  1237. /*! no static exports found */
  1238. /***/ (function(module, exports, __webpack_require__) {
  1239. "use strict";
  1240. Object.defineProperty(exports, "__esModule", { value: true });
  1241. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1242. /**
  1243. * STL file type loader.
  1244. * This is a babylon scene loader plugin.
  1245. */
  1246. var STLFileLoader = /** @class */ (function () {
  1247. function STLFileLoader() {
  1248. /** @hidden */
  1249. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  1250. /** @hidden */
  1251. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  1252. /** @hidden */
  1253. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  1254. /** @hidden */
  1255. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  1256. /**
  1257. * Defines the name of the plugin.
  1258. */
  1259. this.name = "stl";
  1260. /**
  1261. * Defines the extensions the stl loader is able to load.
  1262. * force data to come in as an ArrayBuffer
  1263. * we'll convert to string if it looks like it's an ASCII .stl
  1264. */
  1265. this.extensions = {
  1266. ".stl": { isBinary: true },
  1267. };
  1268. }
  1269. /**
  1270. * Import meshes into a scene.
  1271. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  1272. * @param scene The scene to import into
  1273. * @param data The data to import
  1274. * @param rootUrl The root url for scene and resources
  1275. * @param meshes The meshes array to import into
  1276. * @param particleSystems The particle systems array to import into
  1277. * @param skeletons The skeletons array to import into
  1278. * @param onError The callback when import fails
  1279. * @returns True if successful or false otherwise
  1280. */
  1281. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  1282. var matches;
  1283. if (typeof data !== "string") {
  1284. if (this._isBinary(data)) {
  1285. // binary .stl
  1286. var babylonMesh = new babylonjs_1.Mesh("stlmesh", scene);
  1287. this._parseBinary(babylonMesh, data);
  1288. if (meshes) {
  1289. meshes.push(babylonMesh);
  1290. }
  1291. return true;
  1292. }
  1293. // ASCII .stl
  1294. // convert to string
  1295. var array_buffer = new Uint8Array(data);
  1296. var str = '';
  1297. for (var i = 0; i < data.byteLength; i++) {
  1298. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  1299. }
  1300. data = str;
  1301. }
  1302. //if arrived here, data is a string, containing the STLA data.
  1303. while (matches = this.solidPattern.exec(data)) {
  1304. var meshName = matches[1];
  1305. var meshNameFromEnd = matches[3];
  1306. if (meshName != meshNameFromEnd) {
  1307. babylonjs_1.Tools.Error("Error in STL, solid name != endsolid name");
  1308. return false;
  1309. }
  1310. // check meshesNames
  1311. if (meshesNames && meshName) {
  1312. if (meshesNames instanceof Array) {
  1313. if (!meshesNames.indexOf(meshName)) {
  1314. continue;
  1315. }
  1316. }
  1317. else {
  1318. if (meshName !== meshesNames) {
  1319. continue;
  1320. }
  1321. }
  1322. }
  1323. // stl mesh name can be empty as well
  1324. meshName = meshName || "stlmesh";
  1325. var babylonMesh = new babylonjs_1.Mesh(meshName, scene);
  1326. this._parseASCII(babylonMesh, matches[2]);
  1327. if (meshes) {
  1328. meshes.push(babylonMesh);
  1329. }
  1330. }
  1331. return true;
  1332. };
  1333. /**
  1334. * Load into a scene.
  1335. * @param scene The scene to load into
  1336. * @param data The data to import
  1337. * @param rootUrl The root url for scene and resources
  1338. * @param onError The callback when import fails
  1339. * @returns true if successful or false otherwise
  1340. */
  1341. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  1342. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  1343. if (result) {
  1344. scene.createDefaultCameraOrLight();
  1345. }
  1346. return result;
  1347. };
  1348. /**
  1349. * Load into an asset container.
  1350. * @param scene The scene to load into
  1351. * @param data The data to import
  1352. * @param rootUrl The root url for scene and resources
  1353. * @param onError The callback when import fails
  1354. * @returns The loaded asset container
  1355. */
  1356. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  1357. var container = new babylonjs_1.AssetContainer(scene);
  1358. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  1359. container.removeAllFromScene();
  1360. return container;
  1361. };
  1362. STLFileLoader.prototype._isBinary = function (data) {
  1363. // check if file size is correct for binary stl
  1364. var faceSize, nFaces, reader;
  1365. reader = new DataView(data);
  1366. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  1367. nFaces = reader.getUint32(80, true);
  1368. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  1369. return true;
  1370. }
  1371. // check characters higher than ASCII to confirm binary
  1372. var fileLength = reader.byteLength;
  1373. for (var index = 0; index < fileLength; index++) {
  1374. if (reader.getUint8(index) > 127) {
  1375. return true;
  1376. }
  1377. }
  1378. return false;
  1379. };
  1380. STLFileLoader.prototype._parseBinary = function (mesh, data) {
  1381. var reader = new DataView(data);
  1382. var faces = reader.getUint32(80, true);
  1383. var dataOffset = 84;
  1384. var faceLength = 12 * 4 + 2;
  1385. var offset = 0;
  1386. var positions = new Float32Array(faces * 3 * 3);
  1387. var normals = new Float32Array(faces * 3 * 3);
  1388. var indices = new Uint32Array(faces * 3);
  1389. var indicesCount = 0;
  1390. for (var face = 0; face < faces; face++) {
  1391. var start = dataOffset + face * faceLength;
  1392. var normalX = reader.getFloat32(start, true);
  1393. var normalY = reader.getFloat32(start + 4, true);
  1394. var normalZ = reader.getFloat32(start + 8, true);
  1395. for (var i = 1; i <= 3; i++) {
  1396. var vertexstart = start + i * 12;
  1397. // ordering is intentional to match ascii import
  1398. positions[offset] = reader.getFloat32(vertexstart, true);
  1399. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  1400. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  1401. normals[offset] = normalX;
  1402. normals[offset + 2] = normalY;
  1403. normals[offset + 1] = normalZ;
  1404. offset += 3;
  1405. }
  1406. indices[indicesCount] = indicesCount++;
  1407. indices[indicesCount] = indicesCount++;
  1408. indices[indicesCount] = indicesCount++;
  1409. }
  1410. mesh.setVerticesData(babylonjs_1.VertexBuffer.PositionKind, positions);
  1411. mesh.setVerticesData(babylonjs_1.VertexBuffer.NormalKind, normals);
  1412. mesh.setIndices(indices);
  1413. mesh.computeWorldMatrix(true);
  1414. };
  1415. STLFileLoader.prototype._parseASCII = function (mesh, solidData) {
  1416. var positions = [];
  1417. var normals = [];
  1418. var indices = [];
  1419. var indicesCount = 0;
  1420. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  1421. var matches;
  1422. while (matches = this.facetsPattern.exec(solidData)) {
  1423. var facet = matches[1];
  1424. //one normal per face
  1425. var normalMatches = this.normalPattern.exec(facet);
  1426. this.normalPattern.lastIndex = 0;
  1427. if (!normalMatches) {
  1428. continue;
  1429. }
  1430. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  1431. var vertexMatch;
  1432. while (vertexMatch = this.vertexPattern.exec(facet)) {
  1433. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  1434. normals.push(normal[0], normal[1], normal[2]);
  1435. }
  1436. indices.push(indicesCount++, indicesCount++, indicesCount++);
  1437. this.vertexPattern.lastIndex = 0;
  1438. }
  1439. this.facetsPattern.lastIndex = 0;
  1440. mesh.setVerticesData(babylonjs_1.VertexBuffer.PositionKind, positions);
  1441. mesh.setVerticesData(babylonjs_1.VertexBuffer.NormalKind, normals);
  1442. mesh.setIndices(indices);
  1443. mesh.computeWorldMatrix(true);
  1444. };
  1445. return STLFileLoader;
  1446. }());
  1447. exports.STLFileLoader = STLFileLoader;
  1448. if (babylonjs_1.SceneLoader) {
  1449. babylonjs_1.SceneLoader.RegisterPlugin(new STLFileLoader());
  1450. }
  1451. /***/ }),
  1452. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  1453. /*!*********************************************!*\
  1454. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  1455. \*********************************************/
  1456. /*! no static exports found */
  1457. /***/ (function(module, exports, __webpack_require__) {
  1458. "use strict";
  1459. var __extends = (this && this.__extends) || (function () {
  1460. var extendStatics = function (d, b) {
  1461. extendStatics = Object.setPrototypeOf ||
  1462. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1463. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1464. return extendStatics(d, b);
  1465. }
  1466. return function (d, b) {
  1467. extendStatics(d, b);
  1468. function __() { this.constructor = d; }
  1469. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1470. };
  1471. })();
  1472. Object.defineProperty(exports, "__esModule", { value: true });
  1473. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  1474. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  1475. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1476. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  1477. var BinaryExtensionBufferName = "binary_glTF";
  1478. /** @hidden */
  1479. var GLTFBinaryExtension = /** @class */ (function (_super) {
  1480. __extends(GLTFBinaryExtension, _super);
  1481. function GLTFBinaryExtension() {
  1482. return _super.call(this, "KHR_binary_glTF") || this;
  1483. }
  1484. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1485. var extensionsUsed = data.json.extensionsUsed;
  1486. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  1487. return false;
  1488. }
  1489. this._bin = data.bin;
  1490. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1491. return true;
  1492. };
  1493. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1494. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1495. return false;
  1496. }
  1497. if (id !== BinaryExtensionBufferName) {
  1498. return false;
  1499. }
  1500. onSuccess(this._bin);
  1501. return true;
  1502. };
  1503. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1504. var texture = gltfRuntime.textures[id];
  1505. var source = gltfRuntime.images[texture.source];
  1506. if (!source.extensions || !(this.name in source.extensions)) {
  1507. return false;
  1508. }
  1509. var sourceExt = source.extensions[this.name];
  1510. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1511. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1512. onSuccess(buffer);
  1513. return true;
  1514. };
  1515. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1516. var shader = gltfRuntime.shaders[id];
  1517. if (!shader.extensions || !(this.name in shader.extensions)) {
  1518. return false;
  1519. }
  1520. var binaryExtensionShader = shader.extensions[this.name];
  1521. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1522. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1523. setTimeout(function () {
  1524. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  1525. onSuccess(shaderString);
  1526. });
  1527. return true;
  1528. };
  1529. return GLTFBinaryExtension;
  1530. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  1531. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  1532. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  1533. /***/ }),
  1534. /***/ "./src/glTF/1.0/glTFLoader.ts":
  1535. /*!************************************!*\
  1536. !*** ./src/glTF/1.0/glTFLoader.ts ***!
  1537. \************************************/
  1538. /*! no static exports found */
  1539. /***/ (function(module, exports, __webpack_require__) {
  1540. "use strict";
  1541. Object.defineProperty(exports, "__esModule", { value: true });
  1542. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1543. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  1544. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1545. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  1546. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  1547. /**
  1548. * Tokenizer. Used for shaders compatibility
  1549. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1550. */
  1551. var ETokenType;
  1552. (function (ETokenType) {
  1553. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1554. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1555. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1556. })(ETokenType || (ETokenType = {}));
  1557. var Tokenizer = /** @class */ (function () {
  1558. function Tokenizer(toParse) {
  1559. this._pos = 0;
  1560. this.currentToken = ETokenType.UNKNOWN;
  1561. this.currentIdentifier = "";
  1562. this.currentString = "";
  1563. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1564. this._toParse = toParse;
  1565. this._maxPos = toParse.length;
  1566. }
  1567. Tokenizer.prototype.getNextToken = function () {
  1568. if (this.isEnd()) {
  1569. return ETokenType.END_OF_INPUT;
  1570. }
  1571. this.currentString = this.read();
  1572. this.currentToken = ETokenType.UNKNOWN;
  1573. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1574. this.currentToken = ETokenType.IDENTIFIER;
  1575. this.currentIdentifier = this.currentString;
  1576. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1577. this.currentIdentifier += this.currentString;
  1578. this.forward();
  1579. }
  1580. }
  1581. return this.currentToken;
  1582. };
  1583. Tokenizer.prototype.peek = function () {
  1584. return this._toParse[this._pos];
  1585. };
  1586. Tokenizer.prototype.read = function () {
  1587. return this._toParse[this._pos++];
  1588. };
  1589. Tokenizer.prototype.forward = function () {
  1590. this._pos++;
  1591. };
  1592. Tokenizer.prototype.isEnd = function () {
  1593. return this._pos >= this._maxPos;
  1594. };
  1595. return Tokenizer;
  1596. }());
  1597. /**
  1598. * Values
  1599. */
  1600. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1601. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1602. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1603. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1604. /**
  1605. * Parse
  1606. */
  1607. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1608. for (var buf in parsedBuffers) {
  1609. var parsedBuffer = parsedBuffers[buf];
  1610. gltfRuntime.buffers[buf] = parsedBuffer;
  1611. gltfRuntime.buffersCount++;
  1612. }
  1613. };
  1614. var parseShaders = function (parsedShaders, gltfRuntime) {
  1615. for (var sha in parsedShaders) {
  1616. var parsedShader = parsedShaders[sha];
  1617. gltfRuntime.shaders[sha] = parsedShader;
  1618. gltfRuntime.shaderscount++;
  1619. }
  1620. };
  1621. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1622. for (var object in parsedObjects) {
  1623. var parsedObject = parsedObjects[object];
  1624. gltfRuntime[runtimeProperty][object] = parsedObject;
  1625. }
  1626. };
  1627. /**
  1628. * Utils
  1629. */
  1630. var normalizeUVs = function (buffer) {
  1631. if (!buffer) {
  1632. return;
  1633. }
  1634. for (var i = 0; i < buffer.length / 2; i++) {
  1635. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1636. }
  1637. };
  1638. var getAttribute = function (attributeParameter) {
  1639. if (attributeParameter.semantic === "NORMAL") {
  1640. return "normal";
  1641. }
  1642. else if (attributeParameter.semantic === "POSITION") {
  1643. return "position";
  1644. }
  1645. else if (attributeParameter.semantic === "JOINT") {
  1646. return "matricesIndices";
  1647. }
  1648. else if (attributeParameter.semantic === "WEIGHT") {
  1649. return "matricesWeights";
  1650. }
  1651. else if (attributeParameter.semantic === "COLOR") {
  1652. return "color";
  1653. }
  1654. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1655. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1656. return "uv" + (channel === 0 ? "" : channel + 1);
  1657. }
  1658. return null;
  1659. };
  1660. /**
  1661. * Loads and creates animations
  1662. */
  1663. var loadAnimations = function (gltfRuntime) {
  1664. for (var anim in gltfRuntime.animations) {
  1665. var animation = gltfRuntime.animations[anim];
  1666. if (!animation.channels || !animation.samplers) {
  1667. continue;
  1668. }
  1669. var lastAnimation = null;
  1670. for (var i = 0; i < animation.channels.length; i++) {
  1671. // Get parameters and load buffers
  1672. var channel = animation.channels[i];
  1673. var sampler = animation.samplers[channel.sampler];
  1674. if (!sampler) {
  1675. continue;
  1676. }
  1677. var inputData = null;
  1678. var outputData = null;
  1679. if (animation.parameters) {
  1680. inputData = animation.parameters[sampler.input];
  1681. outputData = animation.parameters[sampler.output];
  1682. }
  1683. else {
  1684. inputData = sampler.input;
  1685. outputData = sampler.output;
  1686. }
  1687. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1688. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1689. var targetID = channel.target.id;
  1690. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1691. if (targetNode === null) {
  1692. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1693. }
  1694. if (targetNode === null) {
  1695. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1696. continue;
  1697. }
  1698. var isBone = targetNode instanceof babylonjs_1.Bone;
  1699. // Get target path (position, rotation or scaling)
  1700. var targetPath = channel.target.path;
  1701. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1702. if (targetPathIndex !== -1) {
  1703. targetPath = babylonAnimationPaths[targetPathIndex];
  1704. }
  1705. // Determine animation type
  1706. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  1707. if (!isBone) {
  1708. if (targetPath === "rotationQuaternion") {
  1709. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  1710. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  1711. }
  1712. else {
  1713. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  1714. }
  1715. }
  1716. // Create animation and key frames
  1717. var babylonAnimation = null;
  1718. var keys = [];
  1719. var arrayOffset = 0;
  1720. var modifyKey = false;
  1721. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1722. babylonAnimation = lastAnimation;
  1723. modifyKey = true;
  1724. }
  1725. if (!modifyKey) {
  1726. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  1727. }
  1728. // For each frame
  1729. for (var j = 0; j < bufferInput.length; j++) {
  1730. var value = null;
  1731. if (targetPath === "rotationQuaternion") { // VEC4
  1732. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1733. arrayOffset += 4;
  1734. }
  1735. else { // Position and scaling are VEC3
  1736. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1737. arrayOffset += 3;
  1738. }
  1739. if (isBone) {
  1740. var bone = targetNode;
  1741. var translation = babylonjs_1.Vector3.Zero();
  1742. var rotationQuaternion = new babylonjs_1.Quaternion();
  1743. var scaling = babylonjs_1.Vector3.Zero();
  1744. // Warning on decompose
  1745. var mat = bone.getBaseMatrix();
  1746. if (modifyKey && lastAnimation) {
  1747. mat = lastAnimation.getKeys()[j].value;
  1748. }
  1749. mat.decompose(scaling, rotationQuaternion, translation);
  1750. if (targetPath === "position") {
  1751. translation = value;
  1752. }
  1753. else if (targetPath === "rotationQuaternion") {
  1754. rotationQuaternion = value;
  1755. }
  1756. else {
  1757. scaling = value;
  1758. }
  1759. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  1760. }
  1761. if (!modifyKey) {
  1762. keys.push({
  1763. frame: bufferInput[j],
  1764. value: value
  1765. });
  1766. }
  1767. else if (lastAnimation) {
  1768. lastAnimation.getKeys()[j].value = value;
  1769. }
  1770. }
  1771. // Finish
  1772. if (!modifyKey && babylonAnimation) {
  1773. babylonAnimation.setKeys(keys);
  1774. targetNode.animations.push(babylonAnimation);
  1775. }
  1776. lastAnimation = babylonAnimation;
  1777. gltfRuntime.scene.stopAnimation(targetNode);
  1778. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1779. }
  1780. }
  1781. };
  1782. /**
  1783. * Returns the bones transformation matrix
  1784. */
  1785. var configureBoneTransformation = function (node) {
  1786. var mat = null;
  1787. if (node.translation || node.rotation || node.scale) {
  1788. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  1789. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1790. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  1791. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  1792. }
  1793. else {
  1794. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  1795. }
  1796. return mat;
  1797. };
  1798. /**
  1799. * Returns the parent bone
  1800. */
  1801. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1802. // Try to find
  1803. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1804. if (newSkeleton.bones[i].name === jointName) {
  1805. return newSkeleton.bones[i];
  1806. }
  1807. }
  1808. // Not found, search in gltf nodes
  1809. var nodes = gltfRuntime.nodes;
  1810. for (var nde in nodes) {
  1811. var node = nodes[nde];
  1812. if (!node.jointName) {
  1813. continue;
  1814. }
  1815. var children = node.children;
  1816. for (var i = 0; i < children.length; i++) {
  1817. var child = gltfRuntime.nodes[children[i]];
  1818. if (!child.jointName) {
  1819. continue;
  1820. }
  1821. if (child.jointName === jointName) {
  1822. var mat = configureBoneTransformation(node);
  1823. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1824. bone.id = nde;
  1825. return bone;
  1826. }
  1827. }
  1828. }
  1829. return null;
  1830. };
  1831. /**
  1832. * Returns the appropriate root node
  1833. */
  1834. var getNodeToRoot = function (nodesToRoot, id) {
  1835. for (var i = 0; i < nodesToRoot.length; i++) {
  1836. var nodeToRoot = nodesToRoot[i];
  1837. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1838. var child = nodeToRoot.node.children[j];
  1839. if (child === id) {
  1840. return nodeToRoot.bone;
  1841. }
  1842. }
  1843. }
  1844. return null;
  1845. };
  1846. /**
  1847. * Returns the node with the joint name
  1848. */
  1849. var getJointNode = function (gltfRuntime, jointName) {
  1850. var nodes = gltfRuntime.nodes;
  1851. var node = nodes[jointName];
  1852. if (node) {
  1853. return {
  1854. node: node,
  1855. id: jointName
  1856. };
  1857. }
  1858. for (var nde in nodes) {
  1859. node = nodes[nde];
  1860. if (node.jointName === jointName) {
  1861. return {
  1862. node: node,
  1863. id: nde
  1864. };
  1865. }
  1866. }
  1867. return null;
  1868. };
  1869. /**
  1870. * Checks if a nodes is in joints
  1871. */
  1872. var nodeIsInJoints = function (skins, id) {
  1873. for (var i = 0; i < skins.jointNames.length; i++) {
  1874. if (skins.jointNames[i] === id) {
  1875. return true;
  1876. }
  1877. }
  1878. return false;
  1879. };
  1880. /**
  1881. * Fills the nodes to root for bones and builds hierarchy
  1882. */
  1883. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1884. // Creates nodes for root
  1885. for (var nde in gltfRuntime.nodes) {
  1886. var node = gltfRuntime.nodes[nde];
  1887. var id = nde;
  1888. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1889. continue;
  1890. }
  1891. // Create node to root bone
  1892. var mat = configureBoneTransformation(node);
  1893. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  1894. bone.id = id;
  1895. nodesToRoot.push({ bone: bone, node: node, id: id });
  1896. }
  1897. // Parenting
  1898. for (var i = 0; i < nodesToRoot.length; i++) {
  1899. var nodeToRoot = nodesToRoot[i];
  1900. var children = nodeToRoot.node.children;
  1901. for (var j = 0; j < children.length; j++) {
  1902. var child = null;
  1903. for (var k = 0; k < nodesToRoot.length; k++) {
  1904. if (nodesToRoot[k].id === children[j]) {
  1905. child = nodesToRoot[k];
  1906. break;
  1907. }
  1908. }
  1909. if (child) {
  1910. child.bone._parent = nodeToRoot.bone;
  1911. nodeToRoot.bone.children.push(child.bone);
  1912. }
  1913. }
  1914. }
  1915. };
  1916. /**
  1917. * Imports a skeleton
  1918. */
  1919. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1920. if (!newSkeleton) {
  1921. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1922. }
  1923. if (!skins.babylonSkeleton) {
  1924. return newSkeleton;
  1925. }
  1926. // Find the root bones
  1927. var nodesToRoot = [];
  1928. var nodesToRootToAdd = [];
  1929. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1930. newSkeleton.bones = [];
  1931. // Joints
  1932. for (var i = 0; i < skins.jointNames.length; i++) {
  1933. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1934. if (!jointNode) {
  1935. continue;
  1936. }
  1937. var node = jointNode.node;
  1938. if (!node) {
  1939. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1940. continue;
  1941. }
  1942. var id = jointNode.id;
  1943. // Optimize, if the bone already exists...
  1944. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1945. if (existingBone) {
  1946. newSkeleton.bones.push(existingBone);
  1947. continue;
  1948. }
  1949. // Search for parent bone
  1950. var foundBone = false;
  1951. var parentBone = null;
  1952. for (var j = 0; j < i; j++) {
  1953. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1954. if (!jointNode_1) {
  1955. continue;
  1956. }
  1957. var joint = jointNode_1.node;
  1958. if (!joint) {
  1959. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1960. continue;
  1961. }
  1962. var children = joint.children;
  1963. if (!children) {
  1964. continue;
  1965. }
  1966. foundBone = false;
  1967. for (var k = 0; k < children.length; k++) {
  1968. if (children[k] === id) {
  1969. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1970. foundBone = true;
  1971. break;
  1972. }
  1973. }
  1974. if (foundBone) {
  1975. break;
  1976. }
  1977. }
  1978. // Create bone
  1979. var mat = configureBoneTransformation(node);
  1980. if (!parentBone && nodesToRoot.length > 0) {
  1981. parentBone = getNodeToRoot(nodesToRoot, id);
  1982. if (parentBone) {
  1983. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1984. nodesToRootToAdd.push(parentBone);
  1985. }
  1986. }
  1987. }
  1988. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1989. bone.id = id;
  1990. }
  1991. // Polish
  1992. var bones = newSkeleton.bones;
  1993. newSkeleton.bones = [];
  1994. for (var i = 0; i < skins.jointNames.length; i++) {
  1995. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1996. if (!jointNode) {
  1997. continue;
  1998. }
  1999. for (var j = 0; j < bones.length; j++) {
  2000. if (bones[j].id === jointNode.id) {
  2001. newSkeleton.bones.push(bones[j]);
  2002. break;
  2003. }
  2004. }
  2005. }
  2006. newSkeleton.prepare();
  2007. // Finish
  2008. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2009. newSkeleton.bones.push(nodesToRootToAdd[i]);
  2010. }
  2011. return newSkeleton;
  2012. };
  2013. /**
  2014. * Imports a mesh and its geometries
  2015. */
  2016. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  2017. if (!newMesh) {
  2018. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  2019. newMesh.id = id;
  2020. }
  2021. if (!node.babylonNode) {
  2022. return newMesh;
  2023. }
  2024. var subMaterials = [];
  2025. var vertexData = null;
  2026. var verticesStarts = new Array();
  2027. var verticesCounts = new Array();
  2028. var indexStarts = new Array();
  2029. var indexCounts = new Array();
  2030. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2031. var meshID = meshes[meshIndex];
  2032. var mesh = gltfRuntime.meshes[meshID];
  2033. if (!mesh) {
  2034. continue;
  2035. }
  2036. // Positions, normals and UVs
  2037. for (var i = 0; i < mesh.primitives.length; i++) {
  2038. // Temporary vertex data
  2039. var tempVertexData = new babylonjs_1.VertexData();
  2040. var primitive = mesh.primitives[i];
  2041. if (primitive.mode !== 4) {
  2042. // continue;
  2043. }
  2044. var attributes = primitive.attributes;
  2045. var accessor = null;
  2046. var buffer = null;
  2047. // Set positions, normal and uvs
  2048. for (var semantic in attributes) {
  2049. // Link accessor and buffer view
  2050. accessor = gltfRuntime.accessors[attributes[semantic]];
  2051. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2052. if (semantic === "NORMAL") {
  2053. tempVertexData.normals = new Float32Array(buffer.length);
  2054. tempVertexData.normals.set(buffer);
  2055. }
  2056. else if (semantic === "POSITION") {
  2057. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  2058. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2059. for (var j = 0; j < buffer.length; j += 4) {
  2060. tempVertexData.positions[j] = buffer[j];
  2061. tempVertexData.positions[j + 1] = buffer[j + 1];
  2062. tempVertexData.positions[j + 2] = buffer[j + 2];
  2063. }
  2064. }
  2065. else {
  2066. tempVertexData.positions = new Float32Array(buffer.length);
  2067. tempVertexData.positions.set(buffer);
  2068. }
  2069. verticesCounts.push(tempVertexData.positions.length);
  2070. }
  2071. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2072. var channel = Number(semantic.split("_")[1]);
  2073. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2074. var uvs = new Float32Array(buffer.length);
  2075. uvs.set(buffer);
  2076. normalizeUVs(uvs);
  2077. tempVertexData.set(uvs, uvKind);
  2078. }
  2079. else if (semantic === "JOINT") {
  2080. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2081. tempVertexData.matricesIndices.set(buffer);
  2082. }
  2083. else if (semantic === "WEIGHT") {
  2084. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2085. tempVertexData.matricesWeights.set(buffer);
  2086. }
  2087. else if (semantic === "COLOR") {
  2088. tempVertexData.colors = new Float32Array(buffer.length);
  2089. tempVertexData.colors.set(buffer);
  2090. }
  2091. }
  2092. // Indices
  2093. accessor = gltfRuntime.accessors[primitive.indices];
  2094. if (accessor) {
  2095. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2096. tempVertexData.indices = new Int32Array(buffer.length);
  2097. tempVertexData.indices.set(buffer);
  2098. indexCounts.push(tempVertexData.indices.length);
  2099. }
  2100. else {
  2101. // Set indices on the fly
  2102. var indices = [];
  2103. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2104. indices.push(j);
  2105. }
  2106. tempVertexData.indices = new Int32Array(indices);
  2107. indexCounts.push(tempVertexData.indices.length);
  2108. }
  2109. if (!vertexData) {
  2110. vertexData = tempVertexData;
  2111. }
  2112. else {
  2113. vertexData.merge(tempVertexData);
  2114. }
  2115. // Sub material
  2116. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2117. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2118. // Update vertices start and index start
  2119. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2120. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2121. }
  2122. }
  2123. var material;
  2124. if (subMaterials.length > 1) {
  2125. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2126. material.subMaterials = subMaterials;
  2127. }
  2128. else {
  2129. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2130. }
  2131. if (subMaterials.length === 1) {
  2132. material = subMaterials[0];
  2133. }
  2134. if (!newMesh.material) {
  2135. newMesh.material = material;
  2136. }
  2137. // Apply geometry
  2138. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2139. newMesh.computeWorldMatrix(true);
  2140. // Apply submeshes
  2141. newMesh.subMeshes = [];
  2142. var index = 0;
  2143. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2144. var meshID = meshes[meshIndex];
  2145. var mesh = gltfRuntime.meshes[meshID];
  2146. if (!mesh) {
  2147. continue;
  2148. }
  2149. for (var i = 0; i < mesh.primitives.length; i++) {
  2150. if (mesh.primitives[i].mode !== 4) {
  2151. //continue;
  2152. }
  2153. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2154. index++;
  2155. }
  2156. }
  2157. // Finish
  2158. return newMesh;
  2159. };
  2160. /**
  2161. * Configure node transformation from position, rotation and scaling
  2162. */
  2163. var configureNode = function (newNode, position, rotation, scaling) {
  2164. if (newNode.position) {
  2165. newNode.position = position;
  2166. }
  2167. if (newNode.rotationQuaternion || newNode.rotation) {
  2168. newNode.rotationQuaternion = rotation;
  2169. }
  2170. if (newNode.scaling) {
  2171. newNode.scaling = scaling;
  2172. }
  2173. };
  2174. /**
  2175. * Configures node from transformation matrix
  2176. */
  2177. var configureNodeFromMatrix = function (newNode, node, parent) {
  2178. if (node.matrix) {
  2179. var position = new babylonjs_1.Vector3(0, 0, 0);
  2180. var rotation = new babylonjs_1.Quaternion();
  2181. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  2182. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  2183. mat.decompose(scaling, rotation, position);
  2184. configureNode(newNode, position, rotation, scaling);
  2185. }
  2186. else if (node.translation && node.rotation && node.scale) {
  2187. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  2188. }
  2189. newNode.computeWorldMatrix(true);
  2190. };
  2191. /**
  2192. * Imports a node
  2193. */
  2194. var importNode = function (gltfRuntime, node, id, parent) {
  2195. var lastNode = null;
  2196. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2197. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2198. return null;
  2199. }
  2200. }
  2201. // Meshes
  2202. if (node.skin) {
  2203. if (node.meshes) {
  2204. var skin = gltfRuntime.skins[node.skin];
  2205. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2206. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2207. if (newMesh.skeleton === null) {
  2208. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2209. if (!skin.babylonSkeleton) {
  2210. skin.babylonSkeleton = newMesh.skeleton;
  2211. }
  2212. }
  2213. lastNode = newMesh;
  2214. }
  2215. }
  2216. else if (node.meshes) {
  2217. /**
  2218. * Improve meshes property
  2219. */
  2220. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2221. lastNode = newMesh;
  2222. }
  2223. // Lights
  2224. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2225. var light = gltfRuntime.lights[node.light];
  2226. if (light) {
  2227. if (light.type === "ambient") {
  2228. var ambienLight = light[light.type];
  2229. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2230. hemiLight.name = node.name || "";
  2231. if (ambienLight.color) {
  2232. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  2233. }
  2234. lastNode = hemiLight;
  2235. }
  2236. else if (light.type === "directional") {
  2237. var directionalLight = light[light.type];
  2238. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2239. dirLight.name = node.name || "";
  2240. if (directionalLight.color) {
  2241. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  2242. }
  2243. lastNode = dirLight;
  2244. }
  2245. else if (light.type === "point") {
  2246. var pointLight = light[light.type];
  2247. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  2248. ptLight.name = node.name || "";
  2249. if (pointLight.color) {
  2250. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  2251. }
  2252. lastNode = ptLight;
  2253. }
  2254. else if (light.type === "spot") {
  2255. var spotLight = light[light.type];
  2256. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2257. spLight.name = node.name || "";
  2258. if (spotLight.color) {
  2259. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  2260. }
  2261. if (spotLight.fallOfAngle) {
  2262. spLight.angle = spotLight.fallOfAngle;
  2263. }
  2264. if (spotLight.fallOffExponent) {
  2265. spLight.exponent = spotLight.fallOffExponent;
  2266. }
  2267. lastNode = spLight;
  2268. }
  2269. }
  2270. }
  2271. // Cameras
  2272. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2273. var camera = gltfRuntime.cameras[node.camera];
  2274. if (camera) {
  2275. if (camera.type === "orthographic") {
  2276. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  2277. orthoCamera.name = node.name || "";
  2278. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  2279. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2280. lastNode = orthoCamera;
  2281. }
  2282. else if (camera.type === "perspective") {
  2283. var perspectiveCamera = camera[camera.type];
  2284. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  2285. persCamera.name = node.name || "";
  2286. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2287. if (!perspectiveCamera.aspectRatio) {
  2288. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2289. }
  2290. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2291. persCamera.maxZ = perspectiveCamera.zfar;
  2292. persCamera.minZ = perspectiveCamera.znear;
  2293. }
  2294. lastNode = persCamera;
  2295. }
  2296. }
  2297. }
  2298. // Empty node
  2299. if (!node.jointName) {
  2300. if (node.babylonNode) {
  2301. return node.babylonNode;
  2302. }
  2303. else if (lastNode === null) {
  2304. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  2305. node.babylonNode = dummy;
  2306. lastNode = dummy;
  2307. }
  2308. }
  2309. if (lastNode !== null) {
  2310. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  2311. configureNodeFromMatrix(lastNode, node, parent);
  2312. }
  2313. else {
  2314. var translation = node.translation || [0, 0, 0];
  2315. var rotation = node.rotation || [0, 0, 0, 1];
  2316. var scale = node.scale || [1, 1, 1];
  2317. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  2318. }
  2319. lastNode.updateCache(true);
  2320. node.babylonNode = lastNode;
  2321. }
  2322. return lastNode;
  2323. };
  2324. /**
  2325. * Traverses nodes and creates them
  2326. */
  2327. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2328. if (meshIncluded === void 0) { meshIncluded = false; }
  2329. var node = gltfRuntime.nodes[id];
  2330. var newNode = null;
  2331. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2332. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2333. meshIncluded = true;
  2334. }
  2335. else {
  2336. meshIncluded = false;
  2337. }
  2338. }
  2339. else {
  2340. meshIncluded = true;
  2341. }
  2342. if (!node.jointName && meshIncluded) {
  2343. newNode = importNode(gltfRuntime, node, id, parent);
  2344. if (newNode !== null) {
  2345. newNode.id = id;
  2346. newNode.parent = parent;
  2347. }
  2348. }
  2349. if (node.children) {
  2350. for (var i = 0; i < node.children.length; i++) {
  2351. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2352. }
  2353. }
  2354. };
  2355. /**
  2356. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2357. */
  2358. var postLoad = function (gltfRuntime) {
  2359. // Nodes
  2360. var currentScene = gltfRuntime.currentScene;
  2361. if (currentScene) {
  2362. for (var i = 0; i < currentScene.nodes.length; i++) {
  2363. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2364. }
  2365. }
  2366. else {
  2367. for (var thing in gltfRuntime.scenes) {
  2368. currentScene = gltfRuntime.scenes[thing];
  2369. for (var i = 0; i < currentScene.nodes.length; i++) {
  2370. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2371. }
  2372. }
  2373. }
  2374. // Set animations
  2375. loadAnimations(gltfRuntime);
  2376. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2377. var skeleton = gltfRuntime.scene.skeletons[i];
  2378. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2379. }
  2380. };
  2381. /**
  2382. * onBind shaderrs callback to set uniforms and matrices
  2383. */
  2384. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2385. var materialValues = material.values || technique.parameters;
  2386. for (var unif in unTreatedUniforms) {
  2387. var uniform = unTreatedUniforms[unif];
  2388. var type = uniform.type;
  2389. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  2390. if (uniform.semantic && !uniform.source && !uniform.node) {
  2391. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2392. }
  2393. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2394. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2395. if (source === null) {
  2396. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2397. }
  2398. if (source === null) {
  2399. continue;
  2400. }
  2401. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2402. }
  2403. }
  2404. else {
  2405. var value = materialValues[technique.uniforms[unif]];
  2406. if (!value) {
  2407. continue;
  2408. }
  2409. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2410. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2411. if (texture === null || texture === undefined) {
  2412. continue;
  2413. }
  2414. shaderMaterial.getEffect().setTexture(unif, texture);
  2415. }
  2416. else {
  2417. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2418. }
  2419. }
  2420. }
  2421. onSuccess(shaderMaterial);
  2422. };
  2423. /**
  2424. * Prepare uniforms to send the only one time
  2425. * Loads the appropriate textures
  2426. */
  2427. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2428. var materialValues = material.values || technique.parameters;
  2429. var techniqueUniforms = technique.uniforms;
  2430. /**
  2431. * Prepare values here (not matrices)
  2432. */
  2433. for (var unif in unTreatedUniforms) {
  2434. var uniform = unTreatedUniforms[unif];
  2435. var type = uniform.type;
  2436. var value = materialValues[techniqueUniforms[unif]];
  2437. if (value === undefined) {
  2438. // In case the value is the same for all materials
  2439. value = uniform.value;
  2440. }
  2441. if (!value) {
  2442. continue;
  2443. }
  2444. var onLoadTexture = function (uniformName) {
  2445. return function (texture) {
  2446. if (uniform.value && uniformName) {
  2447. // Static uniform
  2448. shaderMaterial.setTexture(uniformName, texture);
  2449. delete unTreatedUniforms[uniformName];
  2450. }
  2451. };
  2452. };
  2453. // Texture (sampler2D)
  2454. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2455. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2456. }
  2457. // Others
  2458. else {
  2459. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2460. // Static uniform
  2461. delete unTreatedUniforms[unif];
  2462. }
  2463. }
  2464. }
  2465. };
  2466. /**
  2467. * Shader compilation failed
  2468. */
  2469. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2470. return function (effect, error) {
  2471. shaderMaterial.dispose(true);
  2472. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2473. };
  2474. };
  2475. /**
  2476. * Shader compilation success
  2477. */
  2478. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2479. return function (_) {
  2480. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2481. shaderMaterial.onBind = function (mesh) {
  2482. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2483. };
  2484. };
  2485. };
  2486. /**
  2487. * Returns the appropriate uniform if already handled by babylon
  2488. */
  2489. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2490. for (var unif in technique.uniforms) {
  2491. var uniform = technique.uniforms[unif];
  2492. var uniformParameter = technique.parameters[uniform];
  2493. if (tokenizer.currentIdentifier === unif) {
  2494. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2495. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2496. if (transformIndex !== -1) {
  2497. delete unTreatedUniforms[unif];
  2498. return babylonTransforms[transformIndex];
  2499. }
  2500. }
  2501. }
  2502. }
  2503. return tokenizer.currentIdentifier;
  2504. };
  2505. /**
  2506. * All shaders loaded. Create materials one by one
  2507. */
  2508. var importMaterials = function (gltfRuntime) {
  2509. // Create materials
  2510. for (var mat in gltfRuntime.materials) {
  2511. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2512. }
  2513. };
  2514. /**
  2515. * Implementation of the base glTF spec
  2516. * @hidden
  2517. */
  2518. var GLTFLoaderBase = /** @class */ (function () {
  2519. function GLTFLoaderBase() {
  2520. }
  2521. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2522. var gltfRuntime = {
  2523. extensions: {},
  2524. accessors: {},
  2525. buffers: {},
  2526. bufferViews: {},
  2527. meshes: {},
  2528. lights: {},
  2529. cameras: {},
  2530. nodes: {},
  2531. images: {},
  2532. textures: {},
  2533. shaders: {},
  2534. programs: {},
  2535. samplers: {},
  2536. techniques: {},
  2537. materials: {},
  2538. animations: {},
  2539. skins: {},
  2540. extensionsUsed: [],
  2541. scenes: {},
  2542. buffersCount: 0,
  2543. shaderscount: 0,
  2544. scene: scene,
  2545. rootUrl: rootUrl,
  2546. loadedBufferCount: 0,
  2547. loadedBufferViews: {},
  2548. loadedShaderCount: 0,
  2549. importOnlyMeshes: false,
  2550. dummyNodes: []
  2551. };
  2552. // Parse
  2553. if (parsedData.extensions) {
  2554. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2555. }
  2556. if (parsedData.extensionsUsed) {
  2557. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2558. }
  2559. if (parsedData.buffers) {
  2560. parseBuffers(parsedData.buffers, gltfRuntime);
  2561. }
  2562. if (parsedData.bufferViews) {
  2563. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2564. }
  2565. if (parsedData.accessors) {
  2566. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2567. }
  2568. if (parsedData.meshes) {
  2569. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2570. }
  2571. if (parsedData.lights) {
  2572. parseObject(parsedData.lights, "lights", gltfRuntime);
  2573. }
  2574. if (parsedData.cameras) {
  2575. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2576. }
  2577. if (parsedData.nodes) {
  2578. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2579. }
  2580. if (parsedData.images) {
  2581. parseObject(parsedData.images, "images", gltfRuntime);
  2582. }
  2583. if (parsedData.textures) {
  2584. parseObject(parsedData.textures, "textures", gltfRuntime);
  2585. }
  2586. if (parsedData.shaders) {
  2587. parseShaders(parsedData.shaders, gltfRuntime);
  2588. }
  2589. if (parsedData.programs) {
  2590. parseObject(parsedData.programs, "programs", gltfRuntime);
  2591. }
  2592. if (parsedData.samplers) {
  2593. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2594. }
  2595. if (parsedData.techniques) {
  2596. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2597. }
  2598. if (parsedData.materials) {
  2599. parseObject(parsedData.materials, "materials", gltfRuntime);
  2600. }
  2601. if (parsedData.animations) {
  2602. parseObject(parsedData.animations, "animations", gltfRuntime);
  2603. }
  2604. if (parsedData.skins) {
  2605. parseObject(parsedData.skins, "skins", gltfRuntime);
  2606. }
  2607. if (parsedData.scenes) {
  2608. gltfRuntime.scenes = parsedData.scenes;
  2609. }
  2610. if (parsedData.scene && parsedData.scenes) {
  2611. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2612. }
  2613. return gltfRuntime;
  2614. };
  2615. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2616. var buffer = gltfRuntime.buffers[id];
  2617. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  2618. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  2619. }
  2620. else {
  2621. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2622. if (request) {
  2623. onError(request.status + " " + request.statusText);
  2624. }
  2625. });
  2626. }
  2627. };
  2628. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2629. var texture = gltfRuntime.textures[id];
  2630. if (!texture || !texture.source) {
  2631. onError("");
  2632. return;
  2633. }
  2634. if (texture.babylonTexture) {
  2635. onSuccess(null);
  2636. return;
  2637. }
  2638. var source = gltfRuntime.images[texture.source];
  2639. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  2640. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  2641. }
  2642. else {
  2643. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  2644. if (request) {
  2645. onError(request.status + " " + request.statusText);
  2646. }
  2647. });
  2648. }
  2649. };
  2650. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2651. var texture = gltfRuntime.textures[id];
  2652. if (texture.babylonTexture) {
  2653. onSuccess(texture.babylonTexture);
  2654. return;
  2655. }
  2656. var sampler = gltfRuntime.samplers[texture.sampler];
  2657. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2658. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2659. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2660. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2661. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  2662. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  2663. var blobURL = URL.createObjectURL(blob);
  2664. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2665. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2666. if (sampler.wrapS !== undefined) {
  2667. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2668. }
  2669. if (sampler.wrapT !== undefined) {
  2670. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2671. }
  2672. newTexture.name = id;
  2673. texture.babylonTexture = newTexture;
  2674. onSuccess(newTexture);
  2675. };
  2676. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2677. var shader = gltfRuntime.shaders[id];
  2678. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  2679. var shaderString = atob(shader.uri.split(",")[1]);
  2680. if (onSuccess) {
  2681. onSuccess(shaderString);
  2682. }
  2683. }
  2684. else {
  2685. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  2686. if (request && onError) {
  2687. onError(request.status + " " + request.statusText);
  2688. }
  2689. });
  2690. }
  2691. };
  2692. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2693. var material = gltfRuntime.materials[id];
  2694. if (!material.technique) {
  2695. if (onError) {
  2696. onError("No technique found.");
  2697. }
  2698. return;
  2699. }
  2700. var technique = gltfRuntime.techniques[material.technique];
  2701. if (!technique) {
  2702. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  2703. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  2704. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2705. onSuccess(defaultMaterial);
  2706. return;
  2707. }
  2708. var program = gltfRuntime.programs[technique.program];
  2709. var states = technique.states;
  2710. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2711. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2712. var newVertexShader = "";
  2713. var newPixelShader = "";
  2714. var vertexTokenizer = new Tokenizer(vertexShader);
  2715. var pixelTokenizer = new Tokenizer(pixelShader);
  2716. var unTreatedUniforms = {};
  2717. var uniforms = [];
  2718. var attributes = [];
  2719. var samplers = [];
  2720. // Fill uniform, sampler2D and attributes
  2721. for (var unif in technique.uniforms) {
  2722. var uniform = technique.uniforms[unif];
  2723. var uniformParameter = technique.parameters[uniform];
  2724. unTreatedUniforms[unif] = uniformParameter;
  2725. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2726. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2727. if (transformIndex !== -1) {
  2728. uniforms.push(babylonTransforms[transformIndex]);
  2729. delete unTreatedUniforms[unif];
  2730. }
  2731. else {
  2732. uniforms.push(unif);
  2733. }
  2734. }
  2735. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  2736. samplers.push(unif);
  2737. }
  2738. else {
  2739. uniforms.push(unif);
  2740. }
  2741. }
  2742. for (var attr in technique.attributes) {
  2743. var attribute = technique.attributes[attr];
  2744. var attributeParameter = technique.parameters[attribute];
  2745. if (attributeParameter.semantic) {
  2746. var name_1 = getAttribute(attributeParameter);
  2747. if (name_1) {
  2748. attributes.push(name_1);
  2749. }
  2750. }
  2751. }
  2752. // Configure vertex shader
  2753. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2754. var tokenType = vertexTokenizer.currentToken;
  2755. if (tokenType !== ETokenType.IDENTIFIER) {
  2756. newVertexShader += vertexTokenizer.currentString;
  2757. continue;
  2758. }
  2759. var foundAttribute = false;
  2760. for (var attr in technique.attributes) {
  2761. var attribute = technique.attributes[attr];
  2762. var attributeParameter = technique.parameters[attribute];
  2763. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2764. newVertexShader += getAttribute(attributeParameter);
  2765. foundAttribute = true;
  2766. break;
  2767. }
  2768. }
  2769. if (foundAttribute) {
  2770. continue;
  2771. }
  2772. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2773. }
  2774. // Configure pixel shader
  2775. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2776. var tokenType = pixelTokenizer.currentToken;
  2777. if (tokenType !== ETokenType.IDENTIFIER) {
  2778. newPixelShader += pixelTokenizer.currentString;
  2779. continue;
  2780. }
  2781. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2782. }
  2783. // Create shader material
  2784. var shaderPath = {
  2785. vertex: program.vertexShader + id,
  2786. fragment: program.fragmentShader + id
  2787. };
  2788. var options = {
  2789. attributes: attributes,
  2790. uniforms: uniforms,
  2791. samplers: samplers,
  2792. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2793. };
  2794. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2795. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2796. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2797. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2798. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2799. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2800. if (states && states.functions) {
  2801. var functions = states.functions;
  2802. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  2803. shaderMaterial.backFaceCulling = false;
  2804. }
  2805. var blendFunc = functions.blendFuncSeparate;
  2806. if (blendFunc) {
  2807. if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2808. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  2809. }
  2810. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2811. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  2812. }
  2813. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2814. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  2815. }
  2816. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2817. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  2818. }
  2819. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.DST_COLOR && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2820. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  2821. }
  2822. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  2823. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  2824. }
  2825. }
  2826. }
  2827. };
  2828. return GLTFLoaderBase;
  2829. }());
  2830. exports.GLTFLoaderBase = GLTFLoaderBase;
  2831. /**
  2832. * glTF V1 Loader
  2833. * @hidden
  2834. */
  2835. var GLTFLoader = /** @class */ (function () {
  2836. function GLTFLoader() {
  2837. this.state = null;
  2838. }
  2839. GLTFLoader.RegisterExtension = function (extension) {
  2840. if (GLTFLoader.Extensions[extension.name]) {
  2841. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2842. return;
  2843. }
  2844. GLTFLoader.Extensions[extension.name] = extension;
  2845. };
  2846. GLTFLoader.prototype.dispose = function () {
  2847. // do nothing
  2848. };
  2849. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2850. var _this = this;
  2851. scene.useRightHandedSystem = true;
  2852. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2853. gltfRuntime.importOnlyMeshes = true;
  2854. if (meshesNames === "") {
  2855. gltfRuntime.importMeshesNames = [];
  2856. }
  2857. else if (typeof meshesNames === "string") {
  2858. gltfRuntime.importMeshesNames = [meshesNames];
  2859. }
  2860. else if (meshesNames && !(meshesNames instanceof Array)) {
  2861. gltfRuntime.importMeshesNames = [meshesNames];
  2862. }
  2863. else {
  2864. gltfRuntime.importMeshesNames = [];
  2865. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2866. }
  2867. // Create nodes
  2868. _this._createNodes(gltfRuntime);
  2869. var meshes = new Array();
  2870. var skeletons = new Array();
  2871. // Fill arrays of meshes and skeletons
  2872. for (var nde in gltfRuntime.nodes) {
  2873. var node = gltfRuntime.nodes[nde];
  2874. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  2875. meshes.push(node.babylonNode);
  2876. }
  2877. }
  2878. for (var skl in gltfRuntime.skins) {
  2879. var skin = gltfRuntime.skins[skl];
  2880. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  2881. skeletons.push(skin.babylonSkeleton);
  2882. }
  2883. }
  2884. // Load buffers, shaders, materials, etc.
  2885. _this._loadBuffersAsync(gltfRuntime, function () {
  2886. _this._loadShadersAsync(gltfRuntime, function () {
  2887. importMaterials(gltfRuntime);
  2888. postLoad(gltfRuntime);
  2889. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2890. onSuccess(meshes, skeletons);
  2891. }
  2892. });
  2893. }, onProgress);
  2894. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2895. onSuccess(meshes, skeletons);
  2896. }
  2897. }, onError);
  2898. return true;
  2899. };
  2900. /**
  2901. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2902. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2903. * @param scene the scene the meshes should be added to
  2904. * @param data gltf data containing information of the meshes in a loaded file
  2905. * @param rootUrl root url to load from
  2906. * @param onProgress event that fires when loading progress has occured
  2907. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2908. */
  2909. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2910. var _this = this;
  2911. return new Promise(function (resolve, reject) {
  2912. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  2913. resolve({
  2914. meshes: meshes,
  2915. particleSystems: [],
  2916. skeletons: skeletons,
  2917. animationGroups: []
  2918. });
  2919. }, onProgress, function (message) {
  2920. reject(new Error(message));
  2921. });
  2922. });
  2923. };
  2924. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2925. var _this = this;
  2926. scene.useRightHandedSystem = true;
  2927. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2928. // Load runtime extensios
  2929. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2930. // Create nodes
  2931. _this._createNodes(gltfRuntime);
  2932. // Load buffers, shaders, materials, etc.
  2933. _this._loadBuffersAsync(gltfRuntime, function () {
  2934. _this._loadShadersAsync(gltfRuntime, function () {
  2935. importMaterials(gltfRuntime);
  2936. postLoad(gltfRuntime);
  2937. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  2938. onSuccess();
  2939. }
  2940. });
  2941. });
  2942. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  2943. onSuccess();
  2944. }
  2945. }, onError);
  2946. }, onError);
  2947. };
  2948. /**
  2949. * Imports all objects from a loaded gltf file and adds them to the scene
  2950. * @param scene the scene the objects should be added to
  2951. * @param data gltf data containing information of the meshes in a loaded file
  2952. * @param rootUrl root url to load from
  2953. * @param onProgress event that fires when loading progress has occured
  2954. * @returns a promise which completes when objects have been loaded to the scene
  2955. */
  2956. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2957. var _this = this;
  2958. return new Promise(function (resolve, reject) {
  2959. _this._loadAsync(scene, data, rootUrl, function () {
  2960. resolve();
  2961. }, onProgress, function (message) {
  2962. reject(new Error(message));
  2963. });
  2964. });
  2965. };
  2966. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2967. var hasShaders = false;
  2968. var processShader = function (sha, shader) {
  2969. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2970. if (shaderString instanceof ArrayBuffer) {
  2971. return;
  2972. }
  2973. gltfRuntime.loadedShaderCount++;
  2974. if (shaderString) {
  2975. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2976. }
  2977. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2978. onload();
  2979. }
  2980. }, function () {
  2981. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2982. });
  2983. };
  2984. for (var sha in gltfRuntime.shaders) {
  2985. hasShaders = true;
  2986. var shader = gltfRuntime.shaders[sha];
  2987. if (shader) {
  2988. processShader.bind(this, sha, shader)();
  2989. }
  2990. else {
  2991. babylonjs_1.Tools.Error("No shader named: " + sha);
  2992. }
  2993. }
  2994. if (!hasShaders) {
  2995. onload();
  2996. }
  2997. };
  2998. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2999. var hasBuffers = false;
  3000. var processBuffer = function (buf, buffer) {
  3001. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  3002. gltfRuntime.loadedBufferCount++;
  3003. if (bufferView) {
  3004. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  3005. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  3006. }
  3007. gltfRuntime.loadedBufferViews[buf] = bufferView;
  3008. }
  3009. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  3010. onLoad();
  3011. }
  3012. }, function () {
  3013. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  3014. });
  3015. };
  3016. for (var buf in gltfRuntime.buffers) {
  3017. hasBuffers = true;
  3018. var buffer = gltfRuntime.buffers[buf];
  3019. if (buffer) {
  3020. processBuffer.bind(this, buf, buffer)();
  3021. }
  3022. else {
  3023. babylonjs_1.Tools.Error("No buffer named: " + buf);
  3024. }
  3025. }
  3026. if (!hasBuffers) {
  3027. onLoad();
  3028. }
  3029. };
  3030. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  3031. var currentScene = gltfRuntime.currentScene;
  3032. if (currentScene) {
  3033. // Only one scene even if multiple scenes are defined
  3034. for (var i = 0; i < currentScene.nodes.length; i++) {
  3035. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3036. }
  3037. }
  3038. else {
  3039. // Load all scenes
  3040. for (var thing in gltfRuntime.scenes) {
  3041. currentScene = gltfRuntime.scenes[thing];
  3042. for (var i = 0; i < currentScene.nodes.length; i++) {
  3043. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3044. }
  3045. }
  3046. }
  3047. };
  3048. GLTFLoader.Extensions = {};
  3049. return GLTFLoader;
  3050. }());
  3051. exports.GLTFLoader = GLTFLoader;
  3052. glTFFileLoader_1.GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
  3053. /***/ }),
  3054. /***/ "./src/glTF/1.0/glTFLoaderExtension.ts":
  3055. /*!*********************************************!*\
  3056. !*** ./src/glTF/1.0/glTFLoaderExtension.ts ***!
  3057. \*********************************************/
  3058. /*! no static exports found */
  3059. /***/ (function(module, exports, __webpack_require__) {
  3060. "use strict";
  3061. Object.defineProperty(exports, "__esModule", { value: true });
  3062. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  3063. /** @hidden */
  3064. var GLTFLoaderExtension = /** @class */ (function () {
  3065. function GLTFLoaderExtension(name) {
  3066. this._name = name;
  3067. }
  3068. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3069. get: function () {
  3070. return this._name;
  3071. },
  3072. enumerable: true,
  3073. configurable: true
  3074. });
  3075. /**
  3076. * Defines an override for loading the runtime
  3077. * Return true to stop further extensions from loading the runtime
  3078. */
  3079. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3080. return false;
  3081. };
  3082. /**
  3083. * Defines an onverride for creating gltf runtime
  3084. * Return true to stop further extensions from creating the runtime
  3085. */
  3086. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3087. return false;
  3088. };
  3089. /**
  3090. * Defines an override for loading buffers
  3091. * Return true to stop further extensions from loading this buffer
  3092. */
  3093. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3094. return false;
  3095. };
  3096. /**
  3097. * Defines an override for loading texture buffers
  3098. * Return true to stop further extensions from loading this texture data
  3099. */
  3100. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3101. return false;
  3102. };
  3103. /**
  3104. * Defines an override for creating textures
  3105. * Return true to stop further extensions from loading this texture
  3106. */
  3107. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3108. return false;
  3109. };
  3110. /**
  3111. * Defines an override for loading shader strings
  3112. * Return true to stop further extensions from loading this shader data
  3113. */
  3114. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3115. return false;
  3116. };
  3117. /**
  3118. * Defines an override for loading materials
  3119. * Return true to stop further extensions from loading this material
  3120. */
  3121. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3122. return false;
  3123. };
  3124. // ---------
  3125. // Utilities
  3126. // ---------
  3127. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3128. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3129. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3130. }, function () {
  3131. setTimeout(function () {
  3132. if (!onSuccess) {
  3133. return;
  3134. }
  3135. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3136. });
  3137. });
  3138. };
  3139. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3140. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3141. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3142. }, function () {
  3143. setTimeout(function () {
  3144. onSuccess();
  3145. });
  3146. });
  3147. };
  3148. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3149. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3150. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3151. }, function () {
  3152. glTFLoader_1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3153. });
  3154. };
  3155. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3156. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3157. if (buffer) {
  3158. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3159. }
  3160. }, onError);
  3161. };
  3162. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3163. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3164. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3165. }, function () {
  3166. glTFLoader_1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3167. });
  3168. };
  3169. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3170. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3171. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3172. }, function () {
  3173. glTFLoader_1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3174. });
  3175. };
  3176. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3177. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3178. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3179. }, function () {
  3180. glTFLoader_1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3181. });
  3182. };
  3183. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3184. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3185. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3186. }, function () {
  3187. glTFLoader_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3188. });
  3189. };
  3190. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3191. for (var extensionName in glTFLoader_1.GLTFLoader.Extensions) {
  3192. var loaderExtension = glTFLoader_1.GLTFLoader.Extensions[extensionName];
  3193. if (func(loaderExtension)) {
  3194. return;
  3195. }
  3196. }
  3197. defaultFunc();
  3198. };
  3199. return GLTFLoaderExtension;
  3200. }());
  3201. exports.GLTFLoaderExtension = GLTFLoaderExtension;
  3202. /***/ }),
  3203. /***/ "./src/glTF/1.0/glTFLoaderInterfaces.ts":
  3204. /*!**********************************************!*\
  3205. !*** ./src/glTF/1.0/glTFLoaderInterfaces.ts ***!
  3206. \**********************************************/
  3207. /*! no static exports found */
  3208. /***/ (function(module, exports, __webpack_require__) {
  3209. "use strict";
  3210. Object.defineProperty(exports, "__esModule", { value: true });
  3211. /**
  3212. * Enums
  3213. * @hidden
  3214. */
  3215. var EComponentType;
  3216. (function (EComponentType) {
  3217. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  3218. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  3219. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  3220. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  3221. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  3222. })(EComponentType = exports.EComponentType || (exports.EComponentType = {}));
  3223. /** @hidden */
  3224. var EShaderType;
  3225. (function (EShaderType) {
  3226. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  3227. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  3228. })(EShaderType = exports.EShaderType || (exports.EShaderType = {}));
  3229. /** @hidden */
  3230. var EParameterType;
  3231. (function (EParameterType) {
  3232. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  3233. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  3234. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  3235. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  3236. EParameterType[EParameterType["INT"] = 5124] = "INT";
  3237. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  3238. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  3239. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  3240. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  3241. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  3242. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  3243. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  3244. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  3245. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  3246. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  3247. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  3248. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  3249. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  3250. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  3251. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  3252. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  3253. })(EParameterType = exports.EParameterType || (exports.EParameterType = {}));
  3254. /** @hidden */
  3255. var ETextureWrapMode;
  3256. (function (ETextureWrapMode) {
  3257. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  3258. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  3259. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  3260. })(ETextureWrapMode = exports.ETextureWrapMode || (exports.ETextureWrapMode = {}));
  3261. /** @hidden */
  3262. var ETextureFilterType;
  3263. (function (ETextureFilterType) {
  3264. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  3265. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  3266. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  3267. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  3268. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  3269. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  3270. })(ETextureFilterType = exports.ETextureFilterType || (exports.ETextureFilterType = {}));
  3271. /** @hidden */
  3272. var ETextureFormat;
  3273. (function (ETextureFormat) {
  3274. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  3275. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  3276. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  3277. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  3278. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  3279. })(ETextureFormat = exports.ETextureFormat || (exports.ETextureFormat = {}));
  3280. /** @hidden */
  3281. var ECullingType;
  3282. (function (ECullingType) {
  3283. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  3284. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  3285. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  3286. })(ECullingType = exports.ECullingType || (exports.ECullingType = {}));
  3287. /** @hidden */
  3288. var EBlendingFunction;
  3289. (function (EBlendingFunction) {
  3290. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  3291. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  3292. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  3293. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  3294. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  3295. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  3296. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  3297. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  3298. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  3299. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  3300. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  3301. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  3302. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  3303. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  3304. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  3305. })(EBlendingFunction = exports.EBlendingFunction || (exports.EBlendingFunction = {}));
  3306. /***/ }),
  3307. /***/ "./src/glTF/1.0/glTFLoaderUtils.ts":
  3308. /*!*****************************************!*\
  3309. !*** ./src/glTF/1.0/glTFLoaderUtils.ts ***!
  3310. \*****************************************/
  3311. /*! no static exports found */
  3312. /***/ (function(module, exports, __webpack_require__) {
  3313. "use strict";
  3314. Object.defineProperty(exports, "__esModule", { value: true });
  3315. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3316. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  3317. /**
  3318. * Utils functions for GLTF
  3319. * @hidden
  3320. */
  3321. var GLTFUtils = /** @class */ (function () {
  3322. function GLTFUtils() {
  3323. }
  3324. /**
  3325. * Sets the given "parameter" matrix
  3326. * @param scene: the Scene object
  3327. * @param source: the source node where to pick the matrix
  3328. * @param parameter: the GLTF technique parameter
  3329. * @param uniformName: the name of the shader's uniform
  3330. * @param shaderMaterial: the shader material
  3331. */
  3332. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  3333. var mat = null;
  3334. if (parameter.semantic === "MODEL") {
  3335. mat = source.getWorldMatrix();
  3336. }
  3337. else if (parameter.semantic === "PROJECTION") {
  3338. mat = scene.getProjectionMatrix();
  3339. }
  3340. else if (parameter.semantic === "VIEW") {
  3341. mat = scene.getViewMatrix();
  3342. }
  3343. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  3344. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  3345. }
  3346. else if (parameter.semantic === "MODELVIEW") {
  3347. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  3348. }
  3349. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  3350. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  3351. }
  3352. else if (parameter.semantic === "MODELINVERSE") {
  3353. mat = source.getWorldMatrix().invert();
  3354. }
  3355. else if (parameter.semantic === "VIEWINVERSE") {
  3356. mat = scene.getViewMatrix().invert();
  3357. }
  3358. else if (parameter.semantic === "PROJECTIONINVERSE") {
  3359. mat = scene.getProjectionMatrix().invert();
  3360. }
  3361. else if (parameter.semantic === "MODELVIEWINVERSE") {
  3362. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  3363. }
  3364. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  3365. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  3366. }
  3367. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  3368. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().invert());
  3369. }
  3370. else {
  3371. debugger;
  3372. }
  3373. if (mat) {
  3374. switch (parameter.type) {
  3375. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2:
  3376. shaderMaterial.setMatrix2x2(uniformName, babylonjs_1.Matrix.GetAsMatrix2x2(mat));
  3377. break;
  3378. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3:
  3379. shaderMaterial.setMatrix3x3(uniformName, babylonjs_1.Matrix.GetAsMatrix3x3(mat));
  3380. break;
  3381. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4:
  3382. shaderMaterial.setMatrix(uniformName, mat);
  3383. break;
  3384. default: break;
  3385. }
  3386. }
  3387. };
  3388. /**
  3389. * Sets the given "parameter" matrix
  3390. * @param shaderMaterial: the shader material
  3391. * @param uniform: the name of the shader's uniform
  3392. * @param value: the value of the uniform
  3393. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  3394. */
  3395. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  3396. switch (type) {
  3397. case glTFLoaderInterfaces_1.EParameterType.FLOAT:
  3398. shaderMaterial.setFloat(uniform, value);
  3399. return true;
  3400. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC2:
  3401. shaderMaterial.setVector2(uniform, babylonjs_1.Vector2.FromArray(value));
  3402. return true;
  3403. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC3:
  3404. shaderMaterial.setVector3(uniform, babylonjs_1.Vector3.FromArray(value));
  3405. return true;
  3406. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC4:
  3407. shaderMaterial.setVector4(uniform, babylonjs_1.Vector4.FromArray(value));
  3408. return true;
  3409. default: return false;
  3410. }
  3411. };
  3412. /**
  3413. * Returns the wrap mode of the texture
  3414. * @param mode: the mode value
  3415. */
  3416. GLTFUtils.GetWrapMode = function (mode) {
  3417. switch (mode) {
  3418. case glTFLoaderInterfaces_1.ETextureWrapMode.CLAMP_TO_EDGE: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  3419. case glTFLoaderInterfaces_1.ETextureWrapMode.MIRRORED_REPEAT: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  3420. case glTFLoaderInterfaces_1.ETextureWrapMode.REPEAT: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  3421. default: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  3422. }
  3423. };
  3424. /**
  3425. * Returns the byte stride giving an accessor
  3426. * @param accessor: the GLTF accessor objet
  3427. */
  3428. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3429. // Needs this function since "byteStride" isn't requiered in glTF format
  3430. var type = accessor.type;
  3431. switch (type) {
  3432. case "VEC2": return 2;
  3433. case "VEC3": return 3;
  3434. case "VEC4": return 4;
  3435. case "MAT2": return 4;
  3436. case "MAT3": return 9;
  3437. case "MAT4": return 16;
  3438. default: return 1;
  3439. }
  3440. };
  3441. /**
  3442. * Returns the texture filter mode giving a mode value
  3443. * @param mode: the filter mode value
  3444. */
  3445. GLTFUtils.GetTextureFilterMode = function (mode) {
  3446. switch (mode) {
  3447. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR:
  3448. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  3449. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return babylonjs_1.Texture.TRILINEAR_SAMPLINGMODE;
  3450. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST:
  3451. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return babylonjs_1.Texture.NEAREST_SAMPLINGMODE;
  3452. default: return babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  3453. }
  3454. };
  3455. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  3456. var byteOffset = bufferView.byteOffset + byteOffset;
  3457. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  3458. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3459. throw new Error("Buffer access is out of range");
  3460. }
  3461. var buffer = loadedBufferView.buffer;
  3462. byteOffset += loadedBufferView.byteOffset;
  3463. switch (componentType) {
  3464. case glTFLoaderInterfaces_1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3465. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3466. case glTFLoaderInterfaces_1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3467. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3468. default: return new Float32Array(buffer, byteOffset, byteLength);
  3469. }
  3470. };
  3471. /**
  3472. * Returns a buffer from its accessor
  3473. * @param gltfRuntime: the GLTF runtime
  3474. * @param accessor: the GLTF accessor
  3475. */
  3476. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  3477. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  3478. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3479. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3480. };
  3481. /**
  3482. * Decodes a buffer view into a string
  3483. * @param view: the buffer view
  3484. */
  3485. GLTFUtils.DecodeBufferToText = function (view) {
  3486. var result = "";
  3487. var length = view.byteLength;
  3488. for (var i = 0; i < length; ++i) {
  3489. result += String.fromCharCode(view[i]);
  3490. }
  3491. return result;
  3492. };
  3493. /**
  3494. * Returns the default material of gltf. Related to
  3495. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  3496. * @param scene: the Babylon.js scene
  3497. */
  3498. GLTFUtils.GetDefaultMaterial = function (scene) {
  3499. if (!GLTFUtils._DefaultMaterial) {
  3500. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  3501. "precision highp float;",
  3502. "",
  3503. "uniform mat4 worldView;",
  3504. "uniform mat4 projection;",
  3505. "",
  3506. "attribute vec3 position;",
  3507. "",
  3508. "void main(void)",
  3509. "{",
  3510. " gl_Position = projection * worldView * vec4(position, 1.0);",
  3511. "}"
  3512. ].join("\n");
  3513. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  3514. "precision highp float;",
  3515. "",
  3516. "uniform vec4 u_emission;",
  3517. "",
  3518. "void main(void)",
  3519. "{",
  3520. " gl_FragColor = u_emission;",
  3521. "}"
  3522. ].join("\n");
  3523. var shaderPath = {
  3524. vertex: "GLTFDefaultMaterial",
  3525. fragment: "GLTFDefaultMaterial"
  3526. };
  3527. var options = {
  3528. attributes: ["position"],
  3529. uniforms: ["worldView", "projection", "u_emission"],
  3530. samplers: new Array(),
  3531. needAlphaBlending: false
  3532. };
  3533. GLTFUtils._DefaultMaterial = new babylonjs_1.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  3534. GLTFUtils._DefaultMaterial.setColor4("u_emission", new babylonjs_1.Color4(0.5, 0.5, 0.5, 1.0));
  3535. }
  3536. return GLTFUtils._DefaultMaterial;
  3537. };
  3538. // The GLTF default material
  3539. GLTFUtils._DefaultMaterial = null;
  3540. return GLTFUtils;
  3541. }());
  3542. exports.GLTFUtils = GLTFUtils;
  3543. /***/ }),
  3544. /***/ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts":
  3545. /*!******************************************************!*\
  3546. !*** ./src/glTF/1.0/glTFMaterialsCommonExtension.ts ***!
  3547. \******************************************************/
  3548. /*! no static exports found */
  3549. /***/ (function(module, exports, __webpack_require__) {
  3550. "use strict";
  3551. var __extends = (this && this.__extends) || (function () {
  3552. var extendStatics = function (d, b) {
  3553. extendStatics = Object.setPrototypeOf ||
  3554. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3555. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3556. return extendStatics(d, b);
  3557. }
  3558. return function (d, b) {
  3559. extendStatics(d, b);
  3560. function __() { this.constructor = d; }
  3561. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3562. };
  3563. })();
  3564. Object.defineProperty(exports, "__esModule", { value: true });
  3565. var _1 = __webpack_require__(/*! . */ "./src/glTF/1.0/index.ts");
  3566. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3567. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  3568. /** @hidden */
  3569. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3570. __extends(GLTFMaterialsCommonExtension, _super);
  3571. function GLTFMaterialsCommonExtension() {
  3572. return _super.call(this, "KHR_materials_common") || this;
  3573. }
  3574. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3575. if (!gltfRuntime.extensions) {
  3576. return false;
  3577. }
  3578. var extension = gltfRuntime.extensions[this.name];
  3579. if (!extension) {
  3580. return false;
  3581. }
  3582. // Create lights
  3583. var lights = extension.lights;
  3584. if (lights) {
  3585. for (var thing in lights) {
  3586. var light = lights[thing];
  3587. switch (light.type) {
  3588. case "ambient":
  3589. var ambientLight = new babylonjs_1.HemisphericLight(light.name, new babylonjs_1.Vector3(0, 1, 0), gltfRuntime.scene);
  3590. var ambient = light.ambient;
  3591. if (ambient) {
  3592. ambientLight.diffuse = babylonjs_1.Color3.FromArray(ambient.color || [1, 1, 1]);
  3593. }
  3594. break;
  3595. case "point":
  3596. var pointLight = new babylonjs_1.PointLight(light.name, new babylonjs_1.Vector3(10, 10, 10), gltfRuntime.scene);
  3597. var point = light.point;
  3598. if (point) {
  3599. pointLight.diffuse = babylonjs_1.Color3.FromArray(point.color || [1, 1, 1]);
  3600. }
  3601. break;
  3602. case "directional":
  3603. var dirLight = new babylonjs_1.DirectionalLight(light.name, new babylonjs_1.Vector3(0, -1, 0), gltfRuntime.scene);
  3604. var directional = light.directional;
  3605. if (directional) {
  3606. dirLight.diffuse = babylonjs_1.Color3.FromArray(directional.color || [1, 1, 1]);
  3607. }
  3608. break;
  3609. case "spot":
  3610. var spot = light.spot;
  3611. if (spot) {
  3612. var spotLight = new babylonjs_1.SpotLight(light.name, new babylonjs_1.Vector3(0, 10, 0), new babylonjs_1.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  3613. spotLight.diffuse = babylonjs_1.Color3.FromArray(spot.color || [1, 1, 1]);
  3614. }
  3615. break;
  3616. default:
  3617. babylonjs_1.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3618. break;
  3619. }
  3620. }
  3621. }
  3622. return false;
  3623. };
  3624. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3625. var material = gltfRuntime.materials[id];
  3626. if (!material || !material.extensions) {
  3627. return false;
  3628. }
  3629. var extension = material.extensions[this.name];
  3630. if (!extension) {
  3631. return false;
  3632. }
  3633. var standardMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  3634. standardMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  3635. if (extension.technique === "CONSTANT") {
  3636. standardMaterial.disableLighting = true;
  3637. }
  3638. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3639. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3640. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3641. // Ambient
  3642. if (typeof extension.values.ambient === "string") {
  3643. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3644. }
  3645. else {
  3646. standardMaterial.ambientColor = babylonjs_1.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3647. }
  3648. // Diffuse
  3649. if (typeof extension.values.diffuse === "string") {
  3650. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3651. }
  3652. else {
  3653. standardMaterial.diffuseColor = babylonjs_1.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3654. }
  3655. // Emission
  3656. if (typeof extension.values.emission === "string") {
  3657. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3658. }
  3659. else {
  3660. standardMaterial.emissiveColor = babylonjs_1.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3661. }
  3662. // Specular
  3663. if (typeof extension.values.specular === "string") {
  3664. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3665. }
  3666. else {
  3667. standardMaterial.specularColor = babylonjs_1.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3668. }
  3669. return true;
  3670. };
  3671. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3672. // Create buffer from texture url
  3673. _1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3674. // Create texture from buffer
  3675. _1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3676. }, onError);
  3677. };
  3678. return GLTFMaterialsCommonExtension;
  3679. }(_1.GLTFLoaderExtension));
  3680. exports.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3681. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3682. /***/ }),
  3683. /***/ "./src/glTF/1.0/index.ts":
  3684. /*!*******************************!*\
  3685. !*** ./src/glTF/1.0/index.ts ***!
  3686. \*******************************/
  3687. /*! no static exports found */
  3688. /***/ (function(module, exports, __webpack_require__) {
  3689. "use strict";
  3690. function __export(m) {
  3691. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3692. }
  3693. Object.defineProperty(exports, "__esModule", { value: true });
  3694. __export(__webpack_require__(/*! ./glTFBinaryExtension */ "./src/glTF/1.0/glTFBinaryExtension.ts"));
  3695. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts"));
  3696. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts"));
  3697. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts"));
  3698. __export(__webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts"));
  3699. __export(__webpack_require__(/*! ./glTFMaterialsCommonExtension */ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts"));
  3700. /***/ }),
  3701. /***/ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts":
  3702. /*!***********************************************************!*\
  3703. !*** ./src/glTF/2.0/Extensions/EXT_lights_image_based.ts ***!
  3704. \***********************************************************/
  3705. /*! no static exports found */
  3706. /***/ (function(module, exports, __webpack_require__) {
  3707. "use strict";
  3708. Object.defineProperty(exports, "__esModule", { value: true });
  3709. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3710. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3711. var NAME = "EXT_lights_image_based";
  3712. /**
  3713. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  3714. */
  3715. var EXT_lights_image_based = /** @class */ (function () {
  3716. /** @hidden */
  3717. function EXT_lights_image_based(loader) {
  3718. /** The name of this extension. */
  3719. this.name = NAME;
  3720. /** Defines whether this extension is enabled. */
  3721. this.enabled = true;
  3722. this._loader = loader;
  3723. }
  3724. /** @hidden */
  3725. EXT_lights_image_based.prototype.dispose = function () {
  3726. delete this._loader;
  3727. delete this._lights;
  3728. };
  3729. /** @hidden */
  3730. EXT_lights_image_based.prototype.onLoading = function () {
  3731. var extensions = this._loader.gltf.extensions;
  3732. if (extensions && extensions[this.name]) {
  3733. var extension = extensions[this.name];
  3734. this._lights = extension.lights;
  3735. }
  3736. };
  3737. /** @hidden */
  3738. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  3739. var _this = this;
  3740. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3741. var promises = new Array();
  3742. promises.push(_this._loader.loadSceneAsync(context, scene));
  3743. _this._loader.logOpen("" + extensionContext);
  3744. var light = glTFLoader_1.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  3745. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3746. _this._loader.babylonScene.environmentTexture = texture;
  3747. }));
  3748. _this._loader.logClose();
  3749. return Promise.all(promises).then(function () { });
  3750. });
  3751. };
  3752. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  3753. var _this = this;
  3754. if (!light._loaded) {
  3755. var promises = new Array();
  3756. this._loader.logOpen("" + context);
  3757. var imageData_1 = new Array(light.specularImages.length);
  3758. var _loop_1 = function (mipmap) {
  3759. var faces = light.specularImages[mipmap];
  3760. imageData_1[mipmap] = new Array(faces.length);
  3761. var _loop_2 = function (face) {
  3762. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3763. this_1._loader.logOpen("" + specularImageContext);
  3764. var index = faces[face];
  3765. var image = glTFLoader_1.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  3766. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  3767. imageData_1[mipmap][face] = data;
  3768. }));
  3769. this_1._loader.logClose();
  3770. };
  3771. for (var face = 0; face < faces.length; face++) {
  3772. _loop_2(face);
  3773. }
  3774. };
  3775. var this_1 = this;
  3776. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3777. _loop_1(mipmap);
  3778. }
  3779. this._loader.logClose();
  3780. light._loaded = Promise.all(promises).then(function () {
  3781. var babylonTexture = new babylonjs_1.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  3782. light._babylonTexture = babylonTexture;
  3783. if (light.intensity != undefined) {
  3784. babylonTexture.level = light.intensity;
  3785. }
  3786. if (light.rotation) {
  3787. var rotation = babylonjs_1.Quaternion.FromArray(light.rotation);
  3788. // Invert the rotation so that positive rotation is counter-clockwise.
  3789. if (!_this._loader.babylonScene.useRightHandedSystem) {
  3790. rotation = babylonjs_1.Quaternion.Inverse(rotation);
  3791. }
  3792. babylonjs_1.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3793. }
  3794. var sphericalHarmonics = babylonjs_1.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3795. sphericalHarmonics.scale(light.intensity);
  3796. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3797. var sphericalPolynomial = babylonjs_1.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3798. // Compute the lod generation scale to fit exactly to the number of levels available.
  3799. var lodGenerationScale = (imageData_1.length - 1) / babylonjs_1.Scalar.Log2(light.specularImageSize);
  3800. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3801. });
  3802. }
  3803. return light._loaded.then(function () {
  3804. return light._babylonTexture;
  3805. });
  3806. };
  3807. return EXT_lights_image_based;
  3808. }());
  3809. exports.EXT_lights_image_based = EXT_lights_image_based;
  3810. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  3811. /***/ }),
  3812. /***/ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts":
  3813. /*!***************************************************************!*\
  3814. !*** ./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***!
  3815. \***************************************************************/
  3816. /*! no static exports found */
  3817. /***/ (function(module, exports, __webpack_require__) {
  3818. "use strict";
  3819. Object.defineProperty(exports, "__esModule", { value: true });
  3820. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3821. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3822. var NAME = "KHR_draco_mesh_compression";
  3823. /**
  3824. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3825. */
  3826. var KHR_draco_mesh_compression = /** @class */ (function () {
  3827. /** @hidden */
  3828. function KHR_draco_mesh_compression(loader) {
  3829. /** The name of this extension. */
  3830. this.name = NAME;
  3831. /** Defines whether this extension is enabled. */
  3832. this.enabled = babylonjs_1.DracoCompression.DecoderAvailable;
  3833. this._loader = loader;
  3834. }
  3835. /** @hidden */
  3836. KHR_draco_mesh_compression.prototype.dispose = function () {
  3837. if (this._dracoCompression) {
  3838. this._dracoCompression.dispose();
  3839. delete this._dracoCompression;
  3840. }
  3841. delete this._loader;
  3842. };
  3843. /** @hidden */
  3844. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3845. var _this = this;
  3846. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  3847. if (primitive.mode != undefined) {
  3848. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3849. primitive.mode !== 4 /* TRIANGLES */) {
  3850. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3851. }
  3852. // TODO: handle triangle strips
  3853. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3854. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3855. }
  3856. }
  3857. var attributes = {};
  3858. var loadAttribute = function (name, kind) {
  3859. var uniqueId = extension.attributes[name];
  3860. if (uniqueId == undefined) {
  3861. return;
  3862. }
  3863. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3864. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3865. babylonMesh._delayInfo.push(kind);
  3866. }
  3867. attributes[kind] = uniqueId;
  3868. };
  3869. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  3870. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  3871. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  3872. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  3873. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  3874. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  3875. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  3876. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind);
  3877. var bufferView = glTFLoader_1.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  3878. if (!bufferView._dracoBabylonGeometry) {
  3879. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  3880. if (!_this._dracoCompression) {
  3881. _this._dracoCompression = new babylonjs_1.DracoCompression();
  3882. }
  3883. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3884. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, _this._loader.babylonScene);
  3885. babylonVertexData.applyToGeometry(babylonGeometry);
  3886. return babylonGeometry;
  3887. }).catch(function (error) {
  3888. throw new Error(context + ": " + error.message);
  3889. });
  3890. });
  3891. }
  3892. return bufferView._dracoBabylonGeometry;
  3893. });
  3894. };
  3895. return KHR_draco_mesh_compression;
  3896. }());
  3897. exports.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3898. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3899. /***/ }),
  3900. /***/ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts":
  3901. /*!********************************************************!*\
  3902. !*** ./src/glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  3903. \********************************************************/
  3904. /*! no static exports found */
  3905. /***/ (function(module, exports, __webpack_require__) {
  3906. "use strict";
  3907. Object.defineProperty(exports, "__esModule", { value: true });
  3908. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3909. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3910. var NAME = "KHR_lights_punctual";
  3911. var LightType;
  3912. (function (LightType) {
  3913. LightType["DIRECTIONAL"] = "directional";
  3914. LightType["POINT"] = "point";
  3915. LightType["SPOT"] = "spot";
  3916. })(LightType || (LightType = {}));
  3917. /**
  3918. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  3919. */
  3920. var KHR_lights = /** @class */ (function () {
  3921. /** @hidden */
  3922. function KHR_lights(loader) {
  3923. /** The name of this extension. */
  3924. this.name = NAME;
  3925. /** Defines whether this extension is enabled. */
  3926. this.enabled = true;
  3927. this._loader = loader;
  3928. }
  3929. /** @hidden */
  3930. KHR_lights.prototype.dispose = function () {
  3931. delete this._loader;
  3932. delete this._lights;
  3933. };
  3934. /** @hidden */
  3935. KHR_lights.prototype.onLoading = function () {
  3936. var extensions = this._loader.gltf.extensions;
  3937. if (extensions && extensions[this.name]) {
  3938. var extension = extensions[this.name];
  3939. this._lights = extension.lights;
  3940. }
  3941. };
  3942. /** @hidden */
  3943. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  3944. var _this = this;
  3945. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3946. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  3947. var babylonLight;
  3948. var light = glTFLoader_1.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3949. var name = light.name || babylonMesh.name;
  3950. switch (light.type) {
  3951. case LightType.DIRECTIONAL: {
  3952. babylonLight = new babylonjs_1.DirectionalLight(name, babylonjs_1.Vector3.Backward(), _this._loader.babylonScene);
  3953. break;
  3954. }
  3955. case LightType.POINT: {
  3956. babylonLight = new babylonjs_1.PointLight(name, babylonjs_1.Vector3.Zero(), _this._loader.babylonScene);
  3957. break;
  3958. }
  3959. case LightType.SPOT: {
  3960. var babylonSpotLight = new babylonjs_1.SpotLight(name, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  3961. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  3962. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  3963. babylonLight = babylonSpotLight;
  3964. break;
  3965. }
  3966. default: {
  3967. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3968. }
  3969. }
  3970. babylonLight.falloffType = babylonjs_1.Light.FALLOFF_GLTF;
  3971. babylonLight.diffuse = light.color ? babylonjs_1.Color3.FromArray(light.color) : babylonjs_1.Color3.White();
  3972. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3973. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  3974. babylonLight.parent = babylonMesh;
  3975. assign(babylonMesh);
  3976. });
  3977. });
  3978. };
  3979. return KHR_lights;
  3980. }());
  3981. exports.KHR_lights = KHR_lights;
  3982. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  3983. /***/ }),
  3984. /***/ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts":
  3985. /*!************************************************************************!*\
  3986. !*** ./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***!
  3987. \************************************************************************/
  3988. /*! no static exports found */
  3989. /***/ (function(module, exports, __webpack_require__) {
  3990. "use strict";
  3991. Object.defineProperty(exports, "__esModule", { value: true });
  3992. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3993. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3994. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3995. /**
  3996. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3997. */
  3998. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  3999. /** @hidden */
  4000. function KHR_materials_pbrSpecularGlossiness(loader) {
  4001. /** The name of this extension. */
  4002. this.name = NAME;
  4003. /** Defines whether this extension is enabled. */
  4004. this.enabled = true;
  4005. this._loader = loader;
  4006. }
  4007. /** @hidden */
  4008. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  4009. delete this._loader;
  4010. };
  4011. /** @hidden */
  4012. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4013. var _this = this;
  4014. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  4015. var promises = new Array();
  4016. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4017. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  4018. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  4019. return Promise.all(promises).then(function () { });
  4020. });
  4021. };
  4022. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  4023. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4024. throw new Error(context + ": Material type not supported");
  4025. }
  4026. var promises = new Array();
  4027. babylonMaterial.metallic = null;
  4028. babylonMaterial.roughness = null;
  4029. if (properties.diffuseFactor) {
  4030. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.diffuseFactor);
  4031. babylonMaterial.alpha = properties.diffuseFactor[3];
  4032. }
  4033. else {
  4034. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  4035. }
  4036. babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_1.Color3.FromArray(properties.specularFactor) : babylonjs_1.Color3.White();
  4037. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4038. if (properties.diffuseTexture) {
  4039. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4040. babylonMaterial.albedoTexture = texture;
  4041. return Promise.resolve();
  4042. }));
  4043. }
  4044. if (properties.specularGlossinessTexture) {
  4045. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4046. babylonMaterial.reflectivityTexture = texture;
  4047. return Promise.resolve();
  4048. }));
  4049. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4050. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4051. }
  4052. return Promise.all(promises).then(function () { });
  4053. };
  4054. return KHR_materials_pbrSpecularGlossiness;
  4055. }());
  4056. exports.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4057. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4058. /***/ }),
  4059. /***/ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts":
  4060. /*!********************************************************!*\
  4061. !*** ./src/glTF/2.0/Extensions/KHR_materials_unlit.ts ***!
  4062. \********************************************************/
  4063. /*! no static exports found */
  4064. /***/ (function(module, exports, __webpack_require__) {
  4065. "use strict";
  4066. Object.defineProperty(exports, "__esModule", { value: true });
  4067. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4068. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4069. var NAME = "KHR_materials_unlit";
  4070. /**
  4071. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  4072. */
  4073. var KHR_materials_unlit = /** @class */ (function () {
  4074. /** @hidden */
  4075. function KHR_materials_unlit(loader) {
  4076. /** The name of this extension. */
  4077. this.name = NAME;
  4078. /** Defines whether this extension is enabled. */
  4079. this.enabled = true;
  4080. this._loader = loader;
  4081. }
  4082. /** @hidden */
  4083. KHR_materials_unlit.prototype.dispose = function () {
  4084. delete this._loader;
  4085. };
  4086. /** @hidden */
  4087. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4088. var _this = this;
  4089. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  4090. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  4091. });
  4092. };
  4093. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  4094. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4095. throw new Error(context + ": Material type not supported");
  4096. }
  4097. var promises = new Array();
  4098. babylonMaterial.unlit = true;
  4099. var properties = material.pbrMetallicRoughness;
  4100. if (properties) {
  4101. if (properties.baseColorFactor) {
  4102. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  4103. babylonMaterial.alpha = properties.baseColorFactor[3];
  4104. }
  4105. else {
  4106. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  4107. }
  4108. if (properties.baseColorTexture) {
  4109. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4110. babylonMaterial.albedoTexture = texture;
  4111. return Promise.resolve();
  4112. }));
  4113. }
  4114. }
  4115. if (material.doubleSided) {
  4116. babylonMaterial.backFaceCulling = false;
  4117. babylonMaterial.twoSidedLighting = true;
  4118. }
  4119. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  4120. return Promise.all(promises).then(function () { });
  4121. };
  4122. return KHR_materials_unlit;
  4123. }());
  4124. exports.KHR_materials_unlit = KHR_materials_unlit;
  4125. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  4126. /***/ }),
  4127. /***/ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts":
  4128. /*!**********************************************************!*\
  4129. !*** ./src/glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  4130. \**********************************************************/
  4131. /*! no static exports found */
  4132. /***/ (function(module, exports, __webpack_require__) {
  4133. "use strict";
  4134. Object.defineProperty(exports, "__esModule", { value: true });
  4135. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4136. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4137. var NAME = "KHR_texture_transform";
  4138. /**
  4139. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  4140. */
  4141. var KHR_texture_transform = /** @class */ (function () {
  4142. /** @hidden */
  4143. function KHR_texture_transform(loader) {
  4144. /** The name of this extension. */
  4145. this.name = NAME;
  4146. /** Defines whether this extension is enabled. */
  4147. this.enabled = true;
  4148. this._loader = loader;
  4149. }
  4150. /** @hidden */
  4151. KHR_texture_transform.prototype.dispose = function () {
  4152. delete this._loader;
  4153. };
  4154. /** @hidden */
  4155. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  4156. var _this = this;
  4157. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  4158. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  4159. if (!(babylonTexture instanceof babylonjs_1.Texture)) {
  4160. throw new Error(extensionContext + ": Texture type not supported");
  4161. }
  4162. if (extension.offset) {
  4163. babylonTexture.uOffset = extension.offset[0];
  4164. babylonTexture.vOffset = extension.offset[1];
  4165. }
  4166. // Always rotate around the origin.
  4167. babylonTexture.uRotationCenter = 0;
  4168. babylonTexture.vRotationCenter = 0;
  4169. if (extension.rotation) {
  4170. babylonTexture.wAng = -extension.rotation;
  4171. }
  4172. if (extension.scale) {
  4173. babylonTexture.uScale = extension.scale[0];
  4174. babylonTexture.vScale = extension.scale[1];
  4175. }
  4176. if (extension.texCoord != undefined) {
  4177. babylonTexture.coordinatesIndex = extension.texCoord;
  4178. }
  4179. assign(babylonTexture);
  4180. });
  4181. });
  4182. };
  4183. return KHR_texture_transform;
  4184. }());
  4185. exports.KHR_texture_transform = KHR_texture_transform;
  4186. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  4187. /***/ }),
  4188. /***/ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts":
  4189. /*!*******************************************************!*\
  4190. !*** ./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts ***!
  4191. \*******************************************************/
  4192. /*! no static exports found */
  4193. /***/ (function(module, exports, __webpack_require__) {
  4194. "use strict";
  4195. Object.defineProperty(exports, "__esModule", { value: true });
  4196. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4197. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4198. var NAME = "MSFT_audio_emitter";
  4199. /**
  4200. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  4201. */
  4202. var MSFT_audio_emitter = /** @class */ (function () {
  4203. /** @hidden */
  4204. function MSFT_audio_emitter(loader) {
  4205. /** The name of this extension. */
  4206. this.name = NAME;
  4207. /** Defines whether this extension is enabled. */
  4208. this.enabled = true;
  4209. this._loader = loader;
  4210. }
  4211. /** @hidden */
  4212. MSFT_audio_emitter.prototype.dispose = function () {
  4213. delete this._loader;
  4214. delete this._clips;
  4215. delete this._emitters;
  4216. };
  4217. /** @hidden */
  4218. MSFT_audio_emitter.prototype.onLoading = function () {
  4219. var extensions = this._loader.gltf.extensions;
  4220. if (extensions && extensions[this.name]) {
  4221. var extension = extensions[this.name];
  4222. this._clips = extension.clips;
  4223. this._emitters = extension.emitters;
  4224. glTFLoader_1.ArrayItem.Assign(this._clips);
  4225. glTFLoader_1.ArrayItem.Assign(this._emitters);
  4226. }
  4227. };
  4228. /** @hidden */
  4229. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  4230. var _this = this;
  4231. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  4232. var promises = new Array();
  4233. promises.push(_this._loader.loadSceneAsync(context, scene));
  4234. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  4235. var emitterIndex = _a[_i];
  4236. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  4237. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  4238. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  4239. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  4240. }
  4241. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  4242. }
  4243. return Promise.all(promises).then(function () { });
  4244. });
  4245. };
  4246. /** @hidden */
  4247. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  4248. var _this = this;
  4249. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  4250. var promises = new Array();
  4251. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  4252. var _loop_1 = function (emitterIndex) {
  4253. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  4254. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  4255. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  4256. var sound = _a[_i];
  4257. sound.attachToMesh(babylonMesh);
  4258. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  4259. sound.setLocalDirectionToMesh(babylonjs_1.Vector3.Forward());
  4260. sound.setDirectionalCone(2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  4261. }
  4262. }
  4263. }));
  4264. };
  4265. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  4266. var emitterIndex = _a[_i];
  4267. _loop_1(emitterIndex);
  4268. }
  4269. assign(babylonMesh);
  4270. }).then(function (babylonMesh) {
  4271. return Promise.all(promises).then(function () {
  4272. return babylonMesh;
  4273. });
  4274. });
  4275. });
  4276. };
  4277. /** @hidden */
  4278. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  4279. var _this = this;
  4280. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  4281. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  4282. var promises = new Array();
  4283. glTFLoader_1.ArrayItem.Assign(extension.events);
  4284. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  4285. var event_1 = _a[_i];
  4286. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  4287. }
  4288. return Promise.all(promises).then(function () {
  4289. return babylonAnimationGroup;
  4290. });
  4291. });
  4292. });
  4293. };
  4294. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  4295. if (clip._objectURL) {
  4296. return clip._objectURL;
  4297. }
  4298. var promise;
  4299. if (clip.uri) {
  4300. promise = this._loader.loadUriAsync(context, clip.uri);
  4301. }
  4302. else {
  4303. var bufferView = glTFLoader_1.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  4304. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  4305. }
  4306. clip._objectURL = promise.then(function (data) {
  4307. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  4308. });
  4309. return clip._objectURL;
  4310. };
  4311. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  4312. var _this = this;
  4313. emitter._babylonSounds = emitter._babylonSounds || [];
  4314. if (!emitter._babylonData) {
  4315. var clipPromises = new Array();
  4316. var name_1 = emitter.name || "emitter" + emitter.index;
  4317. var options_1 = {
  4318. loop: false,
  4319. autoplay: false,
  4320. volume: emitter.volume == undefined ? 1 : emitter.volume,
  4321. };
  4322. var _loop_2 = function (i) {
  4323. var clipContext = "#/extensions/" + this_1.name + "/clips";
  4324. var clip = glTFLoader_1.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  4325. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  4326. var sound = emitter._babylonSounds[i] = new babylonjs_1.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  4327. sound.refDistance = emitter.refDistance || 1;
  4328. sound.maxDistance = emitter.maxDistance || 256;
  4329. sound.rolloffFactor = emitter.rolloffFactor || 1;
  4330. sound.distanceModel = emitter.distanceModel || 'exponential';
  4331. sound._positionInEmitterSpace = true;
  4332. }));
  4333. };
  4334. var this_1 = this;
  4335. for (var i = 0; i < emitter.clips.length; i++) {
  4336. _loop_2(i);
  4337. }
  4338. var promise = Promise.all(clipPromises).then(function () {
  4339. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  4340. var weightedSound = new babylonjs_1.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  4341. if (emitter.innerAngle) {
  4342. weightedSound.directionalConeInnerAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle);
  4343. }
  4344. if (emitter.outerAngle) {
  4345. weightedSound.directionalConeOuterAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle);
  4346. }
  4347. if (emitter.volume) {
  4348. weightedSound.volume = emitter.volume;
  4349. }
  4350. emitter._babylonData.sound = weightedSound;
  4351. });
  4352. emitter._babylonData = {
  4353. loaded: promise
  4354. };
  4355. }
  4356. return emitter._babylonData.loaded;
  4357. };
  4358. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  4359. switch (action) {
  4360. case "play" /* play */: {
  4361. return function (currentFrame) {
  4362. var frameOffset = (startOffset || 0) + (currentFrame - time);
  4363. sound.play(frameOffset);
  4364. };
  4365. }
  4366. case "stop" /* stop */: {
  4367. return function (currentFrame) {
  4368. sound.stop();
  4369. };
  4370. }
  4371. case "pause" /* pause */: {
  4372. return function (currentFrame) {
  4373. sound.pause();
  4374. };
  4375. }
  4376. default: {
  4377. throw new Error(context + ": Unsupported action " + action);
  4378. }
  4379. }
  4380. };
  4381. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  4382. var _this = this;
  4383. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  4384. return Promise.resolve();
  4385. }
  4386. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  4387. var emitterIndex = event.emitter;
  4388. var emitter = glTFLoader_1.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  4389. return this._loadEmitterAsync(context, emitter).then(function () {
  4390. var sound = emitter._babylonData.sound;
  4391. if (sound) {
  4392. var babylonAnimationEvent = new babylonjs_1.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  4393. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  4394. // Make sure all started audio stops when this animation is terminated.
  4395. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  4396. sound.stop();
  4397. });
  4398. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  4399. sound.pause();
  4400. });
  4401. }
  4402. });
  4403. };
  4404. return MSFT_audio_emitter;
  4405. }());
  4406. exports.MSFT_audio_emitter = MSFT_audio_emitter;
  4407. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  4408. /***/ }),
  4409. /***/ "./src/glTF/2.0/Extensions/MSFT_lod.ts":
  4410. /*!*********************************************!*\
  4411. !*** ./src/glTF/2.0/Extensions/MSFT_lod.ts ***!
  4412. \*********************************************/
  4413. /*! no static exports found */
  4414. /***/ (function(module, exports, __webpack_require__) {
  4415. "use strict";
  4416. Object.defineProperty(exports, "__esModule", { value: true });
  4417. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4418. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4419. var NAME = "MSFT_lod";
  4420. /**
  4421. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  4422. */
  4423. var MSFT_lod = /** @class */ (function () {
  4424. /** @hidden */
  4425. function MSFT_lod(loader) {
  4426. /** The name of this extension. */
  4427. this.name = NAME;
  4428. /** Defines whether this extension is enabled. */
  4429. this.enabled = true;
  4430. /**
  4431. * Maximum number of LODs to load, starting from the lowest LOD.
  4432. */
  4433. this.maxLODsToLoad = Number.MAX_VALUE;
  4434. /**
  4435. * Observable raised when all node LODs of one level are loaded.
  4436. * The event data is the index of the loaded LOD starting from zero.
  4437. * Dispose the loader to cancel the loading of the next level of LODs.
  4438. */
  4439. this.onNodeLODsLoadedObservable = new babylonjs_1.Observable();
  4440. /**
  4441. * Observable raised when all material LODs of one level are loaded.
  4442. * The event data is the index of the loaded LOD starting from zero.
  4443. * Dispose the loader to cancel the loading of the next level of LODs.
  4444. */
  4445. this.onMaterialLODsLoadedObservable = new babylonjs_1.Observable();
  4446. this._nodeIndexLOD = null;
  4447. this._nodeSignalLODs = new Array();
  4448. this._nodePromiseLODs = new Array();
  4449. this._materialIndexLOD = null;
  4450. this._materialSignalLODs = new Array();
  4451. this._materialPromiseLODs = new Array();
  4452. this._loader = loader;
  4453. }
  4454. /** @hidden */
  4455. MSFT_lod.prototype.dispose = function () {
  4456. delete this._loader;
  4457. this._nodeIndexLOD = null;
  4458. this._nodeSignalLODs.length = 0;
  4459. this._nodePromiseLODs.length = 0;
  4460. this._materialIndexLOD = null;
  4461. this._materialSignalLODs.length = 0;
  4462. this._materialPromiseLODs.length = 0;
  4463. this.onMaterialLODsLoadedObservable.clear();
  4464. this.onNodeLODsLoadedObservable.clear();
  4465. };
  4466. /** @hidden */
  4467. MSFT_lod.prototype.onReady = function () {
  4468. var _this = this;
  4469. var _loop_1 = function (indexLOD) {
  4470. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  4471. if (indexLOD !== 0) {
  4472. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  4473. }
  4474. _this._loader.log("Loaded node LOD " + indexLOD);
  4475. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  4476. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  4477. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  4478. if (_this._nodeSignalLODs[indexLOD]) {
  4479. _this._nodeSignalLODs[indexLOD].resolve();
  4480. }
  4481. }
  4482. });
  4483. this_1._loader._completePromises.push(promise);
  4484. };
  4485. var this_1 = this;
  4486. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  4487. _loop_1(indexLOD);
  4488. }
  4489. var _loop_2 = function (indexLOD) {
  4490. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  4491. if (indexLOD !== 0) {
  4492. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  4493. }
  4494. _this._loader.log("Loaded material LOD " + indexLOD);
  4495. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  4496. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  4497. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  4498. if (_this._materialSignalLODs[indexLOD]) {
  4499. _this._materialSignalLODs[indexLOD].resolve();
  4500. }
  4501. }
  4502. });
  4503. this_2._loader._completePromises.push(promise);
  4504. };
  4505. var this_2 = this;
  4506. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  4507. _loop_2(indexLOD);
  4508. }
  4509. };
  4510. /** @hidden */
  4511. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  4512. var _this = this;
  4513. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  4514. var firstPromise;
  4515. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  4516. _this._loader.logOpen("" + extensionContext);
  4517. var _loop_3 = function (indexLOD) {
  4518. var nodeLOD = nodeLODs[indexLOD];
  4519. if (indexLOD !== 0) {
  4520. _this._nodeIndexLOD = indexLOD;
  4521. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_1.Deferred();
  4522. }
  4523. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  4524. if (indexLOD !== 0) {
  4525. // TODO: should not rely on _babylonMesh
  4526. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4527. if (previousNodeLOD._babylonMesh) {
  4528. previousNodeLOD._babylonMesh.dispose();
  4529. delete previousNodeLOD._babylonMesh;
  4530. _this._disposeUnusedMaterials();
  4531. }
  4532. }
  4533. return babylonMesh;
  4534. });
  4535. if (indexLOD === 0) {
  4536. firstPromise = promise;
  4537. }
  4538. else {
  4539. _this._nodeIndexLOD = null;
  4540. }
  4541. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  4542. _this._nodePromiseLODs[indexLOD].push(promise);
  4543. };
  4544. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4545. _loop_3(indexLOD);
  4546. }
  4547. _this._loader.logClose();
  4548. return firstPromise;
  4549. });
  4550. };
  4551. /** @hidden */
  4552. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4553. var _this = this;
  4554. // Don't load material LODs if already loading a node LOD.
  4555. if (this._nodeIndexLOD) {
  4556. return null;
  4557. }
  4558. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  4559. var firstPromise;
  4560. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  4561. _this._loader.logOpen("" + extensionContext);
  4562. var _loop_4 = function (indexLOD) {
  4563. var materialLOD = materialLODs[indexLOD];
  4564. if (indexLOD !== 0) {
  4565. _this._materialIndexLOD = indexLOD;
  4566. }
  4567. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4568. if (indexLOD === 0) {
  4569. assign(babylonMaterial);
  4570. }
  4571. }).then(function (babylonMaterial) {
  4572. if (indexLOD !== 0) {
  4573. assign(babylonMaterial);
  4574. // TODO: should not rely on _babylonData
  4575. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4576. if (previousBabylonDataLOD[babylonDrawMode]) {
  4577. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4578. delete previousBabylonDataLOD[babylonDrawMode];
  4579. }
  4580. }
  4581. return babylonMaterial;
  4582. });
  4583. if (indexLOD === 0) {
  4584. firstPromise = promise;
  4585. }
  4586. else {
  4587. _this._materialIndexLOD = null;
  4588. }
  4589. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  4590. _this._materialPromiseLODs[indexLOD].push(promise);
  4591. };
  4592. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4593. _loop_4(indexLOD);
  4594. }
  4595. _this._loader.logClose();
  4596. return firstPromise;
  4597. });
  4598. };
  4599. /** @hidden */
  4600. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4601. var _this = this;
  4602. // Defer the loading of uris if loading a material or node LOD.
  4603. if (this._materialIndexLOD !== null) {
  4604. this._loader.log("deferred");
  4605. var previousIndexLOD = this._materialIndexLOD - 1;
  4606. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  4607. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  4608. return _this._loader.loadUriAsync(context, uri);
  4609. });
  4610. }
  4611. else if (this._nodeIndexLOD !== null) {
  4612. this._loader.log("deferred");
  4613. var previousIndexLOD = this._nodeIndexLOD - 1;
  4614. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  4615. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  4616. return _this._loader.loadUriAsync(context, uri);
  4617. });
  4618. }
  4619. return null;
  4620. };
  4621. /**
  4622. * Gets an array of LOD properties from lowest to highest.
  4623. */
  4624. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4625. if (this.maxLODsToLoad <= 0) {
  4626. throw new Error("maxLODsToLoad must be greater than zero");
  4627. }
  4628. var properties = new Array();
  4629. for (var i = ids.length - 1; i >= 0; i--) {
  4630. properties.push(glTFLoader_1.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  4631. if (properties.length === this.maxLODsToLoad) {
  4632. return properties;
  4633. }
  4634. }
  4635. properties.push(property);
  4636. return properties;
  4637. };
  4638. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  4639. // TODO: should not rely on _babylonData
  4640. var materials = this._loader.gltf.materials;
  4641. if (materials) {
  4642. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  4643. var material = materials_1[_i];
  4644. if (material._babylonData) {
  4645. for (var drawMode in material._babylonData) {
  4646. var babylonData = material._babylonData[drawMode];
  4647. if (babylonData.meshes.length === 0) {
  4648. babylonData.material.dispose(false, true);
  4649. delete material._babylonData[drawMode];
  4650. }
  4651. }
  4652. }
  4653. }
  4654. }
  4655. };
  4656. return MSFT_lod;
  4657. }());
  4658. exports.MSFT_lod = MSFT_lod;
  4659. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  4660. /***/ }),
  4661. /***/ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts":
  4662. /*!*******************************************************!*\
  4663. !*** ./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***!
  4664. \*******************************************************/
  4665. /*! no static exports found */
  4666. /***/ (function(module, exports, __webpack_require__) {
  4667. "use strict";
  4668. Object.defineProperty(exports, "__esModule", { value: true });
  4669. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4670. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4671. var NAME = "MSFT_minecraftMesh";
  4672. /** @hidden */
  4673. var MSFT_minecraftMesh = /** @class */ (function () {
  4674. function MSFT_minecraftMesh(loader) {
  4675. this.name = NAME;
  4676. this.enabled = true;
  4677. this._loader = loader;
  4678. }
  4679. MSFT_minecraftMesh.prototype.dispose = function () {
  4680. delete this._loader;
  4681. };
  4682. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4683. var _this = this;
  4684. return glTFLoader_1.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  4685. if (extra) {
  4686. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4687. throw new Error(extraContext + ": Material type not supported");
  4688. }
  4689. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  4690. if (babylonMaterial.needAlphaBlending()) {
  4691. babylonMaterial.forceDepthWrite = true;
  4692. babylonMaterial.separateCullingPass = true;
  4693. }
  4694. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  4695. babylonMaterial.twoSidedLighting = true;
  4696. return promise;
  4697. }
  4698. return null;
  4699. });
  4700. };
  4701. return MSFT_minecraftMesh;
  4702. }());
  4703. exports.MSFT_minecraftMesh = MSFT_minecraftMesh;
  4704. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  4705. /***/ }),
  4706. /***/ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts":
  4707. /*!*****************************************************!*\
  4708. !*** ./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***!
  4709. \*****************************************************/
  4710. /*! no static exports found */
  4711. /***/ (function(module, exports, __webpack_require__) {
  4712. "use strict";
  4713. Object.defineProperty(exports, "__esModule", { value: true });
  4714. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4715. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  4716. var NAME = "MSFT_sRGBFactors";
  4717. /** @hidden */
  4718. var MSFT_sRGBFactors = /** @class */ (function () {
  4719. function MSFT_sRGBFactors(loader) {
  4720. this.name = NAME;
  4721. this.enabled = true;
  4722. this._loader = loader;
  4723. }
  4724. MSFT_sRGBFactors.prototype.dispose = function () {
  4725. delete this._loader;
  4726. };
  4727. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4728. var _this = this;
  4729. return glTFLoader_1.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  4730. if (extra) {
  4731. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4732. throw new Error(extraContext + ": Material type not supported");
  4733. }
  4734. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  4735. if (!babylonMaterial.albedoTexture) {
  4736. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  4737. }
  4738. if (!babylonMaterial.reflectivityTexture) {
  4739. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  4740. }
  4741. return promise;
  4742. }
  4743. return null;
  4744. });
  4745. };
  4746. return MSFT_sRGBFactors;
  4747. }());
  4748. exports.MSFT_sRGBFactors = MSFT_sRGBFactors;
  4749. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  4750. /***/ }),
  4751. /***/ "./src/glTF/2.0/Extensions/index.ts":
  4752. /*!******************************************!*\
  4753. !*** ./src/glTF/2.0/Extensions/index.ts ***!
  4754. \******************************************/
  4755. /*! no static exports found */
  4756. /***/ (function(module, exports, __webpack_require__) {
  4757. "use strict";
  4758. function __export(m) {
  4759. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  4760. }
  4761. Object.defineProperty(exports, "__esModule", { value: true });
  4762. __export(__webpack_require__(/*! ./EXT_lights_image_based */ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts"));
  4763. __export(__webpack_require__(/*! ./KHR_draco_mesh_compression */ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"));
  4764. __export(__webpack_require__(/*! ./KHR_lights_punctual */ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts"));
  4765. __export(__webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"));
  4766. __export(__webpack_require__(/*! ./KHR_materials_unlit */ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts"));
  4767. __export(__webpack_require__(/*! ./KHR_texture_transform */ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts"));
  4768. __export(__webpack_require__(/*! ./MSFT_audio_emitter */ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts"));
  4769. __export(__webpack_require__(/*! ./MSFT_lod */ "./src/glTF/2.0/Extensions/MSFT_lod.ts"));
  4770. __export(__webpack_require__(/*! ./MSFT_minecraftMesh */ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts"));
  4771. __export(__webpack_require__(/*! ./MSFT_sRGBFactors */ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts"));
  4772. /***/ }),
  4773. /***/ "./src/glTF/2.0/glTFLoader.ts":
  4774. /*!************************************!*\
  4775. !*** ./src/glTF/2.0/glTFLoader.ts ***!
  4776. \************************************/
  4777. /*! no static exports found */
  4778. /***/ (function(module, exports, __webpack_require__) {
  4779. "use strict";
  4780. Object.defineProperty(exports, "__esModule", { value: true });
  4781. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  4782. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  4783. /**
  4784. * Helper class for working with arrays when loading the glTF asset
  4785. */
  4786. var ArrayItem = /** @class */ (function () {
  4787. function ArrayItem() {
  4788. }
  4789. /**
  4790. * Gets an item from the given array.
  4791. * @param context The context when loading the asset
  4792. * @param array The array to get the item from
  4793. * @param index The index to the array
  4794. * @returns The array item
  4795. */
  4796. ArrayItem.Get = function (context, array, index) {
  4797. if (!array || index == undefined || !array[index]) {
  4798. throw new Error(context + ": Failed to find index (" + index + ")");
  4799. }
  4800. return array[index];
  4801. };
  4802. /**
  4803. * Assign an `index` field to each item of the given array.
  4804. * @param array The array of items
  4805. */
  4806. ArrayItem.Assign = function (array) {
  4807. if (array) {
  4808. for (var index = 0; index < array.length; index++) {
  4809. array[index].index = index;
  4810. }
  4811. }
  4812. };
  4813. return ArrayItem;
  4814. }());
  4815. exports.ArrayItem = ArrayItem;
  4816. /**
  4817. * The glTF 2.0 loader
  4818. */
  4819. var GLTFLoader = /** @class */ (function () {
  4820. /** @hidden */
  4821. function GLTFLoader(parent) {
  4822. /** @hidden */
  4823. this._completePromises = new Array();
  4824. this._disposed = false;
  4825. this._state = null;
  4826. this._extensions = {};
  4827. this._defaultBabylonMaterialData = {};
  4828. this._requests = new Array();
  4829. this._parent = parent;
  4830. }
  4831. /**
  4832. * Registers a loader extension.
  4833. * @param name The name of the loader extension.
  4834. * @param factory The factory function that creates the loader extension.
  4835. */
  4836. GLTFLoader.RegisterExtension = function (name, factory) {
  4837. if (GLTFLoader.UnregisterExtension(name)) {
  4838. babylonjs_1.Tools.Warn("Extension with the name '" + name + "' already exists");
  4839. }
  4840. GLTFLoader._ExtensionFactories[name] = factory;
  4841. // Keep the order of registration so that extensions registered first are called first.
  4842. GLTFLoader._ExtensionNames.push(name);
  4843. };
  4844. /**
  4845. * Unregisters a loader extension.
  4846. * @param name The name of the loader extenion.
  4847. * @returns A boolean indicating whether the extension has been unregistered
  4848. */
  4849. GLTFLoader.UnregisterExtension = function (name) {
  4850. if (!GLTFLoader._ExtensionFactories[name]) {
  4851. return false;
  4852. }
  4853. delete GLTFLoader._ExtensionFactories[name];
  4854. var index = GLTFLoader._ExtensionNames.indexOf(name);
  4855. if (index !== -1) {
  4856. GLTFLoader._ExtensionNames.splice(index, 1);
  4857. }
  4858. return true;
  4859. };
  4860. Object.defineProperty(GLTFLoader.prototype, "state", {
  4861. /**
  4862. * Gets the loader state.
  4863. */
  4864. get: function () {
  4865. return this._state;
  4866. },
  4867. enumerable: true,
  4868. configurable: true
  4869. });
  4870. /** @hidden */
  4871. GLTFLoader.prototype.dispose = function () {
  4872. if (this._disposed) {
  4873. return;
  4874. }
  4875. this._disposed = true;
  4876. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4877. var request = _a[_i];
  4878. request.abort();
  4879. }
  4880. this._requests.length = 0;
  4881. delete this.gltf;
  4882. delete this.babylonScene;
  4883. this._completePromises.length = 0;
  4884. for (var name_1 in this._extensions) {
  4885. var extension = this._extensions[name_1];
  4886. if (extension.dispose) {
  4887. this._extensions[name_1].dispose();
  4888. }
  4889. }
  4890. this._extensions = {};
  4891. delete this._rootBabylonMesh;
  4892. delete this._progressCallback;
  4893. this._parent._clear();
  4894. };
  4895. /** @hidden */
  4896. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  4897. var _this = this;
  4898. return Promise.resolve().then(function () {
  4899. _this.babylonScene = scene;
  4900. _this._rootUrl = rootUrl;
  4901. _this._fileName = fileName || "scene";
  4902. _this._progressCallback = onProgress;
  4903. _this._loadData(data);
  4904. var nodes = null;
  4905. if (meshesNames) {
  4906. var nodeMap_1 = {};
  4907. if (_this.gltf.nodes) {
  4908. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  4909. var node = _a[_i];
  4910. if (node.name) {
  4911. nodeMap_1[node.name] = node.index;
  4912. }
  4913. }
  4914. }
  4915. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  4916. nodes = names.map(function (name) {
  4917. var node = nodeMap_1[name];
  4918. if (node === undefined) {
  4919. throw new Error("Failed to find node '" + name + "'");
  4920. }
  4921. return node;
  4922. });
  4923. }
  4924. return _this._loadAsync(nodes, function () {
  4925. return {
  4926. meshes: _this._getMeshes(),
  4927. particleSystems: [],
  4928. skeletons: _this._getSkeletons(),
  4929. animationGroups: _this._getAnimationGroups()
  4930. };
  4931. });
  4932. });
  4933. };
  4934. /** @hidden */
  4935. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  4936. var _this = this;
  4937. return Promise.resolve().then(function () {
  4938. _this.babylonScene = scene;
  4939. _this._rootUrl = rootUrl;
  4940. _this._fileName = fileName || "scene";
  4941. _this._progressCallback = onProgress;
  4942. _this._loadData(data);
  4943. return _this._loadAsync(null, function () { return undefined; });
  4944. });
  4945. };
  4946. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  4947. var _this = this;
  4948. return Promise.resolve().then(function () {
  4949. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  4950. _this._loadExtensions();
  4951. _this._checkExtensions();
  4952. var loadingToReadyCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.READY];
  4953. var loadingToCompleteCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.COMPLETE];
  4954. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  4955. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  4956. _this._setState(glTFFileLoader_1.GLTFLoaderState.LOADING);
  4957. _this._extensionsOnLoading();
  4958. var promises = new Array();
  4959. if (nodes) {
  4960. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  4961. }
  4962. else {
  4963. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  4964. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  4965. }
  4966. if (_this._parent.compileMaterials) {
  4967. promises.push(_this._compileMaterialsAsync());
  4968. }
  4969. if (_this._parent.compileShadowGenerators) {
  4970. promises.push(_this._compileShadowGeneratorsAsync());
  4971. }
  4972. var resultPromise = Promise.all(promises).then(function () {
  4973. _this._setState(glTFFileLoader_1.GLTFLoaderState.READY);
  4974. _this._extensionsOnReady();
  4975. _this._startAnimations();
  4976. return resultFunc();
  4977. });
  4978. resultPromise.then(function () {
  4979. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  4980. babylonjs_1.Tools.SetImmediate(function () {
  4981. if (!_this._disposed) {
  4982. Promise.all(_this._completePromises).then(function () {
  4983. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  4984. _this._setState(glTFFileLoader_1.GLTFLoaderState.COMPLETE);
  4985. _this._parent.onCompleteObservable.notifyObservers(undefined);
  4986. _this._parent.onCompleteObservable.clear();
  4987. _this.dispose();
  4988. }, function (error) {
  4989. _this._parent.onErrorObservable.notifyObservers(error);
  4990. _this._parent.onErrorObservable.clear();
  4991. _this.dispose();
  4992. });
  4993. }
  4994. });
  4995. });
  4996. return resultPromise;
  4997. }, function (error) {
  4998. if (!_this._disposed) {
  4999. _this._parent.onErrorObservable.notifyObservers(error);
  5000. _this._parent.onErrorObservable.clear();
  5001. _this.dispose();
  5002. }
  5003. throw error;
  5004. });
  5005. };
  5006. GLTFLoader.prototype._loadData = function (data) {
  5007. this.gltf = data.json;
  5008. this._setupData();
  5009. if (data.bin) {
  5010. var buffers = this.gltf.buffers;
  5011. if (buffers && buffers[0] && !buffers[0].uri) {
  5012. var binaryBuffer = buffers[0];
  5013. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  5014. babylonjs_1.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  5015. }
  5016. binaryBuffer._data = Promise.resolve(data.bin);
  5017. }
  5018. else {
  5019. babylonjs_1.Tools.Warn("Unexpected BIN chunk");
  5020. }
  5021. }
  5022. };
  5023. GLTFLoader.prototype._setupData = function () {
  5024. ArrayItem.Assign(this.gltf.accessors);
  5025. ArrayItem.Assign(this.gltf.animations);
  5026. ArrayItem.Assign(this.gltf.buffers);
  5027. ArrayItem.Assign(this.gltf.bufferViews);
  5028. ArrayItem.Assign(this.gltf.cameras);
  5029. ArrayItem.Assign(this.gltf.images);
  5030. ArrayItem.Assign(this.gltf.materials);
  5031. ArrayItem.Assign(this.gltf.meshes);
  5032. ArrayItem.Assign(this.gltf.nodes);
  5033. ArrayItem.Assign(this.gltf.samplers);
  5034. ArrayItem.Assign(this.gltf.scenes);
  5035. ArrayItem.Assign(this.gltf.skins);
  5036. ArrayItem.Assign(this.gltf.textures);
  5037. if (this.gltf.nodes) {
  5038. var nodeParents = {};
  5039. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  5040. var node = _a[_i];
  5041. if (node.children) {
  5042. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  5043. var index = _c[_b];
  5044. nodeParents[index] = node.index;
  5045. }
  5046. }
  5047. }
  5048. var rootNode = this._createRootNode();
  5049. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  5050. var node = _e[_d];
  5051. var parentIndex = nodeParents[node.index];
  5052. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  5053. }
  5054. }
  5055. };
  5056. GLTFLoader.prototype._loadExtensions = function () {
  5057. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5058. var name_2 = _a[_i];
  5059. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  5060. this._extensions[name_2] = extension;
  5061. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  5062. }
  5063. this._parent.onExtensionLoadedObservable.clear();
  5064. };
  5065. GLTFLoader.prototype._checkExtensions = function () {
  5066. if (this.gltf.extensionsRequired) {
  5067. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  5068. var name_3 = _a[_i];
  5069. var extension = this._extensions[name_3];
  5070. if (!extension || !extension.enabled) {
  5071. throw new Error("Require extension " + name_3 + " is not available");
  5072. }
  5073. }
  5074. }
  5075. };
  5076. GLTFLoader.prototype._setState = function (state) {
  5077. this._state = state;
  5078. this.log(glTFFileLoader_1.GLTFLoaderState[this._state]);
  5079. };
  5080. GLTFLoader.prototype._createRootNode = function () {
  5081. this._rootBabylonMesh = new babylonjs_1.Mesh("__root__", this.babylonScene);
  5082. var rootNode = {
  5083. _babylonMesh: this._rootBabylonMesh,
  5084. index: -1
  5085. };
  5086. switch (this._parent.coordinateSystemMode) {
  5087. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.AUTO: {
  5088. if (!this.babylonScene.useRightHandedSystem) {
  5089. rootNode.rotation = [0, 1, 0, 0];
  5090. rootNode.scale = [1, 1, -1];
  5091. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  5092. }
  5093. break;
  5094. }
  5095. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  5096. this.babylonScene.useRightHandedSystem = true;
  5097. break;
  5098. }
  5099. default: {
  5100. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  5101. }
  5102. }
  5103. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  5104. return rootNode;
  5105. };
  5106. /**
  5107. * Loads a glTF scene.
  5108. * @param context The context when loading the asset
  5109. * @param scene The glTF scene property
  5110. * @returns A promise that resolves when the load is complete
  5111. */
  5112. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  5113. var _this = this;
  5114. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  5115. if (extensionPromise) {
  5116. return extensionPromise;
  5117. }
  5118. var promises = new Array();
  5119. this.logOpen(context + " " + (scene.name || ""));
  5120. if (scene.nodes) {
  5121. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  5122. var index = _a[_i];
  5123. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  5124. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  5125. babylonMesh.parent = _this._rootBabylonMesh;
  5126. }));
  5127. }
  5128. }
  5129. promises.push(this._loadAnimationsAsync());
  5130. this.logClose();
  5131. return Promise.all(promises).then(function () { });
  5132. };
  5133. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  5134. if (node._primitiveBabylonMeshes) {
  5135. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  5136. var babylonMesh = _a[_i];
  5137. callback(babylonMesh);
  5138. }
  5139. }
  5140. else {
  5141. callback(node._babylonMesh);
  5142. }
  5143. };
  5144. GLTFLoader.prototype._getMeshes = function () {
  5145. var meshes = new Array();
  5146. // Root mesh is always first.
  5147. meshes.push(this._rootBabylonMesh);
  5148. var nodes = this.gltf.nodes;
  5149. if (nodes) {
  5150. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  5151. var node = nodes_1[_i];
  5152. if (node._babylonMesh) {
  5153. meshes.push(node._babylonMesh);
  5154. }
  5155. if (node._primitiveBabylonMeshes) {
  5156. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  5157. var babylonMesh = _b[_a];
  5158. meshes.push(babylonMesh);
  5159. }
  5160. }
  5161. }
  5162. }
  5163. return meshes;
  5164. };
  5165. GLTFLoader.prototype._getSkeletons = function () {
  5166. var skeletons = new Array();
  5167. var skins = this.gltf.skins;
  5168. if (skins) {
  5169. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  5170. var skin = skins_1[_i];
  5171. if (skin._babylonSkeleton) {
  5172. skeletons.push(skin._babylonSkeleton);
  5173. }
  5174. }
  5175. }
  5176. return skeletons;
  5177. };
  5178. GLTFLoader.prototype._getAnimationGroups = function () {
  5179. var animationGroups = new Array();
  5180. var animations = this.gltf.animations;
  5181. if (animations) {
  5182. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  5183. var animation = animations_1[_i];
  5184. if (animation._babylonAnimationGroup) {
  5185. animationGroups.push(animation._babylonAnimationGroup);
  5186. }
  5187. }
  5188. }
  5189. return animationGroups;
  5190. };
  5191. GLTFLoader.prototype._startAnimations = function () {
  5192. switch (this._parent.animationStartMode) {
  5193. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.NONE: {
  5194. // do nothing
  5195. break;
  5196. }
  5197. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.FIRST: {
  5198. var babylonAnimationGroups = this._getAnimationGroups();
  5199. if (babylonAnimationGroups.length !== 0) {
  5200. babylonAnimationGroups[0].start(true);
  5201. }
  5202. break;
  5203. }
  5204. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.ALL: {
  5205. var babylonAnimationGroups = this._getAnimationGroups();
  5206. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  5207. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  5208. babylonAnimationGroup.start(true);
  5209. }
  5210. break;
  5211. }
  5212. default: {
  5213. babylonjs_1.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  5214. return;
  5215. }
  5216. }
  5217. };
  5218. /**
  5219. * Loads a glTF node.
  5220. * @param context The context when loading the asset
  5221. * @param node The glTF node property
  5222. * @param assign A function called synchronously after parsing the glTF properties
  5223. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  5224. */
  5225. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  5226. var _this = this;
  5227. if (assign === void 0) { assign = function () { }; }
  5228. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  5229. if (extensionPromise) {
  5230. return extensionPromise;
  5231. }
  5232. if (node._babylonMesh) {
  5233. throw new Error(context + ": Invalid recursive node hierarchy");
  5234. }
  5235. var promises = new Array();
  5236. this.logOpen(context + " " + (node.name || ""));
  5237. var babylonMesh = new babylonjs_1.Mesh(node.name || "node" + node.index, this.babylonScene);
  5238. node._babylonMesh = babylonMesh;
  5239. babylonMesh.setEnabled(false);
  5240. GLTFLoader._LoadTransform(node, babylonMesh);
  5241. if (node.mesh != undefined) {
  5242. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  5243. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  5244. }
  5245. if (node.camera != undefined) {
  5246. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  5247. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  5248. babylonCamera.parent = babylonMesh;
  5249. }));
  5250. }
  5251. if (node.children) {
  5252. var _loop_1 = function (index) {
  5253. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  5254. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  5255. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5256. if (childNode.skin != undefined) {
  5257. childBabylonMesh.parent = _this._rootBabylonMesh;
  5258. return;
  5259. }
  5260. childBabylonMesh.parent = babylonMesh;
  5261. }));
  5262. };
  5263. var this_1 = this;
  5264. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  5265. var index = _a[_i];
  5266. _loop_1(index);
  5267. }
  5268. }
  5269. assign(babylonMesh);
  5270. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  5271. this.logClose();
  5272. return Promise.all(promises).then(function () {
  5273. babylonMesh.setEnabled(true);
  5274. return babylonMesh;
  5275. });
  5276. };
  5277. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  5278. var _this = this;
  5279. var promises = new Array();
  5280. this.logOpen(context + " " + (mesh.name || ""));
  5281. var primitives = mesh.primitives;
  5282. if (!primitives || primitives.length === 0) {
  5283. throw new Error(context + ": Primitives are missing");
  5284. }
  5285. ArrayItem.Assign(primitives);
  5286. if (primitives.length === 1) {
  5287. var primitive = primitives[0];
  5288. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  5289. }
  5290. else {
  5291. node._primitiveBabylonMeshes = [];
  5292. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  5293. var primitive = primitives_1[_i];
  5294. var primitiveBabylonMesh = new babylonjs_1.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  5295. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  5296. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  5297. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  5298. }
  5299. }
  5300. if (node.skin != undefined) {
  5301. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  5302. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  5303. }
  5304. this.logClose();
  5305. return Promise.all(promises).then(function () {
  5306. _this._forEachPrimitive(node, function (babylonMesh) {
  5307. babylonMesh._refreshBoundingInfo(true);
  5308. });
  5309. });
  5310. };
  5311. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  5312. var _this = this;
  5313. var promises = new Array();
  5314. this.logOpen("" + context);
  5315. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  5316. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  5317. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  5318. babylonGeometry.applyToMesh(babylonMesh);
  5319. });
  5320. }));
  5321. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  5322. if (primitive.material == undefined) {
  5323. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  5324. if (!babylonMaterial) {
  5325. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  5326. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5327. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  5328. }
  5329. babylonMesh.material = babylonMaterial;
  5330. }
  5331. else {
  5332. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  5333. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  5334. babylonMesh.material = babylonMaterial;
  5335. }));
  5336. }
  5337. this.logClose();
  5338. return Promise.all(promises).then(function () { });
  5339. };
  5340. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  5341. var _this = this;
  5342. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  5343. if (extensionPromise) {
  5344. return extensionPromise;
  5345. }
  5346. var attributes = primitive.attributes;
  5347. if (!attributes) {
  5348. throw new Error(context + ": Attributes are missing");
  5349. }
  5350. var promises = new Array();
  5351. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, this.babylonScene);
  5352. if (primitive.indices == undefined) {
  5353. babylonMesh.isUnIndexed = true;
  5354. }
  5355. else {
  5356. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  5357. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5358. babylonGeometry.setIndices(data);
  5359. }));
  5360. }
  5361. var loadAttribute = function (attribute, kind, callback) {
  5362. if (attributes[attribute] == undefined) {
  5363. return;
  5364. }
  5365. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  5366. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  5367. babylonMesh._delayInfo.push(kind);
  5368. }
  5369. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  5370. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  5371. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  5372. }));
  5373. if (callback) {
  5374. callback(accessor);
  5375. }
  5376. };
  5377. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  5378. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  5379. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  5380. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  5381. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  5382. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  5383. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  5384. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind, function (accessor) {
  5385. if (accessor.type === "VEC4" /* VEC4 */) {
  5386. babylonMesh.hasVertexAlpha = true;
  5387. }
  5388. });
  5389. return Promise.all(promises).then(function () {
  5390. return babylonGeometry;
  5391. });
  5392. };
  5393. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  5394. if (!primitive.targets) {
  5395. return;
  5396. }
  5397. if (node._numMorphTargets == undefined) {
  5398. node._numMorphTargets = primitive.targets.length;
  5399. }
  5400. else if (primitive.targets.length !== node._numMorphTargets) {
  5401. throw new Error(context + ": Primitives do not have the same number of targets");
  5402. }
  5403. babylonMesh.morphTargetManager = new babylonjs_1.MorphTargetManager();
  5404. for (var index = 0; index < primitive.targets.length; index++) {
  5405. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  5406. babylonMesh.morphTargetManager.addTarget(new babylonjs_1.MorphTarget("morphTarget" + index, weight));
  5407. // TODO: tell the target whether it has positions, normals, tangents
  5408. }
  5409. };
  5410. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  5411. if (!primitive.targets) {
  5412. return Promise.resolve();
  5413. }
  5414. var promises = new Array();
  5415. var morphTargetManager = babylonMesh.morphTargetManager;
  5416. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  5417. var babylonMorphTarget = morphTargetManager.getTarget(index);
  5418. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  5419. }
  5420. return Promise.all(promises).then(function () { });
  5421. };
  5422. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  5423. var _this = this;
  5424. var promises = new Array();
  5425. var loadAttribute = function (attribute, kind, setData) {
  5426. if (attributes[attribute] == undefined) {
  5427. return;
  5428. }
  5429. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  5430. if (!babylonVertexBuffer) {
  5431. return;
  5432. }
  5433. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  5434. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5435. setData(babylonVertexBuffer, data);
  5436. }));
  5437. };
  5438. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  5439. babylonVertexBuffer.forEach(data.length, function (value, index) {
  5440. data[index] += value;
  5441. });
  5442. babylonMorphTarget.setPositions(data);
  5443. });
  5444. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  5445. babylonVertexBuffer.forEach(data.length, function (value, index) {
  5446. data[index] += value;
  5447. });
  5448. babylonMorphTarget.setNormals(data);
  5449. });
  5450. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  5451. var dataIndex = 0;
  5452. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  5453. // Tangent data for morph targets is stored as xyz delta.
  5454. // The vertexData.tangent is stored as xyzw.
  5455. // So we need to skip every fourth vertexData.tangent.
  5456. if (((index + 1) % 4) !== 0) {
  5457. data[dataIndex++] += value;
  5458. }
  5459. });
  5460. babylonMorphTarget.setTangents(data);
  5461. });
  5462. return Promise.all(promises).then(function () { });
  5463. };
  5464. GLTFLoader._LoadTransform = function (node, babylonNode) {
  5465. var position = babylonjs_1.Vector3.Zero();
  5466. var rotation = babylonjs_1.Quaternion.Identity();
  5467. var scaling = babylonjs_1.Vector3.One();
  5468. if (node.matrix) {
  5469. var matrix = babylonjs_1.Matrix.FromArray(node.matrix);
  5470. matrix.decompose(scaling, rotation, position);
  5471. }
  5472. else {
  5473. if (node.translation) {
  5474. position = babylonjs_1.Vector3.FromArray(node.translation);
  5475. }
  5476. if (node.rotation) {
  5477. rotation = babylonjs_1.Quaternion.FromArray(node.rotation);
  5478. }
  5479. if (node.scale) {
  5480. scaling = babylonjs_1.Vector3.FromArray(node.scale);
  5481. }
  5482. }
  5483. babylonNode.position = position;
  5484. babylonNode.rotationQuaternion = rotation;
  5485. babylonNode.scaling = scaling;
  5486. };
  5487. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  5488. var _this = this;
  5489. var assignSkeleton = function (skeleton) {
  5490. _this._forEachPrimitive(node, function (babylonMesh) {
  5491. babylonMesh.skeleton = skeleton;
  5492. });
  5493. // Ignore the TRS of skinned nodes.
  5494. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5495. node._babylonMesh.position = babylonjs_1.Vector3.Zero();
  5496. node._babylonMesh.rotationQuaternion = babylonjs_1.Quaternion.Identity();
  5497. node._babylonMesh.scaling = babylonjs_1.Vector3.One();
  5498. };
  5499. if (skin._promise) {
  5500. return skin._promise.then(function () {
  5501. assignSkeleton(skin._babylonSkeleton);
  5502. });
  5503. }
  5504. var skeletonId = "skeleton" + skin.index;
  5505. var babylonSkeleton = new babylonjs_1.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  5506. skin._babylonSkeleton = babylonSkeleton;
  5507. this._loadBones(context, skin);
  5508. assignSkeleton(babylonSkeleton);
  5509. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  5510. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  5511. }));
  5512. };
  5513. GLTFLoader.prototype._loadBones = function (context, skin) {
  5514. var babylonBones = {};
  5515. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  5516. var index = _a[_i];
  5517. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  5518. this._loadBone(node, skin, babylonBones);
  5519. }
  5520. };
  5521. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  5522. var babylonBone = babylonBones[node.index];
  5523. if (babylonBone) {
  5524. return babylonBone;
  5525. }
  5526. var babylonParentBone = null;
  5527. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  5528. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  5529. }
  5530. var boneIndex = skin.joints.indexOf(node.index);
  5531. babylonBone = new babylonjs_1.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  5532. babylonBones[node.index] = babylonBone;
  5533. node._babylonBones = node._babylonBones || [];
  5534. node._babylonBones.push(babylonBone);
  5535. return babylonBone;
  5536. };
  5537. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  5538. if (skin.inverseBindMatrices == undefined) {
  5539. return Promise.resolve(null);
  5540. }
  5541. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  5542. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  5543. };
  5544. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  5545. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  5546. var babylonBone = _a[_i];
  5547. var baseMatrix = babylonjs_1.Matrix.Identity();
  5548. var boneIndex = babylonBone._index;
  5549. if (inverseBindMatricesData && boneIndex !== -1) {
  5550. babylonjs_1.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  5551. baseMatrix.invertToRef(baseMatrix);
  5552. }
  5553. var babylonParentBone = babylonBone.getParent();
  5554. if (babylonParentBone) {
  5555. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  5556. }
  5557. babylonBone.updateMatrix(baseMatrix, false, false);
  5558. babylonBone._updateDifferenceMatrix(undefined, false);
  5559. }
  5560. };
  5561. GLTFLoader.prototype._getNodeMatrix = function (node) {
  5562. return node.matrix ?
  5563. babylonjs_1.Matrix.FromArray(node.matrix) :
  5564. babylonjs_1.Matrix.Compose(node.scale ? babylonjs_1.Vector3.FromArray(node.scale) : babylonjs_1.Vector3.One(), node.rotation ? babylonjs_1.Quaternion.FromArray(node.rotation) : babylonjs_1.Quaternion.Identity(), node.translation ? babylonjs_1.Vector3.FromArray(node.translation) : babylonjs_1.Vector3.Zero());
  5565. };
  5566. /**
  5567. * Loads a glTF camera.
  5568. * @param context The context when loading the asset
  5569. * @param camera The glTF camera property
  5570. * @param assign A function called synchronously after parsing the glTF properties
  5571. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  5572. */
  5573. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  5574. if (assign === void 0) { assign = function () { }; }
  5575. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  5576. if (extensionPromise) {
  5577. return extensionPromise;
  5578. }
  5579. var promises = new Array();
  5580. this.logOpen(context + " " + (camera.name || ""));
  5581. var babylonCamera = new babylonjs_1.FreeCamera(camera.name || "camera" + camera.index, babylonjs_1.Vector3.Zero(), this.babylonScene, false);
  5582. babylonCamera.rotation = new babylonjs_1.Vector3(0, Math.PI, 0);
  5583. switch (camera.type) {
  5584. case "perspective" /* PERSPECTIVE */: {
  5585. var perspective = camera.perspective;
  5586. if (!perspective) {
  5587. throw new Error(context + ": Camera perspective properties are missing");
  5588. }
  5589. babylonCamera.fov = perspective.yfov;
  5590. babylonCamera.minZ = perspective.znear;
  5591. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  5592. break;
  5593. }
  5594. case "orthographic" /* ORTHOGRAPHIC */: {
  5595. if (!camera.orthographic) {
  5596. throw new Error(context + ": Camera orthographic properties are missing");
  5597. }
  5598. babylonCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  5599. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  5600. babylonCamera.orthoRight = camera.orthographic.xmag;
  5601. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  5602. babylonCamera.orthoTop = camera.orthographic.ymag;
  5603. babylonCamera.minZ = camera.orthographic.znear;
  5604. babylonCamera.maxZ = camera.orthographic.zfar;
  5605. break;
  5606. }
  5607. default: {
  5608. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  5609. }
  5610. }
  5611. assign(babylonCamera);
  5612. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  5613. return Promise.all(promises).then(function () {
  5614. return babylonCamera;
  5615. });
  5616. };
  5617. GLTFLoader.prototype._loadAnimationsAsync = function () {
  5618. var animations = this.gltf.animations;
  5619. if (!animations) {
  5620. return Promise.resolve();
  5621. }
  5622. var promises = new Array();
  5623. for (var index = 0; index < animations.length; index++) {
  5624. var animation = animations[index];
  5625. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  5626. }
  5627. return Promise.all(promises).then(function () { });
  5628. };
  5629. /**
  5630. * Loads a glTF animation.
  5631. * @param context The context when loading the asset
  5632. * @param animation The glTF animation property
  5633. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  5634. */
  5635. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  5636. var promise = this._extensionsLoadAnimationAsync(context, animation);
  5637. if (promise) {
  5638. return promise;
  5639. }
  5640. var babylonAnimationGroup = new babylonjs_1.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  5641. animation._babylonAnimationGroup = babylonAnimationGroup;
  5642. var promises = new Array();
  5643. ArrayItem.Assign(animation.channels);
  5644. ArrayItem.Assign(animation.samplers);
  5645. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  5646. var channel = _a[_i];
  5647. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  5648. }
  5649. return Promise.all(promises).then(function () {
  5650. babylonAnimationGroup.normalize(0);
  5651. return babylonAnimationGroup;
  5652. });
  5653. };
  5654. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  5655. var _this = this;
  5656. if (channel.target.node == undefined) {
  5657. return Promise.resolve();
  5658. }
  5659. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  5660. // Ignore animations that have no animation targets.
  5661. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  5662. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  5663. return Promise.resolve();
  5664. }
  5665. // Ignore animations targeting TRS of skinned nodes.
  5666. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  5667. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  5668. return Promise.resolve();
  5669. }
  5670. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  5671. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  5672. var targetPath;
  5673. var animationType;
  5674. switch (channel.target.path) {
  5675. case "translation" /* TRANSLATION */: {
  5676. targetPath = "position";
  5677. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  5678. break;
  5679. }
  5680. case "rotation" /* ROTATION */: {
  5681. targetPath = "rotationQuaternion";
  5682. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  5683. break;
  5684. }
  5685. case "scale" /* SCALE */: {
  5686. targetPath = "scaling";
  5687. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  5688. break;
  5689. }
  5690. case "weights" /* WEIGHTS */: {
  5691. targetPath = "influence";
  5692. animationType = babylonjs_1.Animation.ANIMATIONTYPE_FLOAT;
  5693. break;
  5694. }
  5695. default: {
  5696. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  5697. }
  5698. }
  5699. var outputBufferOffset = 0;
  5700. var getNextOutputValue;
  5701. switch (targetPath) {
  5702. case "position": {
  5703. getNextOutputValue = function () {
  5704. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  5705. outputBufferOffset += 3;
  5706. return value;
  5707. };
  5708. break;
  5709. }
  5710. case "rotationQuaternion": {
  5711. getNextOutputValue = function () {
  5712. var value = babylonjs_1.Quaternion.FromArray(data.output, outputBufferOffset);
  5713. outputBufferOffset += 4;
  5714. return value;
  5715. };
  5716. break;
  5717. }
  5718. case "scaling": {
  5719. getNextOutputValue = function () {
  5720. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  5721. outputBufferOffset += 3;
  5722. return value;
  5723. };
  5724. break;
  5725. }
  5726. case "influence": {
  5727. getNextOutputValue = function () {
  5728. var value = new Array(targetNode._numMorphTargets);
  5729. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  5730. value[i] = data.output[outputBufferOffset++];
  5731. }
  5732. return value;
  5733. };
  5734. break;
  5735. }
  5736. }
  5737. var getNextKey;
  5738. switch (data.interpolation) {
  5739. case "STEP" /* STEP */: {
  5740. getNextKey = function (frameIndex) { return ({
  5741. frame: data.input[frameIndex],
  5742. value: getNextOutputValue(),
  5743. interpolation: babylonjs_1.AnimationKeyInterpolation.STEP
  5744. }); };
  5745. break;
  5746. }
  5747. case "LINEAR" /* LINEAR */: {
  5748. getNextKey = function (frameIndex) { return ({
  5749. frame: data.input[frameIndex],
  5750. value: getNextOutputValue()
  5751. }); };
  5752. break;
  5753. }
  5754. case "CUBICSPLINE" /* CUBICSPLINE */: {
  5755. getNextKey = function (frameIndex) { return ({
  5756. frame: data.input[frameIndex],
  5757. inTangent: getNextOutputValue(),
  5758. value: getNextOutputValue(),
  5759. outTangent: getNextOutputValue()
  5760. }); };
  5761. break;
  5762. }
  5763. }
  5764. var keys = new Array(data.input.length);
  5765. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  5766. keys[frameIndex] = getNextKey(frameIndex);
  5767. }
  5768. if (targetPath === "influence") {
  5769. var _loop_2 = function (targetIndex) {
  5770. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  5771. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  5772. babylonAnimation.setKeys(keys.map(function (key) { return ({
  5773. frame: key.frame,
  5774. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  5775. value: key.value[targetIndex],
  5776. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  5777. }); }));
  5778. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  5779. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  5780. var babylonAnimationClone = babylonAnimation.clone();
  5781. morphTarget.animations.push(babylonAnimationClone);
  5782. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  5783. });
  5784. };
  5785. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  5786. _loop_2(targetIndex);
  5787. }
  5788. }
  5789. else {
  5790. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  5791. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  5792. babylonAnimation.setKeys(keys);
  5793. if (targetNode._babylonBones) {
  5794. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  5795. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  5796. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  5797. babylonAnimationTarget.animations.push(babylonAnimation);
  5798. }
  5799. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  5800. }
  5801. else {
  5802. targetNode._babylonMesh.animations.push(babylonAnimation);
  5803. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  5804. }
  5805. }
  5806. });
  5807. };
  5808. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  5809. if (sampler._data) {
  5810. return sampler._data;
  5811. }
  5812. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  5813. switch (interpolation) {
  5814. case "STEP" /* STEP */:
  5815. case "LINEAR" /* LINEAR */:
  5816. case "CUBICSPLINE" /* CUBICSPLINE */: {
  5817. break;
  5818. }
  5819. default: {
  5820. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  5821. }
  5822. }
  5823. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  5824. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  5825. sampler._data = Promise.all([
  5826. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  5827. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  5828. ]).then(function (_a) {
  5829. var inputData = _a[0], outputData = _a[1];
  5830. return {
  5831. input: inputData,
  5832. interpolation: interpolation,
  5833. output: outputData,
  5834. };
  5835. });
  5836. return sampler._data;
  5837. };
  5838. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  5839. if (buffer._data) {
  5840. return buffer._data;
  5841. }
  5842. if (!buffer.uri) {
  5843. throw new Error(context + "/uri: Value is missing");
  5844. }
  5845. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  5846. return buffer._data;
  5847. };
  5848. /**
  5849. * Loads a glTF buffer view.
  5850. * @param context The context when loading the asset
  5851. * @param bufferView The glTF buffer view property
  5852. * @returns A promise that resolves with the loaded data when the load is complete
  5853. */
  5854. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  5855. if (bufferView._data) {
  5856. return bufferView._data;
  5857. }
  5858. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  5859. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  5860. try {
  5861. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  5862. }
  5863. catch (e) {
  5864. throw new Error(context + ": " + e.message);
  5865. }
  5866. });
  5867. return bufferView._data;
  5868. };
  5869. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  5870. if (accessor.type !== "SCALAR" /* SCALAR */) {
  5871. throw new Error(context + "/type: Invalid value " + accessor.type);
  5872. }
  5873. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  5874. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  5875. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  5876. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  5877. }
  5878. if (accessor._data) {
  5879. return accessor._data;
  5880. }
  5881. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5882. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5883. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  5884. });
  5885. return accessor._data;
  5886. };
  5887. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  5888. // TODO: support normalized and stride
  5889. var _this = this;
  5890. if (accessor.componentType !== 5126 /* FLOAT */) {
  5891. throw new Error("Invalid component type " + accessor.componentType);
  5892. }
  5893. if (accessor._data) {
  5894. return accessor._data;
  5895. }
  5896. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  5897. var length = numComponents * accessor.count;
  5898. if (accessor.bufferView == undefined) {
  5899. accessor._data = Promise.resolve(new Float32Array(length));
  5900. }
  5901. else {
  5902. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5903. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5904. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  5905. });
  5906. }
  5907. if (accessor.sparse) {
  5908. var sparse_1 = accessor.sparse;
  5909. accessor._data = accessor._data.then(function (data) {
  5910. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  5911. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  5912. return Promise.all([
  5913. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  5914. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  5915. ]).then(function (_a) {
  5916. var indicesData = _a[0], valuesData = _a[1];
  5917. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  5918. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  5919. var valuesIndex = 0;
  5920. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  5921. var dataIndex = indices[indicesIndex] * numComponents;
  5922. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  5923. data[dataIndex++] = values[valuesIndex++];
  5924. }
  5925. }
  5926. return data;
  5927. });
  5928. });
  5929. }
  5930. return accessor._data;
  5931. };
  5932. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  5933. var _this = this;
  5934. if (bufferView._babylonBuffer) {
  5935. return bufferView._babylonBuffer;
  5936. }
  5937. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5938. return new babylonjs_1.Buffer(_this.babylonScene.getEngine(), data, false);
  5939. });
  5940. return bufferView._babylonBuffer;
  5941. };
  5942. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  5943. var _this = this;
  5944. if (accessor._babylonVertexBuffer) {
  5945. return accessor._babylonVertexBuffer;
  5946. }
  5947. if (accessor.sparse) {
  5948. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5949. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5950. });
  5951. }
  5952. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  5953. else if (accessor.byteOffset && accessor.byteOffset % babylonjs_1.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  5954. babylonjs_1.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  5955. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5956. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5957. });
  5958. }
  5959. else {
  5960. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5961. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  5962. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  5963. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  5964. });
  5965. }
  5966. return accessor._babylonVertexBuffer;
  5967. };
  5968. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  5969. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  5970. throw new Error(context + ": Material type not supported");
  5971. }
  5972. var promises = new Array();
  5973. if (properties) {
  5974. if (properties.baseColorFactor) {
  5975. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  5976. babylonMaterial.alpha = properties.baseColorFactor[3];
  5977. }
  5978. else {
  5979. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  5980. }
  5981. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  5982. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  5983. if (properties.baseColorTexture) {
  5984. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  5985. babylonMaterial.albedoTexture = texture;
  5986. }));
  5987. }
  5988. if (properties.metallicRoughnessTexture) {
  5989. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  5990. babylonMaterial.metallicTexture = texture;
  5991. }));
  5992. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  5993. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  5994. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  5995. }
  5996. }
  5997. return Promise.all(promises).then(function () { });
  5998. };
  5999. /** @hidden */
  6000. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  6001. if (assign === void 0) { assign = function () { }; }
  6002. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  6003. if (extensionPromise) {
  6004. return extensionPromise;
  6005. }
  6006. material._babylonData = material._babylonData || {};
  6007. var babylonData = material._babylonData[babylonDrawMode];
  6008. if (!babylonData) {
  6009. this.logOpen(context + " " + (material.name || ""));
  6010. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  6011. babylonData = {
  6012. material: babylonMaterial,
  6013. meshes: [],
  6014. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  6015. };
  6016. material._babylonData[babylonDrawMode] = babylonData;
  6017. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  6018. this.logClose();
  6019. }
  6020. babylonData.meshes.push(babylonMesh);
  6021. babylonMesh.onDisposeObservable.addOnce(function () {
  6022. var index = babylonData.meshes.indexOf(babylonMesh);
  6023. if (index !== -1) {
  6024. babylonData.meshes.splice(index, 1);
  6025. }
  6026. });
  6027. assign(babylonData.material);
  6028. return babylonData.promise.then(function () {
  6029. return babylonData.material;
  6030. });
  6031. };
  6032. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  6033. var babylonMaterial = new babylonjs_1.PBRMaterial(name, this.babylonScene);
  6034. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? babylonjs_1.Material.CounterClockWiseSideOrientation : babylonjs_1.Material.ClockWiseSideOrientation;
  6035. babylonMaterial.fillMode = babylonDrawMode;
  6036. babylonMaterial.enableSpecularAntiAliasing = true;
  6037. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  6038. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  6039. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  6040. babylonMaterial.metallic = 1;
  6041. babylonMaterial.roughness = 1;
  6042. return babylonMaterial;
  6043. };
  6044. /**
  6045. * Creates a Babylon material from a glTF material.
  6046. * @param context The context when loading the asset
  6047. * @param material The glTF material property
  6048. * @param babylonDrawMode The draw mode for the Babylon material
  6049. * @returns The Babylon material
  6050. */
  6051. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  6052. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  6053. if (extensionPromise) {
  6054. return extensionPromise;
  6055. }
  6056. var name = material.name || "material" + material.index;
  6057. return this._createDefaultMaterial(name, babylonDrawMode);
  6058. };
  6059. /**
  6060. * Loads properties from a glTF material into a Babylon material.
  6061. * @param context The context when loading the asset
  6062. * @param material The glTF material property
  6063. * @param babylonMaterial The Babylon material
  6064. * @returns A promise that resolves when the load is complete
  6065. */
  6066. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6067. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  6068. if (extensionPromise) {
  6069. return extensionPromise;
  6070. }
  6071. var promises = new Array();
  6072. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  6073. if (material.pbrMetallicRoughness) {
  6074. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  6075. }
  6076. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  6077. return Promise.all(promises).then(function () { });
  6078. };
  6079. /**
  6080. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  6081. * @param context The context when loading the asset
  6082. * @param material The glTF material property
  6083. * @param babylonMaterial The Babylon material
  6084. * @returns A promise that resolves when the load is complete
  6085. */
  6086. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  6087. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  6088. throw new Error(context + ": Material type not supported");
  6089. }
  6090. var promises = new Array();
  6091. babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_1.Color3.FromArray(material.emissiveFactor) : new babylonjs_1.Color3(0, 0, 0);
  6092. if (material.doubleSided) {
  6093. babylonMaterial.backFaceCulling = false;
  6094. babylonMaterial.twoSidedLighting = true;
  6095. }
  6096. if (material.normalTexture) {
  6097. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  6098. babylonMaterial.bumpTexture = texture;
  6099. }));
  6100. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  6101. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  6102. if (material.normalTexture.scale != undefined) {
  6103. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  6104. }
  6105. }
  6106. if (material.occlusionTexture) {
  6107. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  6108. babylonMaterial.ambientTexture = texture;
  6109. }));
  6110. babylonMaterial.useAmbientInGrayScale = true;
  6111. if (material.occlusionTexture.strength != undefined) {
  6112. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  6113. }
  6114. }
  6115. if (material.emissiveTexture) {
  6116. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  6117. babylonMaterial.emissiveTexture = texture;
  6118. }));
  6119. }
  6120. return Promise.all(promises).then(function () { });
  6121. };
  6122. /**
  6123. * Loads the alpha properties from a glTF material into a Babylon material.
  6124. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  6125. * @param context The context when loading the asset
  6126. * @param material The glTF material property
  6127. * @param babylonMaterial The Babylon material
  6128. */
  6129. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  6130. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  6131. throw new Error(context + ": Material type not supported");
  6132. }
  6133. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  6134. switch (alphaMode) {
  6135. case "OPAQUE" /* OPAQUE */: {
  6136. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  6137. break;
  6138. }
  6139. case "MASK" /* MASK */: {
  6140. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHATEST;
  6141. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  6142. if (babylonMaterial.albedoTexture) {
  6143. babylonMaterial.albedoTexture.hasAlpha = true;
  6144. }
  6145. break;
  6146. }
  6147. case "BLEND" /* BLEND */: {
  6148. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  6149. if (babylonMaterial.albedoTexture) {
  6150. babylonMaterial.albedoTexture.hasAlpha = true;
  6151. babylonMaterial.useAlphaFromAlbedoTexture = true;
  6152. }
  6153. break;
  6154. }
  6155. default: {
  6156. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  6157. }
  6158. }
  6159. };
  6160. /**
  6161. * Loads a glTF texture info.
  6162. * @param context The context when loading the asset
  6163. * @param textureInfo The glTF texture info property
  6164. * @param assign A function called synchronously after parsing the glTF properties
  6165. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  6166. */
  6167. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  6168. if (assign === void 0) { assign = function () { }; }
  6169. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  6170. if (extensionPromise) {
  6171. return extensionPromise;
  6172. }
  6173. this.logOpen("" + context);
  6174. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  6175. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  6176. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  6177. assign(babylonTexture);
  6178. });
  6179. this.logClose();
  6180. return promise;
  6181. };
  6182. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  6183. var _this = this;
  6184. if (assign === void 0) { assign = function () { }; }
  6185. var promises = new Array();
  6186. this.logOpen(context + " " + (texture.name || ""));
  6187. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  6188. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  6189. var deferred = new babylonjs_1.Deferred();
  6190. var babylonTexture = new babylonjs_1.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  6191. if (!_this._disposed) {
  6192. deferred.resolve();
  6193. }
  6194. }, function (message, exception) {
  6195. if (!_this._disposed) {
  6196. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  6197. }
  6198. });
  6199. promises.push(deferred.promise);
  6200. babylonTexture.name = texture.name || "texture" + texture.index;
  6201. babylonTexture.wrapU = samplerData.wrapU;
  6202. babylonTexture.wrapV = samplerData.wrapV;
  6203. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  6204. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  6205. var name = image.uri || _this._fileName + "#image" + image.index;
  6206. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  6207. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  6208. }));
  6209. assign(babylonTexture);
  6210. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  6211. this.logClose();
  6212. return Promise.all(promises).then(function () {
  6213. return babylonTexture;
  6214. });
  6215. };
  6216. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  6217. if (!sampler._data) {
  6218. sampler._data = {
  6219. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  6220. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  6221. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  6222. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  6223. };
  6224. }
  6225. return sampler._data;
  6226. };
  6227. /**
  6228. * Loads a glTF image.
  6229. * @param context The context when loading the asset
  6230. * @param image The glTF image property
  6231. * @returns A promise that resolves with the loaded data when the load is complete
  6232. */
  6233. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  6234. if (!image._data) {
  6235. this.logOpen(context + " " + (image.name || ""));
  6236. if (image.uri) {
  6237. image._data = this.loadUriAsync(context + "/uri", image.uri);
  6238. }
  6239. else {
  6240. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  6241. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  6242. }
  6243. this.logClose();
  6244. }
  6245. return image._data;
  6246. };
  6247. /**
  6248. * Loads a glTF uri.
  6249. * @param context The context when loading the asset
  6250. * @param uri The base64 or relative uri
  6251. * @returns A promise that resolves with the loaded data when the load is complete
  6252. */
  6253. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  6254. var _this = this;
  6255. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  6256. if (extensionPromise) {
  6257. return extensionPromise;
  6258. }
  6259. if (!GLTFLoader._ValidateUri(uri)) {
  6260. throw new Error(context + ": '" + uri + "' is invalid");
  6261. }
  6262. if (babylonjs_1.Tools.IsBase64(uri)) {
  6263. var data = new Uint8Array(babylonjs_1.Tools.DecodeBase64(uri));
  6264. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  6265. return Promise.resolve(data);
  6266. }
  6267. this.log("Loading " + uri);
  6268. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  6269. return new Promise(function (resolve, reject) {
  6270. if (!_this._disposed) {
  6271. var request_1 = babylonjs_1.Tools.LoadFile(url, function (fileData) {
  6272. if (!_this._disposed) {
  6273. var data = new Uint8Array(fileData);
  6274. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  6275. resolve(data);
  6276. }
  6277. }, function (event) {
  6278. if (!_this._disposed) {
  6279. if (request_1) {
  6280. request_1._lengthComputable = event.lengthComputable;
  6281. request_1._loaded = event.loaded;
  6282. request_1._total = event.total;
  6283. }
  6284. if (_this._state === glTFFileLoader_1.GLTFLoaderState.LOADING) {
  6285. try {
  6286. _this._onProgress();
  6287. }
  6288. catch (e) {
  6289. reject(e);
  6290. }
  6291. }
  6292. }
  6293. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  6294. if (!_this._disposed) {
  6295. reject(new babylonjs_1.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  6296. }
  6297. });
  6298. _this._requests.push(request_1);
  6299. }
  6300. });
  6301. });
  6302. };
  6303. GLTFLoader.prototype._onProgress = function () {
  6304. if (!this._progressCallback) {
  6305. return;
  6306. }
  6307. var lengthComputable = true;
  6308. var loaded = 0;
  6309. var total = 0;
  6310. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  6311. var request = _a[_i];
  6312. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  6313. return;
  6314. }
  6315. lengthComputable = lengthComputable && request._lengthComputable;
  6316. loaded += request._loaded;
  6317. total += request._total;
  6318. }
  6319. this._progressCallback(new babylonjs_1.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  6320. };
  6321. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  6322. // Set defaults if undefined
  6323. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  6324. switch (mode) {
  6325. case 33071 /* CLAMP_TO_EDGE */: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  6326. case 33648 /* MIRRORED_REPEAT */: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  6327. case 10497 /* REPEAT */: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  6328. default:
  6329. babylonjs_1.Tools.Warn(context + ": Invalid value (" + mode + ")");
  6330. return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  6331. }
  6332. };
  6333. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  6334. // Set defaults if undefined
  6335. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  6336. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  6337. if (magFilter === 9729 /* LINEAR */) {
  6338. switch (minFilter) {
  6339. case 9728 /* NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST;
  6340. case 9729 /* LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR;
  6341. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPNEAREST;
  6342. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPNEAREST;
  6343. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPLINEAR;
  6344. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  6345. default:
  6346. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  6347. return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  6348. }
  6349. }
  6350. else {
  6351. if (magFilter !== 9728 /* NEAREST */) {
  6352. babylonjs_1.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  6353. }
  6354. switch (minFilter) {
  6355. case 9728 /* NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST;
  6356. case 9729 /* LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR;
  6357. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  6358. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPNEAREST;
  6359. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPLINEAR;
  6360. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPLINEAR;
  6361. default:
  6362. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  6363. return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  6364. }
  6365. }
  6366. };
  6367. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  6368. var buffer = bufferView.buffer;
  6369. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  6370. try {
  6371. switch (componentType) {
  6372. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  6373. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  6374. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  6375. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  6376. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  6377. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  6378. default: throw new Error("Invalid component type " + componentType);
  6379. }
  6380. }
  6381. catch (e) {
  6382. throw new Error(context + ": " + e);
  6383. }
  6384. };
  6385. GLTFLoader._GetNumComponents = function (context, type) {
  6386. switch (type) {
  6387. case "SCALAR": return 1;
  6388. case "VEC2": return 2;
  6389. case "VEC3": return 3;
  6390. case "VEC4": return 4;
  6391. case "MAT2": return 4;
  6392. case "MAT3": return 9;
  6393. case "MAT4": return 16;
  6394. }
  6395. throw new Error(context + ": Invalid type (" + type + ")");
  6396. };
  6397. GLTFLoader._ValidateUri = function (uri) {
  6398. return (babylonjs_1.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  6399. };
  6400. GLTFLoader._GetDrawMode = function (context, mode) {
  6401. if (mode == undefined) {
  6402. mode = 4 /* TRIANGLES */;
  6403. }
  6404. switch (mode) {
  6405. case 0 /* POINTS */: return babylonjs_1.Material.PointListDrawMode;
  6406. case 1 /* LINES */: return babylonjs_1.Material.LineListDrawMode;
  6407. case 2 /* LINE_LOOP */: return babylonjs_1.Material.LineLoopDrawMode;
  6408. case 3 /* LINE_STRIP */: return babylonjs_1.Material.LineStripDrawMode;
  6409. case 4 /* TRIANGLES */: return babylonjs_1.Material.TriangleFillMode;
  6410. case 5 /* TRIANGLE_STRIP */: return babylonjs_1.Material.TriangleStripDrawMode;
  6411. case 6 /* TRIANGLE_FAN */: return babylonjs_1.Material.TriangleFanDrawMode;
  6412. }
  6413. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  6414. };
  6415. GLTFLoader.prototype._compileMaterialsAsync = function () {
  6416. var _this = this;
  6417. this._parent._startPerformanceCounter("Compile materials");
  6418. var promises = new Array();
  6419. if (this.gltf.materials) {
  6420. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  6421. var material = _a[_i];
  6422. if (material._babylonData) {
  6423. for (var babylonDrawMode in material._babylonData) {
  6424. var babylonData = material._babylonData[babylonDrawMode];
  6425. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  6426. var babylonMesh = _c[_b];
  6427. // Ensure nonUniformScaling is set if necessary.
  6428. babylonMesh.computeWorldMatrix(true);
  6429. var babylonMaterial = babylonData.material;
  6430. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  6431. if (this._parent.useClipPlane) {
  6432. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  6433. }
  6434. }
  6435. }
  6436. }
  6437. }
  6438. }
  6439. return Promise.all(promises).then(function () {
  6440. _this._parent._endPerformanceCounter("Compile materials");
  6441. });
  6442. };
  6443. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  6444. var _this = this;
  6445. this._parent._startPerformanceCounter("Compile shadow generators");
  6446. var promises = new Array();
  6447. var lights = this.babylonScene.lights;
  6448. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  6449. var light = lights_1[_i];
  6450. var generator = light.getShadowGenerator();
  6451. if (generator) {
  6452. promises.push(generator.forceCompilationAsync());
  6453. }
  6454. }
  6455. return Promise.all(promises).then(function () {
  6456. _this._parent._endPerformanceCounter("Compile shadow generators");
  6457. });
  6458. };
  6459. GLTFLoader.prototype._forEachExtensions = function (action) {
  6460. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  6461. var name_4 = _a[_i];
  6462. var extension = this._extensions[name_4];
  6463. if (extension.enabled) {
  6464. action(extension);
  6465. }
  6466. }
  6467. };
  6468. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  6469. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  6470. var name_5 = _a[_i];
  6471. var extension = this._extensions[name_5];
  6472. if (extension.enabled) {
  6473. var loaderProperty = property;
  6474. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  6475. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  6476. if (!activeLoaderExtensions[name_5]) {
  6477. activeLoaderExtensions[name_5] = true;
  6478. try {
  6479. var result = actionAsync(extension);
  6480. if (result) {
  6481. return result;
  6482. }
  6483. }
  6484. finally {
  6485. delete activeLoaderExtensions[name_5];
  6486. }
  6487. }
  6488. }
  6489. }
  6490. return null;
  6491. };
  6492. GLTFLoader.prototype._extensionsOnLoading = function () {
  6493. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  6494. };
  6495. GLTFLoader.prototype._extensionsOnReady = function () {
  6496. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  6497. };
  6498. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  6499. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  6500. };
  6501. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  6502. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  6503. };
  6504. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  6505. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  6506. };
  6507. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  6508. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  6509. };
  6510. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  6511. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  6512. };
  6513. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  6514. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  6515. };
  6516. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6517. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  6518. };
  6519. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  6520. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  6521. };
  6522. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  6523. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  6524. };
  6525. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  6526. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  6527. };
  6528. /**
  6529. * Helper method called by a loader extension to load an glTF extension.
  6530. * @param context The context when loading the asset
  6531. * @param property The glTF property to load the extension from
  6532. * @param extensionName The name of the extension to load
  6533. * @param actionAsync The action to run
  6534. * @returns The promise returned by actionAsync or null if the extension does not exist
  6535. */
  6536. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  6537. if (!property.extensions) {
  6538. return null;
  6539. }
  6540. var extensions = property.extensions;
  6541. var extension = extensions[extensionName];
  6542. if (!extension) {
  6543. return null;
  6544. }
  6545. return actionAsync(context + "/extensions/" + extensionName, extension);
  6546. };
  6547. /**
  6548. * Helper method called by a loader extension to load a glTF extra.
  6549. * @param context The context when loading the asset
  6550. * @param property The glTF property to load the extra from
  6551. * @param extensionName The name of the extension to load
  6552. * @param actionAsync The action to run
  6553. * @returns The promise returned by actionAsync or null if the extra does not exist
  6554. */
  6555. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  6556. if (!property.extras) {
  6557. return null;
  6558. }
  6559. var extras = property.extras;
  6560. var extra = extras[extensionName];
  6561. if (!extra) {
  6562. return null;
  6563. }
  6564. return actionAsync(context + "/extras/" + extensionName, extra);
  6565. };
  6566. /**
  6567. * Increments the indentation level and logs a message.
  6568. * @param message The message to log
  6569. */
  6570. GLTFLoader.prototype.logOpen = function (message) {
  6571. this._parent._logOpen(message);
  6572. };
  6573. /**
  6574. * Decrements the indentation level.
  6575. */
  6576. GLTFLoader.prototype.logClose = function () {
  6577. this._parent._logClose();
  6578. };
  6579. /**
  6580. * Logs a message
  6581. * @param message The message to log
  6582. */
  6583. GLTFLoader.prototype.log = function (message) {
  6584. this._parent._log(message);
  6585. };
  6586. /**
  6587. * Starts a performance counter.
  6588. * @param counterName The name of the performance counter
  6589. */
  6590. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  6591. this._parent._startPerformanceCounter(counterName);
  6592. };
  6593. /**
  6594. * Ends a performance counter.
  6595. * @param counterName The name of the performance counter
  6596. */
  6597. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  6598. this._parent._endPerformanceCounter(counterName);
  6599. };
  6600. GLTFLoader._DefaultSampler = { index: -1 };
  6601. GLTFLoader._ExtensionNames = new Array();
  6602. GLTFLoader._ExtensionFactories = {};
  6603. return GLTFLoader;
  6604. }());
  6605. exports.GLTFLoader = GLTFLoader;
  6606. glTFFileLoader_1.GLTFFileLoader._CreateGLTF2Loader = function (parent) { return new GLTFLoader(parent); };
  6607. /***/ }),
  6608. /***/ "./src/glTF/2.0/glTFLoaderExtension.ts":
  6609. /*!*********************************************!*\
  6610. !*** ./src/glTF/2.0/glTFLoaderExtension.ts ***!
  6611. \*********************************************/
  6612. /*! no static exports found */
  6613. /***/ (function(module, exports, __webpack_require__) {
  6614. "use strict";
  6615. Object.defineProperty(exports, "__esModule", { value: true });
  6616. /** @hidden */
  6617. exports.__IGLTFLoaderExtension = 0; // I am here to allow dts to be created
  6618. /***/ }),
  6619. /***/ "./src/glTF/2.0/glTFLoaderInterfaces.ts":
  6620. /*!**********************************************!*\
  6621. !*** ./src/glTF/2.0/glTFLoaderInterfaces.ts ***!
  6622. \**********************************************/
  6623. /*! no static exports found */
  6624. /***/ (function(module, exports, __webpack_require__) {
  6625. "use strict";
  6626. Object.defineProperty(exports, "__esModule", { value: true });
  6627. /** @hidden */
  6628. exports.__IGLTFLoaderInterfacesV2 = 0; // I am here to allow dts to be created
  6629. /***/ }),
  6630. /***/ "./src/glTF/2.0/index.ts":
  6631. /*!*******************************!*\
  6632. !*** ./src/glTF/2.0/index.ts ***!
  6633. \*******************************/
  6634. /*! no static exports found */
  6635. /***/ (function(module, exports, __webpack_require__) {
  6636. "use strict";
  6637. function __export(m) {
  6638. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  6639. }
  6640. Object.defineProperty(exports, "__esModule", { value: true });
  6641. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/2.0/glTFLoader.ts"));
  6642. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/2.0/glTFLoaderExtension.ts"));
  6643. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts"));
  6644. __export(__webpack_require__(/*! ./Extensions */ "./src/glTF/2.0/Extensions/index.ts"));
  6645. /***/ }),
  6646. /***/ "./src/glTF/glTFFileLoader.ts":
  6647. /*!************************************!*\
  6648. !*** ./src/glTF/glTFFileLoader.ts ***!
  6649. \************************************/
  6650. /*! no static exports found */
  6651. /***/ (function(module, exports, __webpack_require__) {
  6652. "use strict";
  6653. Object.defineProperty(exports, "__esModule", { value: true });
  6654. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  6655. /**
  6656. * Mode that determines the coordinate system to use.
  6657. */
  6658. var GLTFLoaderCoordinateSystemMode;
  6659. (function (GLTFLoaderCoordinateSystemMode) {
  6660. /**
  6661. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  6662. */
  6663. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  6664. /**
  6665. * Sets the useRightHandedSystem flag on the scene.
  6666. */
  6667. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  6668. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  6669. /**
  6670. * Mode that determines what animations will start.
  6671. */
  6672. var GLTFLoaderAnimationStartMode;
  6673. (function (GLTFLoaderAnimationStartMode) {
  6674. /**
  6675. * No animation will start.
  6676. */
  6677. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  6678. /**
  6679. * The first animation will start.
  6680. */
  6681. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  6682. /**
  6683. * All animations will start.
  6684. */
  6685. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  6686. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  6687. /**
  6688. * Loader state.
  6689. */
  6690. var GLTFLoaderState;
  6691. (function (GLTFLoaderState) {
  6692. /**
  6693. * The asset is loading.
  6694. */
  6695. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  6696. /**
  6697. * The asset is ready for rendering.
  6698. */
  6699. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  6700. /**
  6701. * The asset is completely loaded.
  6702. */
  6703. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  6704. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  6705. /**
  6706. * File loader for loading glTF files into a scene.
  6707. */
  6708. var GLTFFileLoader = /** @class */ (function () {
  6709. function GLTFFileLoader() {
  6710. // --------------
  6711. // Common options
  6712. // --------------
  6713. /**
  6714. * Raised when the asset has been parsed
  6715. */
  6716. this.onParsedObservable = new babylonjs_1.Observable();
  6717. // ----------
  6718. // V2 options
  6719. // ----------
  6720. /**
  6721. * The coordinate system mode. Defaults to AUTO.
  6722. */
  6723. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  6724. /**
  6725. * The animation start mode. Defaults to FIRST.
  6726. */
  6727. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  6728. /**
  6729. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  6730. */
  6731. this.compileMaterials = false;
  6732. /**
  6733. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  6734. */
  6735. this.useClipPlane = false;
  6736. /**
  6737. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  6738. */
  6739. this.compileShadowGenerators = false;
  6740. /**
  6741. * Defines if the Alpha blended materials are only applied as coverage.
  6742. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  6743. * If true, no extra effects are applied to transparent pixels.
  6744. */
  6745. this.transparencyAsCoverage = false;
  6746. /**
  6747. * Function called before loading a url referenced by the asset.
  6748. */
  6749. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  6750. /**
  6751. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  6752. */
  6753. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  6754. /**
  6755. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  6756. */
  6757. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  6758. /**
  6759. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  6760. */
  6761. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  6762. /**
  6763. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  6764. */
  6765. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  6766. /**
  6767. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  6768. * For assets with LODs, raised when all of the LODs are complete.
  6769. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  6770. */
  6771. this.onCompleteObservable = new babylonjs_1.Observable();
  6772. /**
  6773. * Observable raised when an error occurs.
  6774. */
  6775. this.onErrorObservable = new babylonjs_1.Observable();
  6776. /**
  6777. * Observable raised after the loader is disposed.
  6778. */
  6779. this.onDisposeObservable = new babylonjs_1.Observable();
  6780. /**
  6781. * Observable raised after a loader extension is created.
  6782. * Set additional options for a loader extension in this event.
  6783. */
  6784. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  6785. /**
  6786. * Defines if the loader should validate the asset.
  6787. */
  6788. this.validate = false;
  6789. /**
  6790. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  6791. */
  6792. this.onValidatedObservable = new babylonjs_1.Observable();
  6793. this._loader = null;
  6794. /**
  6795. * Name of the loader ("gltf")
  6796. */
  6797. this.name = "gltf";
  6798. /**
  6799. * Supported file extensions of the loader (.gltf, .glb)
  6800. */
  6801. this.extensions = {
  6802. ".gltf": { isBinary: false },
  6803. ".glb": { isBinary: true }
  6804. };
  6805. this._logIndentLevel = 0;
  6806. this._loggingEnabled = false;
  6807. /** @hidden */
  6808. this._log = this._logDisabled;
  6809. this._capturePerformanceCounters = false;
  6810. /** @hidden */
  6811. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  6812. /** @hidden */
  6813. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  6814. }
  6815. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  6816. /**
  6817. * Raised when the asset has been parsed
  6818. */
  6819. set: function (callback) {
  6820. if (this._onParsedObserver) {
  6821. this.onParsedObservable.remove(this._onParsedObserver);
  6822. }
  6823. this._onParsedObserver = this.onParsedObservable.add(callback);
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  6829. /**
  6830. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  6831. */
  6832. set: function (callback) {
  6833. if (this._onMeshLoadedObserver) {
  6834. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  6835. }
  6836. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  6837. },
  6838. enumerable: true,
  6839. configurable: true
  6840. });
  6841. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  6842. /**
  6843. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  6844. */
  6845. set: function (callback) {
  6846. if (this._onTextureLoadedObserver) {
  6847. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  6848. }
  6849. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  6850. },
  6851. enumerable: true,
  6852. configurable: true
  6853. });
  6854. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  6855. /**
  6856. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  6857. */
  6858. set: function (callback) {
  6859. if (this._onMaterialLoadedObserver) {
  6860. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  6861. }
  6862. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  6863. },
  6864. enumerable: true,
  6865. configurable: true
  6866. });
  6867. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  6868. /**
  6869. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  6870. */
  6871. set: function (callback) {
  6872. if (this._onCameraLoadedObserver) {
  6873. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  6874. }
  6875. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  6881. /**
  6882. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  6883. * For assets with LODs, raised when all of the LODs are complete.
  6884. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  6885. */
  6886. set: function (callback) {
  6887. if (this._onCompleteObserver) {
  6888. this.onCompleteObservable.remove(this._onCompleteObserver);
  6889. }
  6890. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  6896. /**
  6897. * Callback raised when an error occurs.
  6898. */
  6899. set: function (callback) {
  6900. if (this._onErrorObserver) {
  6901. this.onErrorObservable.remove(this._onErrorObserver);
  6902. }
  6903. this._onErrorObserver = this.onErrorObservable.add(callback);
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  6909. /**
  6910. * Callback raised after the loader is disposed.
  6911. */
  6912. set: function (callback) {
  6913. if (this._onDisposeObserver) {
  6914. this.onDisposeObservable.remove(this._onDisposeObserver);
  6915. }
  6916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  6922. /**
  6923. * Callback raised after a loader extension is created.
  6924. */
  6925. set: function (callback) {
  6926. if (this._onExtensionLoadedObserver) {
  6927. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  6928. }
  6929. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  6935. /**
  6936. * Defines if the loader logging is enabled.
  6937. */
  6938. get: function () {
  6939. return this._loggingEnabled;
  6940. },
  6941. set: function (value) {
  6942. if (this._loggingEnabled === value) {
  6943. return;
  6944. }
  6945. this._loggingEnabled = value;
  6946. if (this._loggingEnabled) {
  6947. this._log = this._logEnabled;
  6948. }
  6949. else {
  6950. this._log = this._logDisabled;
  6951. }
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  6957. /**
  6958. * Defines if the loader should capture performance counters.
  6959. */
  6960. get: function () {
  6961. return this._capturePerformanceCounters;
  6962. },
  6963. set: function (value) {
  6964. if (this._capturePerformanceCounters === value) {
  6965. return;
  6966. }
  6967. this._capturePerformanceCounters = value;
  6968. if (this._capturePerformanceCounters) {
  6969. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  6970. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  6971. }
  6972. else {
  6973. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  6974. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  6975. }
  6976. },
  6977. enumerable: true,
  6978. configurable: true
  6979. });
  6980. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  6981. /**
  6982. * Callback raised after a loader extension is created.
  6983. */
  6984. set: function (callback) {
  6985. if (this._onValidatedObserver) {
  6986. this.onValidatedObservable.remove(this._onValidatedObserver);
  6987. }
  6988. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. /**
  6994. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  6995. */
  6996. GLTFFileLoader.prototype.dispose = function () {
  6997. if (this._loader) {
  6998. this._loader.dispose();
  6999. this._loader = null;
  7000. }
  7001. this._clear();
  7002. this.onDisposeObservable.notifyObservers(undefined);
  7003. this.onDisposeObservable.clear();
  7004. };
  7005. /** @hidden */
  7006. GLTFFileLoader.prototype._clear = function () {
  7007. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  7008. this.onMeshLoadedObservable.clear();
  7009. this.onTextureLoadedObservable.clear();
  7010. this.onMaterialLoadedObservable.clear();
  7011. this.onCameraLoadedObservable.clear();
  7012. this.onCompleteObservable.clear();
  7013. this.onExtensionLoadedObservable.clear();
  7014. };
  7015. /**
  7016. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  7017. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  7018. * @param scene the scene the meshes should be added to
  7019. * @param data the glTF data to load
  7020. * @param rootUrl root url to load from
  7021. * @param onProgress event that fires when loading progress has occured
  7022. * @param fileName Defines the name of the file to load
  7023. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  7024. */
  7025. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  7026. var _this = this;
  7027. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  7028. _this._log("Loading " + (fileName || ""));
  7029. _this._loader = _this._getLoader(loaderData);
  7030. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  7031. });
  7032. };
  7033. /**
  7034. * Imports all objects from the loaded glTF data and adds them to the scene
  7035. * @param scene the scene the objects should be added to
  7036. * @param data the glTF data to load
  7037. * @param rootUrl root url to load from
  7038. * @param onProgress event that fires when loading progress has occured
  7039. * @param fileName Defines the name of the file to load
  7040. * @returns a promise which completes when objects have been loaded to the scene
  7041. */
  7042. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  7043. var _this = this;
  7044. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  7045. _this._log("Loading " + (fileName || ""));
  7046. _this._loader = _this._getLoader(loaderData);
  7047. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  7048. });
  7049. };
  7050. /**
  7051. * Load into an asset container.
  7052. * @param scene The scene to load into
  7053. * @param data The data to import
  7054. * @param rootUrl The root url for scene and resources
  7055. * @param onProgress The callback when the load progresses
  7056. * @param fileName Defines the name of the file to load
  7057. * @returns The loaded asset container
  7058. */
  7059. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  7060. var _this = this;
  7061. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  7062. _this._log("Loading " + (fileName || ""));
  7063. _this._loader = _this._getLoader(loaderData);
  7064. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  7065. var container = new babylonjs_1.AssetContainer(scene);
  7066. Array.prototype.push.apply(container.meshes, result.meshes);
  7067. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  7068. Array.prototype.push.apply(container.skeletons, result.skeletons);
  7069. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  7070. container.removeAllFromScene();
  7071. return container;
  7072. });
  7073. });
  7074. };
  7075. /**
  7076. * If the data string can be loaded directly.
  7077. * @param data string contianing the file data
  7078. * @returns if the data can be loaded directly
  7079. */
  7080. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  7081. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  7082. };
  7083. /**
  7084. * Instantiates a glTF file loader plugin.
  7085. * @returns the created plugin
  7086. */
  7087. GLTFFileLoader.prototype.createPlugin = function () {
  7088. return new GLTFFileLoader();
  7089. };
  7090. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  7091. /**
  7092. * The loader state or null if the loader is not active.
  7093. */
  7094. get: function () {
  7095. return this._loader ? this._loader.state : null;
  7096. },
  7097. enumerable: true,
  7098. configurable: true
  7099. });
  7100. /**
  7101. * Returns a promise that resolves when the asset is completely loaded.
  7102. * @returns a promise that resolves when the asset is completely loaded.
  7103. */
  7104. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  7105. var _this = this;
  7106. return new Promise(function (resolve, reject) {
  7107. _this.onCompleteObservable.addOnce(function () {
  7108. resolve();
  7109. });
  7110. _this.onErrorObservable.addOnce(function (reason) {
  7111. reject(reason);
  7112. });
  7113. });
  7114. };
  7115. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  7116. var _this = this;
  7117. return Promise.resolve().then(function () {
  7118. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  7119. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  7120. _this._startPerformanceCounter("Parse JSON");
  7121. _this._log("JSON length: " + unpacked.json.length);
  7122. var loaderData = {
  7123. json: JSON.parse(unpacked.json),
  7124. bin: unpacked.bin
  7125. };
  7126. _this._endPerformanceCounter("Parse JSON");
  7127. _this.onParsedObservable.notifyObservers(loaderData);
  7128. _this.onParsedObservable.clear();
  7129. return loaderData;
  7130. });
  7131. });
  7132. };
  7133. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  7134. var _this = this;
  7135. if (!this.validate || typeof GLTFValidator === "undefined") {
  7136. return Promise.resolve();
  7137. }
  7138. this._startPerformanceCounter("Validate JSON");
  7139. var options = {
  7140. externalResourceFunction: function (uri) {
  7141. return _this.preprocessUrlAsync(rootUrl + uri)
  7142. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  7143. .then(function (data) { return new Uint8Array(data); });
  7144. }
  7145. };
  7146. if (fileName && fileName.substr(0, 5) !== "data:") {
  7147. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  7148. }
  7149. return GLTFValidator.validateString(json, options).then(function (result) {
  7150. _this._endPerformanceCounter("Validate JSON");
  7151. _this.onValidatedObservable.notifyObservers(result);
  7152. _this.onValidatedObservable.clear();
  7153. }, function (reason) {
  7154. _this._endPerformanceCounter("Validate JSON");
  7155. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  7156. _this.onValidatedObservable.clear();
  7157. });
  7158. };
  7159. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  7160. var asset = loaderData.json.asset || {};
  7161. this._log("Asset version: " + asset.version);
  7162. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  7163. asset.generator && this._log("Asset generator: " + asset.generator);
  7164. var version = GLTFFileLoader._parseVersion(asset.version);
  7165. if (!version) {
  7166. throw new Error("Invalid version: " + asset.version);
  7167. }
  7168. if (asset.minVersion !== undefined) {
  7169. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  7170. if (!minVersion) {
  7171. throw new Error("Invalid minimum version: " + asset.minVersion);
  7172. }
  7173. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  7174. throw new Error("Incompatible minimum version: " + asset.minVersion);
  7175. }
  7176. }
  7177. var createLoaders = {
  7178. 1: GLTFFileLoader._CreateGLTF1Loader,
  7179. 2: GLTFFileLoader._CreateGLTF2Loader
  7180. };
  7181. var createLoader = createLoaders[version.major];
  7182. if (!createLoader) {
  7183. throw new Error("Unsupported version: " + asset.version);
  7184. }
  7185. return createLoader(this);
  7186. };
  7187. GLTFFileLoader.prototype._unpackBinary = function (data) {
  7188. this._startPerformanceCounter("Unpack binary");
  7189. this._log("Binary length: " + data.byteLength);
  7190. var Binary = {
  7191. Magic: 0x46546C67
  7192. };
  7193. var binaryReader = new BinaryReader(data);
  7194. var magic = binaryReader.readUint32();
  7195. if (magic !== Binary.Magic) {
  7196. throw new Error("Unexpected magic: " + magic);
  7197. }
  7198. var version = binaryReader.readUint32();
  7199. if (this.loggingEnabled) {
  7200. this._log("Binary version: " + version);
  7201. }
  7202. var unpacked;
  7203. switch (version) {
  7204. case 1: {
  7205. unpacked = this._unpackBinaryV1(binaryReader);
  7206. break;
  7207. }
  7208. case 2: {
  7209. unpacked = this._unpackBinaryV2(binaryReader);
  7210. break;
  7211. }
  7212. default: {
  7213. throw new Error("Unsupported version: " + version);
  7214. }
  7215. }
  7216. this._endPerformanceCounter("Unpack binary");
  7217. return unpacked;
  7218. };
  7219. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  7220. var ContentFormat = {
  7221. JSON: 0
  7222. };
  7223. var length = binaryReader.readUint32();
  7224. if (length != binaryReader.getLength()) {
  7225. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  7226. }
  7227. var contentLength = binaryReader.readUint32();
  7228. var contentFormat = binaryReader.readUint32();
  7229. var content;
  7230. switch (contentFormat) {
  7231. case ContentFormat.JSON: {
  7232. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  7233. break;
  7234. }
  7235. default: {
  7236. throw new Error("Unexpected content format: " + contentFormat);
  7237. }
  7238. }
  7239. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  7240. var body = binaryReader.readUint8Array(bytesRemaining);
  7241. return {
  7242. json: content,
  7243. bin: body
  7244. };
  7245. };
  7246. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  7247. var ChunkFormat = {
  7248. JSON: 0x4E4F534A,
  7249. BIN: 0x004E4942
  7250. };
  7251. var length = binaryReader.readUint32();
  7252. if (length !== binaryReader.getLength()) {
  7253. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  7254. }
  7255. // JSON chunk
  7256. var chunkLength = binaryReader.readUint32();
  7257. var chunkFormat = binaryReader.readUint32();
  7258. if (chunkFormat !== ChunkFormat.JSON) {
  7259. throw new Error("First chunk format is not JSON");
  7260. }
  7261. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  7262. // Look for BIN chunk
  7263. var bin = null;
  7264. while (binaryReader.getPosition() < binaryReader.getLength()) {
  7265. var chunkLength_1 = binaryReader.readUint32();
  7266. var chunkFormat_1 = binaryReader.readUint32();
  7267. switch (chunkFormat_1) {
  7268. case ChunkFormat.JSON: {
  7269. throw new Error("Unexpected JSON chunk");
  7270. }
  7271. case ChunkFormat.BIN: {
  7272. bin = binaryReader.readUint8Array(chunkLength_1);
  7273. break;
  7274. }
  7275. default: {
  7276. // ignore unrecognized chunkFormat
  7277. binaryReader.skipBytes(chunkLength_1);
  7278. break;
  7279. }
  7280. }
  7281. }
  7282. return {
  7283. json: json,
  7284. bin: bin
  7285. };
  7286. };
  7287. GLTFFileLoader._parseVersion = function (version) {
  7288. if (version === "1.0" || version === "1.0.1") {
  7289. return {
  7290. major: 1,
  7291. minor: 0
  7292. };
  7293. }
  7294. var match = (version + "").match(/^(\d+)\.(\d+)/);
  7295. if (!match) {
  7296. return null;
  7297. }
  7298. return {
  7299. major: parseInt(match[1]),
  7300. minor: parseInt(match[2])
  7301. };
  7302. };
  7303. GLTFFileLoader._compareVersion = function (a, b) {
  7304. if (a.major > b.major) {
  7305. return 1;
  7306. }
  7307. if (a.major < b.major) {
  7308. return -1;
  7309. }
  7310. if (a.minor > b.minor) {
  7311. return 1;
  7312. }
  7313. if (a.minor < b.minor) {
  7314. return -1;
  7315. }
  7316. return 0;
  7317. };
  7318. GLTFFileLoader._decodeBufferToText = function (buffer) {
  7319. var result = "";
  7320. var length = buffer.byteLength;
  7321. for (var i = 0; i < length; i++) {
  7322. result += String.fromCharCode(buffer[i]);
  7323. }
  7324. return result;
  7325. };
  7326. /** @hidden */
  7327. GLTFFileLoader.prototype._logOpen = function (message) {
  7328. this._log(message);
  7329. this._logIndentLevel++;
  7330. };
  7331. /** @hidden */
  7332. GLTFFileLoader.prototype._logClose = function () {
  7333. --this._logIndentLevel;
  7334. };
  7335. GLTFFileLoader.prototype._logEnabled = function (message) {
  7336. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  7337. babylonjs_1.Tools.Log("" + spaces + message);
  7338. };
  7339. GLTFFileLoader.prototype._logDisabled = function (message) {
  7340. };
  7341. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  7342. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  7343. };
  7344. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  7345. };
  7346. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  7347. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  7348. };
  7349. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  7350. };
  7351. // ----------
  7352. // V1 options
  7353. // ----------
  7354. /**
  7355. * 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.
  7356. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  7357. * Defaults to true.
  7358. * @hidden
  7359. */
  7360. GLTFFileLoader.IncrementalLoading = true;
  7361. /**
  7362. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  7363. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  7364. * @hidden
  7365. */
  7366. GLTFFileLoader.HomogeneousCoordinates = false;
  7367. GLTFFileLoader._logSpaces = " ";
  7368. return GLTFFileLoader;
  7369. }());
  7370. exports.GLTFFileLoader = GLTFFileLoader;
  7371. var BinaryReader = /** @class */ (function () {
  7372. function BinaryReader(arrayBuffer) {
  7373. this._arrayBuffer = arrayBuffer;
  7374. this._dataView = new DataView(arrayBuffer);
  7375. this._byteOffset = 0;
  7376. }
  7377. BinaryReader.prototype.getPosition = function () {
  7378. return this._byteOffset;
  7379. };
  7380. BinaryReader.prototype.getLength = function () {
  7381. return this._arrayBuffer.byteLength;
  7382. };
  7383. BinaryReader.prototype.readUint32 = function () {
  7384. var value = this._dataView.getUint32(this._byteOffset, true);
  7385. this._byteOffset += 4;
  7386. return value;
  7387. };
  7388. BinaryReader.prototype.readUint8Array = function (length) {
  7389. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  7390. this._byteOffset += length;
  7391. return value;
  7392. };
  7393. BinaryReader.prototype.skipBytes = function (length) {
  7394. this._byteOffset += length;
  7395. };
  7396. return BinaryReader;
  7397. }());
  7398. if (babylonjs_1.SceneLoader) {
  7399. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  7400. }
  7401. /***/ }),
  7402. /***/ "./src/glTF/index.ts":
  7403. /*!***************************!*\
  7404. !*** ./src/glTF/index.ts ***!
  7405. \***************************/
  7406. /*! no static exports found */
  7407. /***/ (function(module, exports, __webpack_require__) {
  7408. "use strict";
  7409. function __export(m) {
  7410. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  7411. }
  7412. Object.defineProperty(exports, "__esModule", { value: true });
  7413. __export(__webpack_require__(/*! ./glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  7414. var GLTF1 = __webpack_require__(/*! ./1.0 */ "./src/glTF/1.0/index.ts");
  7415. exports.GLTF1 = GLTF1;
  7416. var GLTF2 = __webpack_require__(/*! ./2.0 */ "./src/glTF/2.0/index.ts");
  7417. exports.GLTF2 = GLTF2;
  7418. /***/ }),
  7419. /***/ "./src/index.ts":
  7420. /*!**********************!*\
  7421. !*** ./src/index.ts ***!
  7422. \**********************/
  7423. /*! no static exports found */
  7424. /***/ (function(module, exports, __webpack_require__) {
  7425. "use strict";
  7426. function __export(m) {
  7427. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  7428. }
  7429. Object.defineProperty(exports, "__esModule", { value: true });
  7430. __export(__webpack_require__(/*! ./glTF */ "./src/glTF/index.ts"));
  7431. __export(__webpack_require__(/*! ./OBJ */ "./src/OBJ/index.ts"));
  7432. __export(__webpack_require__(/*! ./STL */ "./src/STL/index.ts"));
  7433. /***/ }),
  7434. /***/ "babylonjs":
  7435. /*!****************************************************************************************************!*\
  7436. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  7437. \****************************************************************************************************/
  7438. /*! no static exports found */
  7439. /***/ (function(module, exports) {
  7440. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  7441. /***/ })
  7442. /******/ });
  7443. });
  7444. //# sourceMappingURL=babylonjs.loaders.js.map