babylonjs.loaders.js 285 KB

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