babylonjs.loaders.js 362 KB

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