babylonjs.loaders.js 323 KB

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