babylonjs.loaders.js 366 KB

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