babylon.glTFFileLoader.js 311 KB

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