babylonjs.loaders.js 310 KB

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