babylon.glTFFileLoader.js 300 KB

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