babylonjs.loaders.js 284 KB

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