babylonjs.loaders.js 314 KB

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