babylonjs.loaders.js 315 KB

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