babylonjs.loaders.js 325 KB

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