babylonjs.loaders.js 342 KB

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