babylonjs.loaders.js 352 KB

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