babylonjs.loaders.js 363 KB

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