babylon.glTFFileLoader.js 283 KB

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