three-loader-3dtiles.esm.js 503 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420
  1. import { CanvasTexture, LinearFilter, RepeatWrapping, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1, MeshBasicMaterial, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, Vector2 as Vector2$1, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from 'three';
  2. import { GLTFLoader as GLTFLoader$1 } from 'three/examples/jsm/loaders/GLTFLoader.js';
  3. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
  4. import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
  5. function _mergeNamespaces(n, m) {
  6. m.forEach(function (e) {
  7. e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
  8. if (k !== 'default' && !(k in n)) {
  9. var d = Object.getOwnPropertyDescriptor(e, k);
  10. Object.defineProperty(n, k, d.get ? d : {
  11. enumerable: true,
  12. get: function () { return e[k]; }
  13. });
  14. }
  15. });
  16. });
  17. return Object.freeze(n);
  18. }
  19. /******************************************************************************
  20. Copyright (c) Microsoft Corporation.
  21. Permission to use, copy, modify, and/or distribute this software for any
  22. purpose with or without fee is hereby granted.
  23. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  24. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  25. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  26. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  27. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  28. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29. PERFORMANCE OF THIS SOFTWARE.
  30. ***************************************************************************** */
  31. function __awaiter(thisArg, _arguments, P, generator) {
  32. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  33. return new (P || (P = Promise))(function (resolve, reject) {
  34. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  35. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  36. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  37. step((generator = generator.apply(thisArg, _arguments || [])).next());
  38. });
  39. }
  40. function assert$7(condition, message) {
  41. if (!condition) {
  42. throw new Error(message || 'loader assertion failed.');
  43. }
  44. }
  45. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  46. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  47. matches$1 && parseFloat(matches$1[1]) || 0;
  48. const VERSION$8 = "3.2.12" ;
  49. function assert$6(condition, message) {
  50. if (!condition) {
  51. throw new Error(message || 'loaders.gl assertion failed.');
  52. }
  53. }
  54. const globals$1 = {
  55. self: typeof self !== 'undefined' && self,
  56. window: typeof window !== 'undefined' && window,
  57. global: typeof global !== 'undefined' && global,
  58. document: typeof document !== 'undefined' && document
  59. };
  60. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  61. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  62. const isWorker = typeof importScripts === 'function';
  63. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  64. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  65. matches && parseFloat(matches[1]) || 0;
  66. function _typeof(obj) {
  67. "@babel/helpers - typeof";
  68. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  69. return typeof obj;
  70. } : function (obj) {
  71. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  72. }, _typeof(obj);
  73. }
  74. function _toPrimitive(input, hint) {
  75. if (_typeof(input) !== "object" || input === null) return input;
  76. var prim = input[Symbol.toPrimitive];
  77. if (prim !== undefined) {
  78. var res = prim.call(input, hint || "default");
  79. if (_typeof(res) !== "object") return res;
  80. throw new TypeError("@@toPrimitive must return a primitive value.");
  81. }
  82. return (hint === "string" ? String : Number)(input);
  83. }
  84. function _toPropertyKey(arg) {
  85. var key = _toPrimitive(arg, "string");
  86. return _typeof(key) === "symbol" ? key : String(key);
  87. }
  88. function _defineProperty(obj, key, value) {
  89. key = _toPropertyKey(key);
  90. if (key in obj) {
  91. Object.defineProperty(obj, key, {
  92. value: value,
  93. enumerable: true,
  94. configurable: true,
  95. writable: true
  96. });
  97. } else {
  98. obj[key] = value;
  99. }
  100. return obj;
  101. }
  102. class WorkerJob {
  103. constructor(jobName, workerThread) {
  104. _defineProperty(this, "name", void 0);
  105. _defineProperty(this, "workerThread", void 0);
  106. _defineProperty(this, "isRunning", true);
  107. _defineProperty(this, "result", void 0);
  108. _defineProperty(this, "_resolve", () => {});
  109. _defineProperty(this, "_reject", () => {});
  110. this.name = jobName;
  111. this.workerThread = workerThread;
  112. this.result = new Promise((resolve, reject) => {
  113. this._resolve = resolve;
  114. this._reject = reject;
  115. });
  116. }
  117. postMessage(type, payload) {
  118. this.workerThread.postMessage({
  119. source: 'loaders.gl',
  120. type,
  121. payload
  122. });
  123. }
  124. done(value) {
  125. assert$6(this.isRunning);
  126. this.isRunning = false;
  127. this._resolve(value);
  128. }
  129. error(error) {
  130. assert$6(this.isRunning);
  131. this.isRunning = false;
  132. this._reject(error);
  133. }
  134. }
  135. class Worker$1 {}
  136. const workerURLCache = new Map();
  137. function getLoadableWorkerURL(props) {
  138. assert$6(props.source && !props.url || !props.source && props.url);
  139. let workerURL = workerURLCache.get(props.source || props.url);
  140. if (!workerURL) {
  141. if (props.url) {
  142. workerURL = getLoadableWorkerURLFromURL(props.url);
  143. workerURLCache.set(props.url, workerURL);
  144. }
  145. if (props.source) {
  146. workerURL = getLoadableWorkerURLFromSource(props.source);
  147. workerURLCache.set(props.source, workerURL);
  148. }
  149. }
  150. assert$6(workerURL);
  151. return workerURL;
  152. }
  153. function getLoadableWorkerURLFromURL(url) {
  154. if (!url.startsWith('http')) {
  155. return url;
  156. }
  157. const workerSource = buildScriptSource(url);
  158. return getLoadableWorkerURLFromSource(workerSource);
  159. }
  160. function getLoadableWorkerURLFromSource(workerSource) {
  161. const blob = new Blob([workerSource], {
  162. type: 'application/javascript'
  163. });
  164. return URL.createObjectURL(blob);
  165. }
  166. function buildScriptSource(workerUrl) {
  167. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  168. }
  169. function getTransferList(object, recursive = true, transfers) {
  170. const transfersSet = transfers || new Set();
  171. if (!object) ; else if (isTransferable(object)) {
  172. transfersSet.add(object);
  173. } else if (isTransferable(object.buffer)) {
  174. transfersSet.add(object.buffer);
  175. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  176. for (const key in object) {
  177. getTransferList(object[key], recursive, transfersSet);
  178. }
  179. }
  180. return transfers === undefined ? Array.from(transfersSet) : [];
  181. }
  182. function isTransferable(object) {
  183. if (!object) {
  184. return false;
  185. }
  186. if (object instanceof ArrayBuffer) {
  187. return true;
  188. }
  189. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  190. return true;
  191. }
  192. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  193. return true;
  194. }
  195. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  196. return true;
  197. }
  198. return false;
  199. }
  200. const NOOP = () => {};
  201. class WorkerThread {
  202. static isSupported() {
  203. return typeof Worker !== 'undefined' && isBrowser$1 || typeof Worker$1 !== 'undefined' && !isBrowser$1;
  204. }
  205. constructor(props) {
  206. _defineProperty(this, "name", void 0);
  207. _defineProperty(this, "source", void 0);
  208. _defineProperty(this, "url", void 0);
  209. _defineProperty(this, "terminated", false);
  210. _defineProperty(this, "worker", void 0);
  211. _defineProperty(this, "onMessage", void 0);
  212. _defineProperty(this, "onError", void 0);
  213. _defineProperty(this, "_loadableURL", '');
  214. const {
  215. name,
  216. source,
  217. url
  218. } = props;
  219. assert$6(source || url);
  220. this.name = name;
  221. this.source = source;
  222. this.url = url;
  223. this.onMessage = NOOP;
  224. this.onError = error => console.log(error);
  225. this.worker = isBrowser$1 ? this._createBrowserWorker() : this._createNodeWorker();
  226. }
  227. destroy() {
  228. this.onMessage = NOOP;
  229. this.onError = NOOP;
  230. this.worker.terminate();
  231. this.terminated = true;
  232. }
  233. get isRunning() {
  234. return Boolean(this.onMessage);
  235. }
  236. postMessage(data, transferList) {
  237. transferList = transferList || getTransferList(data);
  238. this.worker.postMessage(data, transferList);
  239. }
  240. _getErrorFromErrorEvent(event) {
  241. let message = 'Failed to load ';
  242. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  243. if (event.message) {
  244. message += "".concat(event.message, " in ");
  245. }
  246. if (event.lineno) {
  247. message += ":".concat(event.lineno, ":").concat(event.colno);
  248. }
  249. return new Error(message);
  250. }
  251. _createBrowserWorker() {
  252. this._loadableURL = getLoadableWorkerURL({
  253. source: this.source,
  254. url: this.url
  255. });
  256. const worker = new Worker(this._loadableURL, {
  257. name: this.name
  258. });
  259. worker.onmessage = event => {
  260. if (!event.data) {
  261. this.onError(new Error('No data received'));
  262. } else {
  263. this.onMessage(event.data);
  264. }
  265. };
  266. worker.onerror = error => {
  267. this.onError(this._getErrorFromErrorEvent(error));
  268. this.terminated = true;
  269. };
  270. worker.onmessageerror = event => console.error(event);
  271. return worker;
  272. }
  273. _createNodeWorker() {
  274. let worker;
  275. if (this.url) {
  276. const absolute = this.url.includes(':/') || this.url.startsWith('/');
  277. const url = absolute ? this.url : "./".concat(this.url);
  278. worker = new Worker$1(url, {
  279. eval: false
  280. });
  281. } else if (this.source) {
  282. worker = new Worker$1(this.source, {
  283. eval: true
  284. });
  285. } else {
  286. throw new Error('no worker');
  287. }
  288. worker.on('message', data => {
  289. this.onMessage(data);
  290. });
  291. worker.on('error', error => {
  292. this.onError(error);
  293. });
  294. worker.on('exit', code => {});
  295. return worker;
  296. }
  297. }
  298. class WorkerPool {
  299. static isSupported() {
  300. return WorkerThread.isSupported();
  301. }
  302. constructor(props) {
  303. _defineProperty(this, "name", 'unnamed');
  304. _defineProperty(this, "source", void 0);
  305. _defineProperty(this, "url", void 0);
  306. _defineProperty(this, "maxConcurrency", 1);
  307. _defineProperty(this, "maxMobileConcurrency", 1);
  308. _defineProperty(this, "onDebug", () => {});
  309. _defineProperty(this, "reuseWorkers", true);
  310. _defineProperty(this, "props", {});
  311. _defineProperty(this, "jobQueue", []);
  312. _defineProperty(this, "idleQueue", []);
  313. _defineProperty(this, "count", 0);
  314. _defineProperty(this, "isDestroyed", false);
  315. this.source = props.source;
  316. this.url = props.url;
  317. this.setProps(props);
  318. }
  319. destroy() {
  320. this.idleQueue.forEach(worker => worker.destroy());
  321. this.isDestroyed = true;
  322. }
  323. setProps(props) {
  324. this.props = { ...this.props,
  325. ...props
  326. };
  327. if (props.name !== undefined) {
  328. this.name = props.name;
  329. }
  330. if (props.maxConcurrency !== undefined) {
  331. this.maxConcurrency = props.maxConcurrency;
  332. }
  333. if (props.maxMobileConcurrency !== undefined) {
  334. this.maxMobileConcurrency = props.maxMobileConcurrency;
  335. }
  336. if (props.reuseWorkers !== undefined) {
  337. this.reuseWorkers = props.reuseWorkers;
  338. }
  339. if (props.onDebug !== undefined) {
  340. this.onDebug = props.onDebug;
  341. }
  342. }
  343. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  344. const startPromise = new Promise(onStart => {
  345. this.jobQueue.push({
  346. name,
  347. onMessage,
  348. onError,
  349. onStart
  350. });
  351. return this;
  352. });
  353. this._startQueuedJob();
  354. return await startPromise;
  355. }
  356. async _startQueuedJob() {
  357. if (!this.jobQueue.length) {
  358. return;
  359. }
  360. const workerThread = this._getAvailableWorker();
  361. if (!workerThread) {
  362. return;
  363. }
  364. const queuedJob = this.jobQueue.shift();
  365. if (queuedJob) {
  366. this.onDebug({
  367. message: 'Starting job',
  368. name: queuedJob.name,
  369. workerThread,
  370. backlog: this.jobQueue.length
  371. });
  372. const job = new WorkerJob(queuedJob.name, workerThread);
  373. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  374. workerThread.onError = error => queuedJob.onError(job, error);
  375. queuedJob.onStart(job);
  376. try {
  377. await job.result;
  378. } finally {
  379. this.returnWorkerToQueue(workerThread);
  380. }
  381. }
  382. }
  383. returnWorkerToQueue(worker) {
  384. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  385. if (shouldDestroyWorker) {
  386. worker.destroy();
  387. this.count--;
  388. } else {
  389. this.idleQueue.push(worker);
  390. }
  391. if (!this.isDestroyed) {
  392. this._startQueuedJob();
  393. }
  394. }
  395. _getAvailableWorker() {
  396. if (this.idleQueue.length > 0) {
  397. return this.idleQueue.shift() || null;
  398. }
  399. if (this.count < this._getMaxConcurrency()) {
  400. this.count++;
  401. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  402. return new WorkerThread({
  403. name,
  404. source: this.source,
  405. url: this.url
  406. });
  407. }
  408. return null;
  409. }
  410. _getMaxConcurrency() {
  411. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  412. }
  413. }
  414. const DEFAULT_PROPS$3 = {
  415. maxConcurrency: 3,
  416. maxMobileConcurrency: 1,
  417. reuseWorkers: true,
  418. onDebug: () => {}
  419. };
  420. class WorkerFarm {
  421. static isSupported() {
  422. return WorkerThread.isSupported();
  423. }
  424. static getWorkerFarm(props = {}) {
  425. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  426. WorkerFarm._workerFarm.setProps(props);
  427. return WorkerFarm._workerFarm;
  428. }
  429. constructor(props) {
  430. _defineProperty(this, "props", void 0);
  431. _defineProperty(this, "workerPools", new Map());
  432. this.props = { ...DEFAULT_PROPS$3
  433. };
  434. this.setProps(props);
  435. this.workerPools = new Map();
  436. }
  437. destroy() {
  438. for (const workerPool of this.workerPools.values()) {
  439. workerPool.destroy();
  440. }
  441. this.workerPools = new Map();
  442. }
  443. setProps(props) {
  444. this.props = { ...this.props,
  445. ...props
  446. };
  447. for (const workerPool of this.workerPools.values()) {
  448. workerPool.setProps(this._getWorkerPoolProps());
  449. }
  450. }
  451. getWorkerPool(options) {
  452. const {
  453. name,
  454. source,
  455. url
  456. } = options;
  457. let workerPool = this.workerPools.get(name);
  458. if (!workerPool) {
  459. workerPool = new WorkerPool({
  460. name,
  461. source,
  462. url
  463. });
  464. workerPool.setProps(this._getWorkerPoolProps());
  465. this.workerPools.set(name, workerPool);
  466. }
  467. return workerPool;
  468. }
  469. _getWorkerPoolProps() {
  470. return {
  471. maxConcurrency: this.props.maxConcurrency,
  472. maxMobileConcurrency: this.props.maxMobileConcurrency,
  473. reuseWorkers: this.props.reuseWorkers,
  474. onDebug: this.props.onDebug
  475. };
  476. }
  477. }
  478. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  479. const NPM_TAG = 'latest';
  480. function getWorkerURL(worker, options = {}) {
  481. const workerOptions = options[worker.id] || {};
  482. const workerFile = "".concat(worker.id, "-worker.js");
  483. let url = workerOptions.workerUrl;
  484. if (!url && worker.id === 'compression') {
  485. url = options.workerUrl;
  486. }
  487. if (options._workerType === 'test') {
  488. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  489. }
  490. if (!url) {
  491. let version = worker.version;
  492. if (version === 'latest') {
  493. version = NPM_TAG;
  494. }
  495. const versionTag = version ? "@".concat(version) : '';
  496. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  497. }
  498. assert$6(url);
  499. return url;
  500. }
  501. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  502. assert$6(worker, 'no worker provided');
  503. const workerVersion = worker.version;
  504. if (!coreVersion || !workerVersion) {
  505. return false;
  506. }
  507. return true;
  508. }
  509. var ChildProcessProxy = {};
  510. var node = /*#__PURE__*/_mergeNamespaces({
  511. __proto__: null,
  512. 'default': ChildProcessProxy
  513. }, [ChildProcessProxy]);
  514. const VERSION$7 = "3.2.12" ;
  515. const loadLibraryPromises = {};
  516. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  517. if (moduleName) {
  518. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  519. }
  520. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  521. return await loadLibraryPromises[libraryUrl];
  522. }
  523. function getLibraryUrl(library, moduleName, options) {
  524. if (library.startsWith('http')) {
  525. return library;
  526. }
  527. const modules = options.modules || {};
  528. if (modules[library]) {
  529. return modules[library];
  530. }
  531. if (!isBrowser$1) {
  532. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  533. }
  534. if (options.CDN) {
  535. assert$6(options.CDN.startsWith('http'));
  536. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  537. }
  538. if (isWorker) {
  539. return "../src/libs/".concat(library);
  540. }
  541. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  542. }
  543. async function loadLibraryFromFile(libraryUrl) {
  544. if (libraryUrl.endsWith('wasm')) {
  545. const response = await fetch(libraryUrl);
  546. return await response.arrayBuffer();
  547. }
  548. if (!isBrowser$1) {
  549. try {
  550. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  551. } catch {
  552. return null;
  553. }
  554. }
  555. if (isWorker) {
  556. return importScripts(libraryUrl);
  557. }
  558. const response = await fetch(libraryUrl);
  559. const scriptSource = await response.text();
  560. return loadLibraryFromString(scriptSource, libraryUrl);
  561. }
  562. function loadLibraryFromString(scriptSource, id) {
  563. if (!isBrowser$1) {
  564. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  565. }
  566. if (isWorker) {
  567. eval.call(global_, scriptSource);
  568. return null;
  569. }
  570. const script = document.createElement('script');
  571. script.id = id;
  572. try {
  573. script.appendChild(document.createTextNode(scriptSource));
  574. } catch (e) {
  575. script.text = scriptSource;
  576. }
  577. document.body.appendChild(script);
  578. return null;
  579. }
  580. function canParseWithWorker(loader, options) {
  581. if (!WorkerFarm.isSupported()) {
  582. return false;
  583. }
  584. if (!isBrowser$1 && !(options !== null && options !== void 0 && options._nodeWorkers)) {
  585. return false;
  586. }
  587. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  588. }
  589. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  590. const name = loader.id;
  591. const url = getWorkerURL(loader, options);
  592. const workerFarm = WorkerFarm.getWorkerFarm(options);
  593. const workerPool = workerFarm.getWorkerPool({
  594. name,
  595. url
  596. });
  597. options = JSON.parse(JSON.stringify(options));
  598. context = JSON.parse(JSON.stringify(context || {}));
  599. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  600. job.postMessage('process', {
  601. input: data,
  602. options,
  603. context
  604. });
  605. const result = await job.result;
  606. return await result.result;
  607. }
  608. async function onMessage(parseOnMainThread, job, type, payload) {
  609. switch (type) {
  610. case 'done':
  611. job.done(payload);
  612. break;
  613. case 'error':
  614. job.error(new Error(payload.error));
  615. break;
  616. case 'process':
  617. const {
  618. id,
  619. input,
  620. options
  621. } = payload;
  622. try {
  623. const result = await parseOnMainThread(input, options);
  624. job.postMessage('done', {
  625. id,
  626. result
  627. });
  628. } catch (error) {
  629. const message = error instanceof Error ? error.message : 'unknown error';
  630. job.postMessage('error', {
  631. id,
  632. error: message
  633. });
  634. }
  635. break;
  636. default:
  637. console.warn("parse-with-worker unknown message ".concat(type));
  638. }
  639. }
  640. function getFirstCharacters$1(data, length = 5) {
  641. if (typeof data === 'string') {
  642. return data.slice(0, length);
  643. } else if (ArrayBuffer.isView(data)) {
  644. return getMagicString$3(data.buffer, data.byteOffset, length);
  645. } else if (data instanceof ArrayBuffer) {
  646. const byteOffset = 0;
  647. return getMagicString$3(data, byteOffset, length);
  648. }
  649. return '';
  650. }
  651. function getMagicString$3(arrayBuffer, byteOffset, length) {
  652. if (arrayBuffer.byteLength <= byteOffset + length) {
  653. return '';
  654. }
  655. const dataView = new DataView(arrayBuffer);
  656. let magic = '';
  657. for (let i = 0; i < length; i++) {
  658. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  659. }
  660. return magic;
  661. }
  662. function parseJSON(string) {
  663. try {
  664. return JSON.parse(string);
  665. } catch (_) {
  666. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  667. }
  668. }
  669. function isBuffer$1(value) {
  670. return value && typeof value === 'object' && value.isBuffer;
  671. }
  672. function bufferToArrayBuffer(buffer) {
  673. if (isBuffer$1(buffer)) {
  674. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  675. return typedArray.slice().buffer;
  676. }
  677. return buffer;
  678. }
  679. function toArrayBuffer(data) {
  680. if (isBuffer$1(data)) {
  681. return bufferToArrayBuffer(data);
  682. }
  683. if (data instanceof ArrayBuffer) {
  684. return data;
  685. }
  686. if (ArrayBuffer.isView(data)) {
  687. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  688. return data.buffer;
  689. }
  690. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  691. }
  692. if (typeof data === 'string') {
  693. const text = data;
  694. const uint8Array = new TextEncoder().encode(text);
  695. return uint8Array.buffer;
  696. }
  697. if (data && typeof data === 'object' && data._toArrayBuffer) {
  698. return data._toArrayBuffer();
  699. }
  700. throw new Error('toArrayBuffer');
  701. }
  702. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  703. byteLength = byteLength || arrayBuffer1.byteLength;
  704. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  705. return false;
  706. }
  707. const array1 = new Uint8Array(arrayBuffer1);
  708. const array2 = new Uint8Array(arrayBuffer2);
  709. for (let i = 0; i < array1.length; ++i) {
  710. if (array1[i] !== array2[i]) {
  711. return false;
  712. }
  713. }
  714. return true;
  715. }
  716. function concatenateArrayBuffers(...sources) {
  717. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  718. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  719. const result = new Uint8Array(byteLength);
  720. let offset = 0;
  721. for (const sourceArray of sourceArrays) {
  722. result.set(sourceArray, offset);
  723. offset += sourceArray.byteLength;
  724. }
  725. return result.buffer;
  726. }
  727. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  728. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  729. const arrayCopy = new Uint8Array(subArray);
  730. return arrayCopy.buffer;
  731. }
  732. function padToNBytes(byteLength, padding) {
  733. assert$7(byteLength >= 0);
  734. assert$7(padding > 0);
  735. return byteLength + (padding - 1) & ~(padding - 1);
  736. }
  737. function copyToArray(source, target, targetOffset) {
  738. let sourceArray;
  739. if (source instanceof ArrayBuffer) {
  740. sourceArray = new Uint8Array(source);
  741. } else {
  742. const srcByteOffset = source.byteOffset;
  743. const srcByteLength = source.byteLength;
  744. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  745. }
  746. target.set(sourceArray, targetOffset);
  747. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  748. }
  749. async function concatenateArrayBuffersAsync(asyncIterator) {
  750. const arrayBuffers = [];
  751. for await (const chunk of asyncIterator) {
  752. arrayBuffers.push(chunk);
  753. }
  754. return concatenateArrayBuffers(...arrayBuffers);
  755. }
  756. function getHiResTimestamp$1() {
  757. let timestamp;
  758. if (typeof window !== 'undefined' && window.performance) {
  759. timestamp = window.performance.now();
  760. } else if (typeof process !== 'undefined' && process.hrtime) {
  761. const timeParts = process.hrtime();
  762. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  763. } else {
  764. timestamp = Date.now();
  765. }
  766. return timestamp;
  767. }
  768. class Stat {
  769. constructor(name, type) {
  770. _defineProperty(this, "name", void 0);
  771. _defineProperty(this, "type", void 0);
  772. _defineProperty(this, "sampleSize", 1);
  773. _defineProperty(this, "time", void 0);
  774. _defineProperty(this, "count", void 0);
  775. _defineProperty(this, "samples", void 0);
  776. _defineProperty(this, "lastTiming", void 0);
  777. _defineProperty(this, "lastSampleTime", void 0);
  778. _defineProperty(this, "lastSampleCount", void 0);
  779. _defineProperty(this, "_count", 0);
  780. _defineProperty(this, "_time", 0);
  781. _defineProperty(this, "_samples", 0);
  782. _defineProperty(this, "_startTime", 0);
  783. _defineProperty(this, "_timerPending", false);
  784. this.name = name;
  785. this.type = type;
  786. this.reset();
  787. }
  788. setSampleSize(samples) {
  789. this.sampleSize = samples;
  790. return this;
  791. }
  792. incrementCount() {
  793. this.addCount(1);
  794. return this;
  795. }
  796. decrementCount() {
  797. this.subtractCount(1);
  798. return this;
  799. }
  800. addCount(value) {
  801. this._count += value;
  802. this._samples++;
  803. this._checkSampling();
  804. return this;
  805. }
  806. subtractCount(value) {
  807. this._count -= value;
  808. this._samples++;
  809. this._checkSampling();
  810. return this;
  811. }
  812. addTime(time) {
  813. this._time += time;
  814. this.lastTiming = time;
  815. this._samples++;
  816. this._checkSampling();
  817. return this;
  818. }
  819. timeStart() {
  820. this._startTime = getHiResTimestamp$1();
  821. this._timerPending = true;
  822. return this;
  823. }
  824. timeEnd() {
  825. if (!this._timerPending) {
  826. return this;
  827. }
  828. this.addTime(getHiResTimestamp$1() - this._startTime);
  829. this._timerPending = false;
  830. this._checkSampling();
  831. return this;
  832. }
  833. getSampleAverageCount() {
  834. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  835. }
  836. getSampleAverageTime() {
  837. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  838. }
  839. getSampleHz() {
  840. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  841. }
  842. getAverageCount() {
  843. return this.samples > 0 ? this.count / this.samples : 0;
  844. }
  845. getAverageTime() {
  846. return this.samples > 0 ? this.time / this.samples : 0;
  847. }
  848. getHz() {
  849. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  850. }
  851. reset() {
  852. this.time = 0;
  853. this.count = 0;
  854. this.samples = 0;
  855. this.lastTiming = 0;
  856. this.lastSampleTime = 0;
  857. this.lastSampleCount = 0;
  858. this._count = 0;
  859. this._time = 0;
  860. this._samples = 0;
  861. this._startTime = 0;
  862. this._timerPending = false;
  863. return this;
  864. }
  865. _checkSampling() {
  866. if (this._samples === this.sampleSize) {
  867. this.lastSampleTime = this._time;
  868. this.lastSampleCount = this._count;
  869. this.count += this._count;
  870. this.time += this._time;
  871. this.samples += this._samples;
  872. this._time = 0;
  873. this._count = 0;
  874. this._samples = 0;
  875. }
  876. }
  877. }
  878. class Stats {
  879. constructor(options) {
  880. _defineProperty(this, "id", void 0);
  881. _defineProperty(this, "stats", {});
  882. this.id = options.id;
  883. this.stats = {};
  884. this._initializeStats(options.stats);
  885. Object.seal(this);
  886. }
  887. get(name) {
  888. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  889. return this._getOrCreate({
  890. name,
  891. type
  892. });
  893. }
  894. get size() {
  895. return Object.keys(this.stats).length;
  896. }
  897. reset() {
  898. for (const key in this.stats) {
  899. this.stats[key].reset();
  900. }
  901. return this;
  902. }
  903. forEach(fn) {
  904. for (const key in this.stats) {
  905. fn(this.stats[key]);
  906. }
  907. }
  908. getTable() {
  909. const table = {};
  910. this.forEach(stat => {
  911. table[stat.name] = {
  912. time: stat.time || 0,
  913. count: stat.count || 0,
  914. average: stat.getAverageTime() || 0,
  915. hz: stat.getHz() || 0
  916. };
  917. });
  918. return table;
  919. }
  920. _initializeStats() {
  921. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  922. stats.forEach(stat => this._getOrCreate(stat));
  923. }
  924. _getOrCreate(stat) {
  925. if (!stat || !stat.name) {
  926. return null;
  927. }
  928. const {
  929. name,
  930. type
  931. } = stat;
  932. if (!this.stats[name]) {
  933. if (stat instanceof Stat) {
  934. this.stats[name] = stat;
  935. } else {
  936. this.stats[name] = new Stat(name, type);
  937. }
  938. }
  939. return this.stats[name];
  940. }
  941. }
  942. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  943. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  944. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  945. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  946. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  947. const DEFAULT_PROPS$2 = {
  948. id: 'request-scheduler',
  949. throttleRequests: true,
  950. maxRequests: 6
  951. };
  952. class RequestScheduler {
  953. constructor(props = {}) {
  954. _defineProperty(this, "props", void 0);
  955. _defineProperty(this, "stats", void 0);
  956. _defineProperty(this, "activeRequestCount", 0);
  957. _defineProperty(this, "requestQueue", []);
  958. _defineProperty(this, "requestMap", new Map());
  959. _defineProperty(this, "deferredUpdate", null);
  960. this.props = { ...DEFAULT_PROPS$2,
  961. ...props
  962. };
  963. this.stats = new Stats({
  964. id: this.props.id
  965. });
  966. this.stats.get(STAT_QUEUED_REQUESTS);
  967. this.stats.get(STAT_ACTIVE_REQUESTS);
  968. this.stats.get(STAT_CANCELLED_REQUESTS);
  969. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  970. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  971. }
  972. scheduleRequest(handle, getPriority = () => 0) {
  973. if (!this.props.throttleRequests) {
  974. return Promise.resolve({
  975. done: () => {}
  976. });
  977. }
  978. if (this.requestMap.has(handle)) {
  979. return this.requestMap.get(handle);
  980. }
  981. const request = {
  982. handle,
  983. priority: 0,
  984. getPriority
  985. };
  986. const promise = new Promise(resolve => {
  987. request.resolve = resolve;
  988. return request;
  989. });
  990. this.requestQueue.push(request);
  991. this.requestMap.set(handle, promise);
  992. this._issueNewRequests();
  993. return promise;
  994. }
  995. _issueRequest(request) {
  996. const {
  997. handle,
  998. resolve
  999. } = request;
  1000. let isDone = false;
  1001. const done = () => {
  1002. if (!isDone) {
  1003. isDone = true;
  1004. this.requestMap.delete(handle);
  1005. this.activeRequestCount--;
  1006. this._issueNewRequests();
  1007. }
  1008. };
  1009. this.activeRequestCount++;
  1010. return resolve ? resolve({
  1011. done
  1012. }) : Promise.resolve({
  1013. done
  1014. });
  1015. }
  1016. _issueNewRequests() {
  1017. if (!this.deferredUpdate) {
  1018. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  1019. }
  1020. }
  1021. _issueNewRequestsAsync() {
  1022. this.deferredUpdate = null;
  1023. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  1024. if (freeSlots === 0) {
  1025. return;
  1026. }
  1027. this._updateAllRequests();
  1028. for (let i = 0; i < freeSlots; ++i) {
  1029. const request = this.requestQueue.shift();
  1030. if (request) {
  1031. this._issueRequest(request);
  1032. }
  1033. }
  1034. }
  1035. _updateAllRequests() {
  1036. const requestQueue = this.requestQueue;
  1037. for (let i = 0; i < requestQueue.length; ++i) {
  1038. const request = requestQueue[i];
  1039. if (!this._updateRequest(request)) {
  1040. requestQueue.splice(i, 1);
  1041. this.requestMap.delete(request.handle);
  1042. i--;
  1043. }
  1044. }
  1045. requestQueue.sort((a, b) => a.priority - b.priority);
  1046. }
  1047. _updateRequest(request) {
  1048. request.priority = request.getPriority(request.handle);
  1049. if (request.priority < 0) {
  1050. request.resolve(null);
  1051. return false;
  1052. }
  1053. return true;
  1054. }
  1055. }
  1056. let pathPrefix = '';
  1057. const fileAliases = {};
  1058. function resolvePath(filename) {
  1059. for (const alias in fileAliases) {
  1060. if (filename.startsWith(alias)) {
  1061. const replacement = fileAliases[alias];
  1062. filename = filename.replace(alias, replacement);
  1063. }
  1064. }
  1065. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1066. filename = "".concat(pathPrefix).concat(filename);
  1067. }
  1068. return filename;
  1069. }
  1070. function filename(url) {
  1071. const slashIndex = url && url.lastIndexOf('/');
  1072. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1073. }
  1074. function dirname(url) {
  1075. const slashIndex = url && url.lastIndexOf('/');
  1076. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1077. }
  1078. const isBoolean = x => typeof x === 'boolean';
  1079. const isFunction = x => typeof x === 'function';
  1080. const isObject = x => x !== null && typeof x === 'object';
  1081. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1082. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1083. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1084. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1085. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1086. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1087. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1088. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1089. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1090. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1091. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1092. function parseMIMEType(mimeString) {
  1093. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1094. if (matches) {
  1095. return matches[1];
  1096. }
  1097. return mimeString;
  1098. }
  1099. function parseMIMETypeFromURL(url) {
  1100. const matches = DATA_URL_PATTERN.exec(url);
  1101. if (matches) {
  1102. return matches[1];
  1103. }
  1104. return '';
  1105. }
  1106. const QUERY_STRING_PATTERN = /\?.*/;
  1107. function getResourceUrlAndType(resource) {
  1108. if (isResponse(resource)) {
  1109. const url = stripQueryString(resource.url || '');
  1110. const contentTypeHeader = resource.headers.get('content-type') || '';
  1111. return {
  1112. url,
  1113. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1114. };
  1115. }
  1116. if (isBlob(resource)) {
  1117. return {
  1118. url: stripQueryString(resource.name || ''),
  1119. type: resource.type || ''
  1120. };
  1121. }
  1122. if (typeof resource === 'string') {
  1123. return {
  1124. url: stripQueryString(resource),
  1125. type: parseMIMETypeFromURL(resource)
  1126. };
  1127. }
  1128. return {
  1129. url: '',
  1130. type: ''
  1131. };
  1132. }
  1133. function getResourceContentLength(resource) {
  1134. if (isResponse(resource)) {
  1135. return resource.headers['content-length'] || -1;
  1136. }
  1137. if (isBlob(resource)) {
  1138. return resource.size;
  1139. }
  1140. if (typeof resource === 'string') {
  1141. return resource.length;
  1142. }
  1143. if (resource instanceof ArrayBuffer) {
  1144. return resource.byteLength;
  1145. }
  1146. if (ArrayBuffer.isView(resource)) {
  1147. return resource.byteLength;
  1148. }
  1149. return -1;
  1150. }
  1151. function stripQueryString(url) {
  1152. return url.replace(QUERY_STRING_PATTERN, '');
  1153. }
  1154. async function makeResponse(resource) {
  1155. if (isResponse(resource)) {
  1156. return resource;
  1157. }
  1158. const headers = {};
  1159. const contentLength = getResourceContentLength(resource);
  1160. if (contentLength >= 0) {
  1161. headers['content-length'] = String(contentLength);
  1162. }
  1163. const {
  1164. url,
  1165. type
  1166. } = getResourceUrlAndType(resource);
  1167. if (type) {
  1168. headers['content-type'] = type;
  1169. }
  1170. const initialDataUrl = await getInitialDataUrl(resource);
  1171. if (initialDataUrl) {
  1172. headers['x-first-bytes'] = initialDataUrl;
  1173. }
  1174. if (typeof resource === 'string') {
  1175. resource = new TextEncoder().encode(resource);
  1176. }
  1177. const response = new Response(resource, {
  1178. headers
  1179. });
  1180. Object.defineProperty(response, 'url', {
  1181. value: url
  1182. });
  1183. return response;
  1184. }
  1185. async function checkResponse(response) {
  1186. if (!response.ok) {
  1187. const message = await getResponseError(response);
  1188. throw new Error(message);
  1189. }
  1190. }
  1191. async function getResponseError(response) {
  1192. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1193. try {
  1194. const contentType = response.headers.get('Content-Type');
  1195. let text = response.statusText;
  1196. if (contentType.includes('application/json')) {
  1197. text += " ".concat(await response.text());
  1198. }
  1199. message += text;
  1200. message = message.length > 60 ? "".concat(message.slice(0, 60), "...") : message;
  1201. } catch (error) {}
  1202. return message;
  1203. }
  1204. async function getInitialDataUrl(resource) {
  1205. const INITIAL_DATA_LENGTH = 5;
  1206. if (typeof resource === 'string') {
  1207. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1208. }
  1209. if (resource instanceof Blob) {
  1210. const blobSlice = resource.slice(0, 5);
  1211. return await new Promise(resolve => {
  1212. const reader = new FileReader();
  1213. reader.onload = event => {
  1214. var _event$target;
  1215. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1216. };
  1217. reader.readAsDataURL(blobSlice);
  1218. });
  1219. }
  1220. if (resource instanceof ArrayBuffer) {
  1221. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1222. const base64 = arrayBufferToBase64(slice);
  1223. return "data:base64,".concat(base64);
  1224. }
  1225. return null;
  1226. }
  1227. function arrayBufferToBase64(buffer) {
  1228. let binary = '';
  1229. const bytes = new Uint8Array(buffer);
  1230. for (let i = 0; i < bytes.byteLength; i++) {
  1231. binary += String.fromCharCode(bytes[i]);
  1232. }
  1233. return btoa(binary);
  1234. }
  1235. async function fetchFile(url, options) {
  1236. if (typeof url === 'string') {
  1237. url = resolvePath(url);
  1238. let fetchOptions = options;
  1239. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1240. fetchOptions = options.fetch;
  1241. }
  1242. return await fetch(url, fetchOptions);
  1243. }
  1244. return await makeResponse(url);
  1245. }
  1246. function isElectron(mockUserAgent) {
  1247. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1248. return true;
  1249. }
  1250. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions['electron'])) {
  1251. return true;
  1252. }
  1253. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1254. const userAgent = mockUserAgent || realUserAgent;
  1255. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1256. return true;
  1257. }
  1258. return false;
  1259. }
  1260. function isBrowser() {
  1261. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1262. return !isNode || isElectron();
  1263. }
  1264. const globals = {
  1265. self: typeof self !== 'undefined' && self,
  1266. window: typeof window !== 'undefined' && window,
  1267. global: typeof global !== 'undefined' && global,
  1268. document: typeof document !== 'undefined' && document,
  1269. process: typeof process === 'object' && process
  1270. };
  1271. const window_ = globals.window || globals.self || globals.global;
  1272. const process_ = globals.process || {};
  1273. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1274. isBrowser();
  1275. function getStorage(type) {
  1276. try {
  1277. const storage = window[type];
  1278. const x = '__storage_test__';
  1279. storage.setItem(x, x);
  1280. storage.removeItem(x);
  1281. return storage;
  1282. } catch (e) {
  1283. return null;
  1284. }
  1285. }
  1286. class LocalStorage {
  1287. constructor(id, defaultConfig) {
  1288. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1289. _defineProperty(this, "storage", void 0);
  1290. _defineProperty(this, "id", void 0);
  1291. _defineProperty(this, "config", void 0);
  1292. this.storage = getStorage(type);
  1293. this.id = id;
  1294. this.config = defaultConfig;
  1295. this._loadConfiguration();
  1296. }
  1297. getConfiguration() {
  1298. return this.config;
  1299. }
  1300. setConfiguration(configuration) {
  1301. Object.assign(this.config, configuration);
  1302. if (this.storage) {
  1303. const serialized = JSON.stringify(this.config);
  1304. this.storage.setItem(this.id, serialized);
  1305. }
  1306. }
  1307. _loadConfiguration() {
  1308. let configuration = {};
  1309. if (this.storage) {
  1310. const serializedConfiguration = this.storage.getItem(this.id);
  1311. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1312. }
  1313. Object.assign(this.config, configuration);
  1314. return this;
  1315. }
  1316. }
  1317. function formatTime(ms) {
  1318. let formatted;
  1319. if (ms < 10) {
  1320. formatted = "".concat(ms.toFixed(2), "ms");
  1321. } else if (ms < 100) {
  1322. formatted = "".concat(ms.toFixed(1), "ms");
  1323. } else if (ms < 1000) {
  1324. formatted = "".concat(ms.toFixed(0), "ms");
  1325. } else {
  1326. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1327. }
  1328. return formatted;
  1329. }
  1330. function leftPad(string) {
  1331. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1332. const padLength = Math.max(length - string.length, 0);
  1333. return "".concat(' '.repeat(padLength)).concat(string);
  1334. }
  1335. function formatImage(image, message, scale) {
  1336. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1337. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1338. if (image.width > maxWidth) {
  1339. scale = Math.min(scale, maxWidth / image.width);
  1340. }
  1341. const width = image.width * scale;
  1342. const height = image.height * scale;
  1343. const style = ['font-size:1px;', "padding:".concat(Math.floor(height / 2), "px ").concat(Math.floor(width / 2), "px;"), "line-height:".concat(height, "px;"), "background:url(".concat(imageUrl, ");"), "background-size:".concat(width, "px ").concat(height, "px;"), 'color:transparent;'].join('');
  1344. return ["".concat(message, " %c+"), style];
  1345. }
  1346. let COLOR;
  1347. (function (COLOR) {
  1348. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1349. COLOR[COLOR["RED"] = 31] = "RED";
  1350. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1351. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1352. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1353. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1354. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1355. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1356. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1357. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1358. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1359. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1360. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1361. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1362. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1363. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1364. })(COLOR || (COLOR = {}));
  1365. function getColor(color) {
  1366. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1367. }
  1368. function addColor(string, color, background) {
  1369. if (!isBrowser && typeof string === 'string') {
  1370. if (color) {
  1371. color = getColor(color);
  1372. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1373. }
  1374. if (background) {
  1375. color = getColor(background);
  1376. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1377. }
  1378. }
  1379. return string;
  1380. }
  1381. function autobind(obj) {
  1382. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1383. const proto = Object.getPrototypeOf(obj);
  1384. const propNames = Object.getOwnPropertyNames(proto);
  1385. for (const key of propNames) {
  1386. if (typeof obj[key] === 'function') {
  1387. if (!predefined.find(name => key === name)) {
  1388. obj[key] = obj[key].bind(obj);
  1389. }
  1390. }
  1391. }
  1392. }
  1393. function assert$5(condition, message) {
  1394. if (!condition) {
  1395. throw new Error(message || 'Assertion failed');
  1396. }
  1397. }
  1398. function getHiResTimestamp() {
  1399. let timestamp;
  1400. if (isBrowser && 'performance' in window_) {
  1401. var _window$performance, _window$performance$n;
  1402. timestamp = window_ === null || window_ === void 0 ? void 0 : (_window$performance = window_.performance) === null || _window$performance === void 0 ? void 0 : (_window$performance$n = _window$performance.now) === null || _window$performance$n === void 0 ? void 0 : _window$performance$n.call(_window$performance);
  1403. } else if ('hrtime' in process_) {
  1404. var _process$hrtime;
  1405. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1406. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1407. } else {
  1408. timestamp = Date.now();
  1409. }
  1410. return timestamp;
  1411. }
  1412. const originalConsole = {
  1413. debug: isBrowser ? console.debug || console.log : console.log,
  1414. log: console.log,
  1415. info: console.info,
  1416. warn: console.warn,
  1417. error: console.error
  1418. };
  1419. const DEFAULT_SETTINGS = {
  1420. enabled: true,
  1421. level: 0
  1422. };
  1423. function noop() {}
  1424. const cache = {};
  1425. const ONCE = {
  1426. once: true
  1427. };
  1428. class Log {
  1429. constructor() {
  1430. let {
  1431. id
  1432. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1433. id: ''
  1434. };
  1435. _defineProperty(this, "id", void 0);
  1436. _defineProperty(this, "VERSION", VERSION$6);
  1437. _defineProperty(this, "_startTs", getHiResTimestamp());
  1438. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1439. _defineProperty(this, "_storage", void 0);
  1440. _defineProperty(this, "userData", {});
  1441. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1442. this.id = id;
  1443. this.userData = {};
  1444. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1445. this.timeStamp("".concat(this.id, " started"));
  1446. autobind(this);
  1447. Object.seal(this);
  1448. }
  1449. set level(newLevel) {
  1450. this.setLevel(newLevel);
  1451. }
  1452. get level() {
  1453. return this.getLevel();
  1454. }
  1455. isEnabled() {
  1456. return this._storage.config.enabled;
  1457. }
  1458. getLevel() {
  1459. return this._storage.config.level;
  1460. }
  1461. getTotal() {
  1462. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1463. }
  1464. getDelta() {
  1465. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1466. }
  1467. set priority(newPriority) {
  1468. this.level = newPriority;
  1469. }
  1470. get priority() {
  1471. return this.level;
  1472. }
  1473. getPriority() {
  1474. return this.level;
  1475. }
  1476. enable() {
  1477. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1478. this._storage.setConfiguration({
  1479. enabled
  1480. });
  1481. return this;
  1482. }
  1483. setLevel(level) {
  1484. this._storage.setConfiguration({
  1485. level
  1486. });
  1487. return this;
  1488. }
  1489. get(setting) {
  1490. return this._storage.config[setting];
  1491. }
  1492. set(setting, value) {
  1493. this._storage.setConfiguration({
  1494. [setting]: value
  1495. });
  1496. }
  1497. settings() {
  1498. if (console.table) {
  1499. console.table(this._storage.config);
  1500. } else {
  1501. console.log(this._storage.config);
  1502. }
  1503. }
  1504. assert(condition, message) {
  1505. assert$5(condition, message);
  1506. }
  1507. warn(message) {
  1508. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1509. }
  1510. error(message) {
  1511. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1512. }
  1513. deprecated(oldUsage, newUsage) {
  1514. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1515. }
  1516. removed(oldUsage, newUsage) {
  1517. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1518. }
  1519. probe(logLevel, message) {
  1520. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1521. time: true,
  1522. once: true
  1523. });
  1524. }
  1525. log(logLevel, message) {
  1526. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1527. }
  1528. info(logLevel, message) {
  1529. return this._getLogFunction(logLevel, message, console.info, arguments);
  1530. }
  1531. once(logLevel, message) {
  1532. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1533. args[_key - 2] = arguments[_key];
  1534. }
  1535. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1536. }
  1537. table(logLevel, table, columns) {
  1538. if (table) {
  1539. return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], {
  1540. tag: getTableHeader(table)
  1541. });
  1542. }
  1543. return noop;
  1544. }
  1545. image(_ref) {
  1546. let {
  1547. logLevel,
  1548. priority,
  1549. image,
  1550. message = '',
  1551. scale = 1
  1552. } = _ref;
  1553. if (!this._shouldLog(logLevel || priority)) {
  1554. return noop;
  1555. }
  1556. return isBrowser ? logImageInBrowser({
  1557. image,
  1558. message,
  1559. scale
  1560. }) : logImageInNode();
  1561. }
  1562. time(logLevel, message) {
  1563. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1564. }
  1565. timeEnd(logLevel, message) {
  1566. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1567. }
  1568. timeStamp(logLevel, message) {
  1569. return this._getLogFunction(logLevel, message, console.timeStamp || noop);
  1570. }
  1571. group(logLevel, message) {
  1572. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1573. collapsed: false
  1574. };
  1575. const options = normalizeArguments({
  1576. logLevel,
  1577. message,
  1578. opts
  1579. });
  1580. const {
  1581. collapsed
  1582. } = opts;
  1583. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1584. return this._getLogFunction(options);
  1585. }
  1586. groupCollapsed(logLevel, message) {
  1587. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1588. return this.group(logLevel, message, Object.assign({}, opts, {
  1589. collapsed: true
  1590. }));
  1591. }
  1592. groupEnd(logLevel) {
  1593. return this._getLogFunction(logLevel, '', console.groupEnd || noop);
  1594. }
  1595. withGroup(logLevel, message, func) {
  1596. this.group(logLevel, message)();
  1597. try {
  1598. func();
  1599. } finally {
  1600. this.groupEnd(logLevel)();
  1601. }
  1602. }
  1603. trace() {
  1604. if (console.trace) {
  1605. console.trace();
  1606. }
  1607. }
  1608. _shouldLog(logLevel) {
  1609. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1610. }
  1611. _getLogFunction(logLevel, message, method, args, opts) {
  1612. if (this._shouldLog(logLevel)) {
  1613. opts = normalizeArguments({
  1614. logLevel,
  1615. message,
  1616. args,
  1617. opts
  1618. });
  1619. method = method || opts.method;
  1620. assert$5(method);
  1621. opts.total = this.getTotal();
  1622. opts.delta = this.getDelta();
  1623. this._deltaTs = getHiResTimestamp();
  1624. const tag = opts.tag || opts.message;
  1625. if (opts.once) {
  1626. if (!cache[tag]) {
  1627. cache[tag] = getHiResTimestamp();
  1628. } else {
  1629. return noop;
  1630. }
  1631. }
  1632. message = decorateMessage(this.id, opts.message, opts);
  1633. return method.bind(console, message, ...opts.args);
  1634. }
  1635. return noop;
  1636. }
  1637. }
  1638. _defineProperty(Log, "VERSION", VERSION$6);
  1639. function normalizeLogLevel(logLevel) {
  1640. if (!logLevel) {
  1641. return 0;
  1642. }
  1643. let resolvedLevel;
  1644. switch (typeof logLevel) {
  1645. case 'number':
  1646. resolvedLevel = logLevel;
  1647. break;
  1648. case 'object':
  1649. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1650. break;
  1651. default:
  1652. return 0;
  1653. }
  1654. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1655. return resolvedLevel;
  1656. }
  1657. function normalizeArguments(opts) {
  1658. const {
  1659. logLevel,
  1660. message
  1661. } = opts;
  1662. opts.logLevel = normalizeLogLevel(logLevel);
  1663. const args = opts.args ? Array.from(opts.args) : [];
  1664. while (args.length && args.shift() !== message) {}
  1665. switch (typeof logLevel) {
  1666. case 'string':
  1667. case 'function':
  1668. if (message !== undefined) {
  1669. args.unshift(message);
  1670. }
  1671. opts.message = logLevel;
  1672. break;
  1673. case 'object':
  1674. Object.assign(opts, logLevel);
  1675. break;
  1676. }
  1677. if (typeof opts.message === 'function') {
  1678. opts.message = opts.message();
  1679. }
  1680. const messageType = typeof opts.message;
  1681. assert$5(messageType === 'string' || messageType === 'object');
  1682. return Object.assign(opts, {
  1683. args
  1684. }, opts.opts);
  1685. }
  1686. function decorateMessage(id, message, opts) {
  1687. if (typeof message === 'string') {
  1688. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1689. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1690. message = addColor(message, opts.color, opts.background);
  1691. }
  1692. return message;
  1693. }
  1694. function logImageInNode(_ref2) {
  1695. console.warn('removed');
  1696. return noop;
  1697. }
  1698. function logImageInBrowser(_ref3) {
  1699. let {
  1700. image,
  1701. message = '',
  1702. scale = 1
  1703. } = _ref3;
  1704. if (typeof image === 'string') {
  1705. const img = new Image();
  1706. img.onload = () => {
  1707. const args = formatImage(img, message, scale);
  1708. console.log(...args);
  1709. };
  1710. img.src = image;
  1711. return noop;
  1712. }
  1713. const element = image.nodeName || '';
  1714. if (element.toLowerCase() === 'img') {
  1715. console.log(...formatImage(image, message, scale));
  1716. return noop;
  1717. }
  1718. if (element.toLowerCase() === 'canvas') {
  1719. const img = new Image();
  1720. img.onload = () => console.log(...formatImage(img, message, scale));
  1721. img.src = image.toDataURL();
  1722. return noop;
  1723. }
  1724. return noop;
  1725. }
  1726. function getTableHeader(table) {
  1727. for (const key in table) {
  1728. for (const title in table[key]) {
  1729. return title || 'untitled';
  1730. }
  1731. }
  1732. return 'empty';
  1733. }
  1734. const probeLog = new Log({
  1735. id: 'loaders.gl'
  1736. });
  1737. class NullLog {
  1738. log() {
  1739. return () => {};
  1740. }
  1741. info() {
  1742. return () => {};
  1743. }
  1744. warn() {
  1745. return () => {};
  1746. }
  1747. error() {
  1748. return () => {};
  1749. }
  1750. }
  1751. class ConsoleLog {
  1752. constructor() {
  1753. _defineProperty(this, "console", void 0);
  1754. this.console = console;
  1755. }
  1756. log(...args) {
  1757. return this.console.log.bind(this.console, ...args);
  1758. }
  1759. info(...args) {
  1760. return this.console.info.bind(this.console, ...args);
  1761. }
  1762. warn(...args) {
  1763. return this.console.warn.bind(this.console, ...args);
  1764. }
  1765. error(...args) {
  1766. return this.console.error.bind(this.console, ...args);
  1767. }
  1768. }
  1769. const DEFAULT_LOADER_OPTIONS = {
  1770. fetch: null,
  1771. mimeType: undefined,
  1772. nothrow: false,
  1773. log: new ConsoleLog(),
  1774. CDN: 'https://unpkg.com/@loaders.gl',
  1775. worker: true,
  1776. maxConcurrency: 3,
  1777. maxMobileConcurrency: 1,
  1778. reuseWorkers: isBrowser$2,
  1779. _nodeWorkers: false,
  1780. _workerType: '',
  1781. limit: 0,
  1782. _limitMB: 0,
  1783. batchSize: 'auto',
  1784. batchDebounceMs: 0,
  1785. metadata: false,
  1786. transforms: []
  1787. };
  1788. const REMOVED_LOADER_OPTIONS = {
  1789. throws: 'nothrow',
  1790. dataType: '(no longer used)',
  1791. uri: 'baseUri',
  1792. method: 'fetch.method',
  1793. headers: 'fetch.headers',
  1794. body: 'fetch.body',
  1795. mode: 'fetch.mode',
  1796. credentials: 'fetch.credentials',
  1797. cache: 'fetch.cache',
  1798. redirect: 'fetch.redirect',
  1799. referrer: 'fetch.referrer',
  1800. referrerPolicy: 'fetch.referrerPolicy',
  1801. integrity: 'fetch.integrity',
  1802. keepalive: 'fetch.keepalive',
  1803. signal: 'fetch.signal'
  1804. };
  1805. function getGlobalLoaderState() {
  1806. globalThis.loaders = globalThis.loaders || {};
  1807. const {
  1808. loaders
  1809. } = globalThis;
  1810. loaders._state = loaders._state || {};
  1811. return loaders._state;
  1812. }
  1813. const getGlobalLoaderOptions = () => {
  1814. const state = getGlobalLoaderState();
  1815. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1816. };
  1817. return state.globalOptions;
  1818. };
  1819. function normalizeOptions(options, loader, loaders, url) {
  1820. loaders = loaders || [];
  1821. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1822. validateOptions(options, loaders);
  1823. return normalizeOptionsInternal(loader, options, url);
  1824. }
  1825. function getFetchFunction(options, context) {
  1826. const globalOptions = getGlobalLoaderOptions();
  1827. const fetchOptions = options || globalOptions;
  1828. if (typeof fetchOptions.fetch === 'function') {
  1829. return fetchOptions.fetch;
  1830. }
  1831. if (isObject(fetchOptions.fetch)) {
  1832. return url => fetchFile(url, fetchOptions);
  1833. }
  1834. if (context !== null && context !== void 0 && context.fetch) {
  1835. return context === null || context === void 0 ? void 0 : context.fetch;
  1836. }
  1837. return fetchFile;
  1838. }
  1839. function validateOptions(options, loaders) {
  1840. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1841. for (const loader of loaders) {
  1842. const idOptions = options && options[loader.id] || {};
  1843. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1844. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1845. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1846. }
  1847. }
  1848. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1849. const loaderName = id || 'Top level';
  1850. const prefix = id ? "".concat(id, ".") : '';
  1851. for (const key in options) {
  1852. const isSubOptions = !id && isObject(options[key]);
  1853. const isBaseUriOption = key === 'baseUri' && !id;
  1854. const isWorkerUrlOption = key === 'workerUrl' && id;
  1855. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1856. if (key in deprecatedOptions) {
  1857. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1858. } else if (!isSubOptions) {
  1859. const suggestion = findSimilarOption(key, loaders);
  1860. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1861. }
  1862. }
  1863. }
  1864. }
  1865. function findSimilarOption(optionKey, loaders) {
  1866. const lowerCaseOptionKey = optionKey.toLowerCase();
  1867. let bestSuggestion = '';
  1868. for (const loader of loaders) {
  1869. for (const key in loader.options) {
  1870. if (optionKey === key) {
  1871. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1872. }
  1873. const lowerCaseKey = key.toLowerCase();
  1874. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1875. if (isPartialMatch) {
  1876. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1877. }
  1878. }
  1879. }
  1880. return bestSuggestion;
  1881. }
  1882. function normalizeOptionsInternal(loader, options, url) {
  1883. const loaderDefaultOptions = loader.options || {};
  1884. const mergedOptions = { ...loaderDefaultOptions
  1885. };
  1886. addUrlOptions(mergedOptions, url);
  1887. if (mergedOptions.log === null) {
  1888. mergedOptions.log = new NullLog();
  1889. }
  1890. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1891. mergeNestedFields(mergedOptions, options);
  1892. return mergedOptions;
  1893. }
  1894. function mergeNestedFields(mergedOptions, options) {
  1895. for (const key in options) {
  1896. if (key in options) {
  1897. const value = options[key];
  1898. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1899. mergedOptions[key] = { ...mergedOptions[key],
  1900. ...options[key]
  1901. };
  1902. } else {
  1903. mergedOptions[key] = options[key];
  1904. }
  1905. }
  1906. }
  1907. }
  1908. function addUrlOptions(options, url) {
  1909. if (url && !('baseUri' in options)) {
  1910. options.baseUri = url;
  1911. }
  1912. }
  1913. function isLoaderObject(loader) {
  1914. var _loader;
  1915. if (!loader) {
  1916. return false;
  1917. }
  1918. if (Array.isArray(loader)) {
  1919. loader = loader[0];
  1920. }
  1921. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1922. return hasExtensions;
  1923. }
  1924. function normalizeLoader(loader) {
  1925. var _loader2, _loader3;
  1926. assert$7(loader, 'null loader');
  1927. assert$7(isLoaderObject(loader), 'invalid loader');
  1928. let options;
  1929. if (Array.isArray(loader)) {
  1930. options = loader[1];
  1931. loader = loader[0];
  1932. loader = { ...loader,
  1933. options: { ...loader.options,
  1934. ...options
  1935. }
  1936. };
  1937. }
  1938. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1939. loader.text = true;
  1940. }
  1941. if (!loader.text) {
  1942. loader.binary = true;
  1943. }
  1944. return loader;
  1945. }
  1946. const getGlobalLoaderRegistry = () => {
  1947. const state = getGlobalLoaderState();
  1948. state.loaderRegistry = state.loaderRegistry || [];
  1949. return state.loaderRegistry;
  1950. };
  1951. function getRegisteredLoaders() {
  1952. return getGlobalLoaderRegistry();
  1953. }
  1954. const log = new Log({
  1955. id: 'loaders.gl'
  1956. });
  1957. const EXT_PATTERN = /\.([^.]+)$/;
  1958. async function selectLoader(data, loaders = [], options, context) {
  1959. if (!validHTTPResponse(data)) {
  1960. return null;
  1961. }
  1962. let loader = selectLoaderSync(data, loaders, { ...options,
  1963. nothrow: true
  1964. }, context);
  1965. if (loader) {
  1966. return loader;
  1967. }
  1968. if (isBlob(data)) {
  1969. data = await data.slice(0, 10).arrayBuffer();
  1970. loader = selectLoaderSync(data, loaders, options, context);
  1971. }
  1972. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1973. throw new Error(getNoValidLoaderMessage(data));
  1974. }
  1975. return loader;
  1976. }
  1977. function selectLoaderSync(data, loaders = [], options, context) {
  1978. if (!validHTTPResponse(data)) {
  1979. return null;
  1980. }
  1981. if (loaders && !Array.isArray(loaders)) {
  1982. return normalizeLoader(loaders);
  1983. }
  1984. let candidateLoaders = [];
  1985. if (loaders) {
  1986. candidateLoaders = candidateLoaders.concat(loaders);
  1987. }
  1988. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1989. candidateLoaders.push(...getRegisteredLoaders());
  1990. }
  1991. normalizeLoaders(candidateLoaders);
  1992. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1993. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1994. throw new Error(getNoValidLoaderMessage(data));
  1995. }
  1996. return loader;
  1997. }
  1998. function selectLoaderInternal(data, loaders, options, context) {
  1999. const {
  2000. url,
  2001. type
  2002. } = getResourceUrlAndType(data);
  2003. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  2004. let loader = null;
  2005. let reason = '';
  2006. if (options !== null && options !== void 0 && options.mimeType) {
  2007. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  2008. reason = "match forced by supplied MIME type ".concat(options === null || options === void 0 ? void 0 : options.mimeType);
  2009. }
  2010. loader = loader || findLoaderByUrl(loaders, testUrl);
  2011. reason = reason || (loader ? "matched url ".concat(testUrl) : '');
  2012. loader = loader || findLoaderByMIMEType(loaders, type);
  2013. reason = reason || (loader ? "matched MIME type ".concat(type) : '');
  2014. loader = loader || findLoaderByInitialBytes(loaders, data);
  2015. reason = reason || (loader ? "matched initial data ".concat(getFirstCharacters(data)) : '');
  2016. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  2017. reason = reason || (loader ? "matched fallback MIME type ".concat(type) : '');
  2018. if (reason) {
  2019. var _loader;
  2020. log.log(1, "selectLoader selected ".concat((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.name, ": ").concat(reason, "."));
  2021. }
  2022. return loader;
  2023. }
  2024. function validHTTPResponse(data) {
  2025. if (data instanceof Response) {
  2026. if (data.status === 204) {
  2027. return false;
  2028. }
  2029. }
  2030. return true;
  2031. }
  2032. function getNoValidLoaderMessage(data) {
  2033. const {
  2034. url,
  2035. type
  2036. } = getResourceUrlAndType(data);
  2037. let message = 'No valid loader found (';
  2038. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2039. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2040. const firstCharacters = data ? getFirstCharacters(data) : '';
  2041. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2042. message += ')';
  2043. return message;
  2044. }
  2045. function normalizeLoaders(loaders) {
  2046. for (const loader of loaders) {
  2047. normalizeLoader(loader);
  2048. }
  2049. }
  2050. function findLoaderByUrl(loaders, url) {
  2051. const match = url && EXT_PATTERN.exec(url);
  2052. const extension = match && match[1];
  2053. return extension ? findLoaderByExtension(loaders, extension) : null;
  2054. }
  2055. function findLoaderByExtension(loaders, extension) {
  2056. extension = extension.toLowerCase();
  2057. for (const loader of loaders) {
  2058. for (const loaderExtension of loader.extensions) {
  2059. if (loaderExtension.toLowerCase() === extension) {
  2060. return loader;
  2061. }
  2062. }
  2063. }
  2064. return null;
  2065. }
  2066. function findLoaderByMIMEType(loaders, mimeType) {
  2067. for (const loader of loaders) {
  2068. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2069. return loader;
  2070. }
  2071. if (mimeType === "application/x.".concat(loader.id)) {
  2072. return loader;
  2073. }
  2074. }
  2075. return null;
  2076. }
  2077. function findLoaderByInitialBytes(loaders, data) {
  2078. if (!data) {
  2079. return null;
  2080. }
  2081. for (const loader of loaders) {
  2082. if (typeof data === 'string') {
  2083. if (testDataAgainstText(data, loader)) {
  2084. return loader;
  2085. }
  2086. } else if (ArrayBuffer.isView(data)) {
  2087. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2088. return loader;
  2089. }
  2090. } else if (data instanceof ArrayBuffer) {
  2091. const byteOffset = 0;
  2092. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2093. return loader;
  2094. }
  2095. }
  2096. }
  2097. return null;
  2098. }
  2099. function testDataAgainstText(data, loader) {
  2100. if (loader.testText) {
  2101. return loader.testText(data);
  2102. }
  2103. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2104. return tests.some(test => data.startsWith(test));
  2105. }
  2106. function testDataAgainstBinary(data, byteOffset, loader) {
  2107. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2108. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2109. }
  2110. function testBinary(data, byteOffset, loader, test) {
  2111. if (test instanceof ArrayBuffer) {
  2112. return compareArrayBuffers(test, data, test.byteLength);
  2113. }
  2114. switch (typeof test) {
  2115. case 'function':
  2116. return test(data, loader);
  2117. case 'string':
  2118. const magic = getMagicString$2(data, byteOffset, test.length);
  2119. return test === magic;
  2120. default:
  2121. return false;
  2122. }
  2123. }
  2124. function getFirstCharacters(data, length = 5) {
  2125. if (typeof data === 'string') {
  2126. return data.slice(0, length);
  2127. } else if (ArrayBuffer.isView(data)) {
  2128. return getMagicString$2(data.buffer, data.byteOffset, length);
  2129. } else if (data instanceof ArrayBuffer) {
  2130. const byteOffset = 0;
  2131. return getMagicString$2(data, byteOffset, length);
  2132. }
  2133. return '';
  2134. }
  2135. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2136. if (arrayBuffer.byteLength < byteOffset + length) {
  2137. return '';
  2138. }
  2139. const dataView = new DataView(arrayBuffer);
  2140. let magic = '';
  2141. for (let i = 0; i < length; i++) {
  2142. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2143. }
  2144. return magic;
  2145. }
  2146. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2147. function* makeStringIterator(string, options) {
  2148. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2149. let offset = 0;
  2150. const textEncoder = new TextEncoder();
  2151. while (offset < string.length) {
  2152. const chunkLength = Math.min(string.length - offset, chunkSize);
  2153. const chunk = string.slice(offset, offset + chunkLength);
  2154. offset += chunkLength;
  2155. yield textEncoder.encode(chunk);
  2156. }
  2157. }
  2158. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2159. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2160. const {
  2161. chunkSize = DEFAULT_CHUNK_SIZE$1
  2162. } = options;
  2163. let byteOffset = 0;
  2164. while (byteOffset < arrayBuffer.byteLength) {
  2165. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2166. const chunk = new ArrayBuffer(chunkByteLength);
  2167. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2168. const chunkArray = new Uint8Array(chunk);
  2169. chunkArray.set(sourceArray);
  2170. byteOffset += chunkByteLength;
  2171. yield chunk;
  2172. }
  2173. }
  2174. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2175. async function* makeBlobIterator(blob, options) {
  2176. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2177. let offset = 0;
  2178. while (offset < blob.size) {
  2179. const end = offset + chunkSize;
  2180. const chunk = await blob.slice(offset, end).arrayBuffer();
  2181. offset = end;
  2182. yield chunk;
  2183. }
  2184. }
  2185. function makeStreamIterator(stream, options) {
  2186. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2187. }
  2188. async function* makeBrowserStreamIterator(stream, options) {
  2189. const reader = stream.getReader();
  2190. let nextBatchPromise;
  2191. try {
  2192. while (true) {
  2193. const currentBatchPromise = nextBatchPromise || reader.read();
  2194. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2195. nextBatchPromise = reader.read();
  2196. }
  2197. const {
  2198. done,
  2199. value
  2200. } = await currentBatchPromise;
  2201. if (done) {
  2202. return;
  2203. }
  2204. yield toArrayBuffer(value);
  2205. }
  2206. } catch (error) {
  2207. reader.releaseLock();
  2208. }
  2209. }
  2210. async function* makeNodeStreamIterator(stream, options) {
  2211. for await (const chunk of stream) {
  2212. yield toArrayBuffer(chunk);
  2213. }
  2214. }
  2215. function makeIterator(data, options) {
  2216. if (typeof data === 'string') {
  2217. return makeStringIterator(data, options);
  2218. }
  2219. if (data instanceof ArrayBuffer) {
  2220. return makeArrayBufferIterator(data, options);
  2221. }
  2222. if (isBlob(data)) {
  2223. return makeBlobIterator(data, options);
  2224. }
  2225. if (isReadableStream(data)) {
  2226. return makeStreamIterator(data, options);
  2227. }
  2228. if (isResponse(data)) {
  2229. const response = data;
  2230. return makeStreamIterator(response.body, options);
  2231. }
  2232. throw new Error('makeIterator');
  2233. }
  2234. const ERR_DATA = 'Cannot convert supplied data type';
  2235. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2236. if (loader.text && typeof data === 'string') {
  2237. return data;
  2238. }
  2239. if (isBuffer(data)) {
  2240. data = data.buffer;
  2241. }
  2242. if (data instanceof ArrayBuffer) {
  2243. const arrayBuffer = data;
  2244. if (loader.text && !loader.binary) {
  2245. const textDecoder = new TextDecoder('utf8');
  2246. return textDecoder.decode(arrayBuffer);
  2247. }
  2248. return arrayBuffer;
  2249. }
  2250. if (ArrayBuffer.isView(data)) {
  2251. if (loader.text && !loader.binary) {
  2252. const textDecoder = new TextDecoder('utf8');
  2253. return textDecoder.decode(data);
  2254. }
  2255. let arrayBuffer = data.buffer;
  2256. const byteLength = data.byteLength || data.length;
  2257. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2258. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2259. }
  2260. return arrayBuffer;
  2261. }
  2262. throw new Error(ERR_DATA);
  2263. }
  2264. async function getArrayBufferOrStringFromData(data, loader, options) {
  2265. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2266. if (typeof data === 'string' || isArrayBuffer) {
  2267. return getArrayBufferOrStringFromDataSync(data, loader);
  2268. }
  2269. if (isBlob(data)) {
  2270. data = await makeResponse(data);
  2271. }
  2272. if (isResponse(data)) {
  2273. const response = data;
  2274. await checkResponse(response);
  2275. return loader.binary ? await response.arrayBuffer() : await response.text();
  2276. }
  2277. if (isReadableStream(data)) {
  2278. data = makeIterator(data, options);
  2279. }
  2280. if (isIterable(data) || isAsyncIterable(data)) {
  2281. return concatenateArrayBuffersAsync(data);
  2282. }
  2283. throw new Error(ERR_DATA);
  2284. }
  2285. function getLoaderContext(context, options, previousContext = null) {
  2286. if (previousContext) {
  2287. return previousContext;
  2288. }
  2289. const resolvedContext = {
  2290. fetch: getFetchFunction(options, context),
  2291. ...context
  2292. };
  2293. if (!Array.isArray(resolvedContext.loaders)) {
  2294. resolvedContext.loaders = null;
  2295. }
  2296. return resolvedContext;
  2297. }
  2298. function getLoadersFromContext(loaders, context) {
  2299. if (!context && loaders && !Array.isArray(loaders)) {
  2300. return loaders;
  2301. }
  2302. let candidateLoaders;
  2303. if (loaders) {
  2304. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2305. }
  2306. if (context && context.loaders) {
  2307. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2308. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2309. }
  2310. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2311. }
  2312. async function parse$3(data, loaders, options, context) {
  2313. assert$6(!context || typeof context === 'object');
  2314. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2315. context = undefined;
  2316. options = loaders;
  2317. loaders = undefined;
  2318. }
  2319. data = await data;
  2320. options = options || {};
  2321. const {
  2322. url
  2323. } = getResourceUrlAndType(data);
  2324. const typedLoaders = loaders;
  2325. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2326. const loader = await selectLoader(data, candidateLoaders, options);
  2327. if (!loader) {
  2328. return null;
  2329. }
  2330. options = normalizeOptions(options, loader, candidateLoaders, url);
  2331. context = getLoaderContext({
  2332. url,
  2333. parse: parse$3,
  2334. loaders: candidateLoaders
  2335. }, options, context);
  2336. return await parseWithLoader(loader, data, options, context);
  2337. }
  2338. async function parseWithLoader(loader, data, options, context) {
  2339. validateWorkerVersion(loader);
  2340. if (isResponse(data)) {
  2341. const response = data;
  2342. const {
  2343. ok,
  2344. redirected,
  2345. status,
  2346. statusText,
  2347. type,
  2348. url
  2349. } = response;
  2350. const headers = Object.fromEntries(response.headers.entries());
  2351. context.response = {
  2352. headers,
  2353. ok,
  2354. redirected,
  2355. status,
  2356. statusText,
  2357. type,
  2358. url
  2359. };
  2360. }
  2361. data = await getArrayBufferOrStringFromData(data, loader, options);
  2362. if (loader.parseTextSync && typeof data === 'string') {
  2363. options.dataType = 'text';
  2364. return loader.parseTextSync(data, options, context, loader);
  2365. }
  2366. if (canParseWithWorker(loader, options)) {
  2367. return await parseWithWorker(loader, data, options, context, parse$3);
  2368. }
  2369. if (loader.parseText && typeof data === 'string') {
  2370. return await loader.parseText(data, options, context, loader);
  2371. }
  2372. if (loader.parse) {
  2373. return await loader.parse(data, options, context, loader);
  2374. }
  2375. assert$6(!loader.parseSync);
  2376. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2377. }
  2378. async function load(url, loaders, options, context) {
  2379. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2380. options = loaders;
  2381. loaders = undefined;
  2382. }
  2383. const fetch = getFetchFunction(options);
  2384. let data = url;
  2385. if (typeof url === 'string') {
  2386. data = await fetch(url);
  2387. }
  2388. if (isBlob(url)) {
  2389. data = await fetch(url);
  2390. }
  2391. return await parse$3(data, loaders, options);
  2392. }
  2393. function assert$4(condition, message) {
  2394. if (!condition) {
  2395. throw new Error("math.gl assertion ".concat(message));
  2396. }
  2397. }
  2398. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2399. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2400. const config = {
  2401. EPSILON: 1e-12,
  2402. debug: false,
  2403. precision: 4,
  2404. printTypes: false,
  2405. printDegrees: false,
  2406. printRowMajor: true
  2407. };
  2408. function formatValue(value, {
  2409. precision = config.precision
  2410. } = {}) {
  2411. value = round(value);
  2412. return "".concat(parseFloat(value.toPrecision(precision)));
  2413. }
  2414. function isArray(value) {
  2415. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2416. }
  2417. function toRadians(degrees) {
  2418. return radians(degrees);
  2419. }
  2420. function toDegrees(radians) {
  2421. return degrees(radians);
  2422. }
  2423. function radians(degrees, result) {
  2424. return map(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2425. }
  2426. function degrees(radians, result) {
  2427. return map(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2428. }
  2429. function clamp(value, min, max) {
  2430. return map(value, value => Math.max(min, Math.min(max, value)));
  2431. }
  2432. function equals(a, b, epsilon) {
  2433. const oldEpsilon = config.EPSILON;
  2434. if (epsilon) {
  2435. config.EPSILON = epsilon;
  2436. }
  2437. try {
  2438. if (a === b) {
  2439. return true;
  2440. }
  2441. if (isArray(a) && isArray(b)) {
  2442. if (a.length !== b.length) {
  2443. return false;
  2444. }
  2445. for (let i = 0; i < a.length; ++i) {
  2446. if (!equals(a[i], b[i])) {
  2447. return false;
  2448. }
  2449. }
  2450. return true;
  2451. }
  2452. if (a && a.equals) {
  2453. return a.equals(b);
  2454. }
  2455. if (b && b.equals) {
  2456. return b.equals(a);
  2457. }
  2458. if (typeof a === 'number' && typeof b === 'number') {
  2459. return Math.abs(a - b) <= config.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
  2460. }
  2461. return false;
  2462. } finally {
  2463. config.EPSILON = oldEpsilon;
  2464. }
  2465. }
  2466. function round(value) {
  2467. return Math.round(value / config.EPSILON) * config.EPSILON;
  2468. }
  2469. function duplicateArray(array) {
  2470. return array.clone ? array.clone() : new Array(array.length);
  2471. }
  2472. function map(value, func, result) {
  2473. if (isArray(value)) {
  2474. const array = value;
  2475. result = result || duplicateArray(array);
  2476. for (let i = 0; i < result.length && i < array.length; ++i) {
  2477. result[i] = func(value[i], i, result);
  2478. }
  2479. return result;
  2480. }
  2481. return func(value);
  2482. }
  2483. function _extendableBuiltin(cls) {
  2484. function ExtendableBuiltin() {
  2485. var instance = Reflect.construct(cls, Array.from(arguments));
  2486. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2487. return instance;
  2488. }
  2489. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2490. constructor: {
  2491. value: cls,
  2492. enumerable: false,
  2493. writable: true,
  2494. configurable: true
  2495. }
  2496. });
  2497. if (Object.setPrototypeOf) {
  2498. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2499. } else {
  2500. ExtendableBuiltin.__proto__ = cls;
  2501. }
  2502. return ExtendableBuiltin;
  2503. }
  2504. class MathArray extends _extendableBuiltin(Array) {
  2505. clone() {
  2506. return new this.constructor().copy(this);
  2507. }
  2508. fromArray(array, offset = 0) {
  2509. for (let i = 0; i < this.ELEMENTS; ++i) {
  2510. this[i] = array[i + offset];
  2511. }
  2512. return this.check();
  2513. }
  2514. toArray(targetArray = [], offset = 0) {
  2515. for (let i = 0; i < this.ELEMENTS; ++i) {
  2516. targetArray[offset + i] = this[i];
  2517. }
  2518. return targetArray;
  2519. }
  2520. from(arrayOrObject) {
  2521. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2522. }
  2523. to(arrayOrObject) {
  2524. if (arrayOrObject === this) {
  2525. return this;
  2526. }
  2527. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2528. }
  2529. toTarget(target) {
  2530. return target ? this.to(target) : this;
  2531. }
  2532. toFloat32Array() {
  2533. return new Float32Array(this);
  2534. }
  2535. toString() {
  2536. return this.formatString(config);
  2537. }
  2538. formatString(opts) {
  2539. let string = '';
  2540. for (let i = 0; i < this.ELEMENTS; ++i) {
  2541. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2542. }
  2543. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2544. }
  2545. equals(array) {
  2546. if (!array || this.length !== array.length) {
  2547. return false;
  2548. }
  2549. for (let i = 0; i < this.ELEMENTS; ++i) {
  2550. if (!equals(this[i], array[i])) {
  2551. return false;
  2552. }
  2553. }
  2554. return true;
  2555. }
  2556. exactEquals(array) {
  2557. if (!array || this.length !== array.length) {
  2558. return false;
  2559. }
  2560. for (let i = 0; i < this.ELEMENTS; ++i) {
  2561. if (this[i] !== array[i]) {
  2562. return false;
  2563. }
  2564. }
  2565. return true;
  2566. }
  2567. negate() {
  2568. for (let i = 0; i < this.ELEMENTS; ++i) {
  2569. this[i] = -this[i];
  2570. }
  2571. return this.check();
  2572. }
  2573. lerp(a, b, t) {
  2574. if (t === undefined) {
  2575. return this.lerp(this, a, b);
  2576. }
  2577. for (let i = 0; i < this.ELEMENTS; ++i) {
  2578. const ai = a[i];
  2579. this[i] = ai + t * (b[i] - ai);
  2580. }
  2581. return this.check();
  2582. }
  2583. min(vector) {
  2584. for (let i = 0; i < this.ELEMENTS; ++i) {
  2585. this[i] = Math.min(vector[i], this[i]);
  2586. }
  2587. return this.check();
  2588. }
  2589. max(vector) {
  2590. for (let i = 0; i < this.ELEMENTS; ++i) {
  2591. this[i] = Math.max(vector[i], this[i]);
  2592. }
  2593. return this.check();
  2594. }
  2595. clamp(minVector, maxVector) {
  2596. for (let i = 0; i < this.ELEMENTS; ++i) {
  2597. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2598. }
  2599. return this.check();
  2600. }
  2601. add(...vectors) {
  2602. for (const vector of vectors) {
  2603. for (let i = 0; i < this.ELEMENTS; ++i) {
  2604. this[i] += vector[i];
  2605. }
  2606. }
  2607. return this.check();
  2608. }
  2609. subtract(...vectors) {
  2610. for (const vector of vectors) {
  2611. for (let i = 0; i < this.ELEMENTS; ++i) {
  2612. this[i] -= vector[i];
  2613. }
  2614. }
  2615. return this.check();
  2616. }
  2617. scale(scale) {
  2618. if (typeof scale === 'number') {
  2619. for (let i = 0; i < this.ELEMENTS; ++i) {
  2620. this[i] *= scale;
  2621. }
  2622. } else {
  2623. for (let i = 0; i < this.ELEMENTS && i < scale.length; ++i) {
  2624. this[i] *= scale[i];
  2625. }
  2626. }
  2627. return this.check();
  2628. }
  2629. multiplyByScalar(scalar) {
  2630. for (let i = 0; i < this.ELEMENTS; ++i) {
  2631. this[i] *= scalar;
  2632. }
  2633. return this.check();
  2634. }
  2635. check() {
  2636. if (config.debug && !this.validate()) {
  2637. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2638. }
  2639. return this;
  2640. }
  2641. validate() {
  2642. let valid = this.length === this.ELEMENTS;
  2643. for (let i = 0; i < this.ELEMENTS; ++i) {
  2644. valid = valid && Number.isFinite(this[i]);
  2645. }
  2646. return valid;
  2647. }
  2648. sub(a) {
  2649. return this.subtract(a);
  2650. }
  2651. setScalar(a) {
  2652. for (let i = 0; i < this.ELEMENTS; ++i) {
  2653. this[i] = a;
  2654. }
  2655. return this.check();
  2656. }
  2657. addScalar(a) {
  2658. for (let i = 0; i < this.ELEMENTS; ++i) {
  2659. this[i] += a;
  2660. }
  2661. return this.check();
  2662. }
  2663. subScalar(a) {
  2664. return this.addScalar(-a);
  2665. }
  2666. multiplyScalar(scalar) {
  2667. for (let i = 0; i < this.ELEMENTS; ++i) {
  2668. this[i] *= scalar;
  2669. }
  2670. return this.check();
  2671. }
  2672. divideScalar(a) {
  2673. return this.multiplyByScalar(1 / a);
  2674. }
  2675. clampScalar(min, max) {
  2676. for (let i = 0; i < this.ELEMENTS; ++i) {
  2677. this[i] = Math.min(Math.max(this[i], min), max);
  2678. }
  2679. return this.check();
  2680. }
  2681. get elements() {
  2682. return this;
  2683. }
  2684. }
  2685. function validateVector(v, length) {
  2686. if (v.length !== length) {
  2687. return false;
  2688. }
  2689. for (let i = 0; i < v.length; ++i) {
  2690. if (!Number.isFinite(v[i])) {
  2691. return false;
  2692. }
  2693. }
  2694. return true;
  2695. }
  2696. function checkNumber(value) {
  2697. if (!Number.isFinite(value)) {
  2698. throw new Error("Invalid number ".concat(value));
  2699. }
  2700. return value;
  2701. }
  2702. function checkVector(v, length, callerName = '') {
  2703. if (config.debug && !validateVector(v, length)) {
  2704. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2705. }
  2706. return v;
  2707. }
  2708. class Vector extends MathArray {
  2709. get x() {
  2710. return this[0];
  2711. }
  2712. set x(value) {
  2713. this[0] = checkNumber(value);
  2714. }
  2715. get y() {
  2716. return this[1];
  2717. }
  2718. set y(value) {
  2719. this[1] = checkNumber(value);
  2720. }
  2721. len() {
  2722. return Math.sqrt(this.lengthSquared());
  2723. }
  2724. magnitude() {
  2725. return this.len();
  2726. }
  2727. lengthSquared() {
  2728. let length = 0;
  2729. for (let i = 0; i < this.ELEMENTS; ++i) {
  2730. length += this[i] * this[i];
  2731. }
  2732. return length;
  2733. }
  2734. magnitudeSquared() {
  2735. return this.lengthSquared();
  2736. }
  2737. distance(mathArray) {
  2738. return Math.sqrt(this.distanceSquared(mathArray));
  2739. }
  2740. distanceSquared(mathArray) {
  2741. let length = 0;
  2742. for (let i = 0; i < this.ELEMENTS; ++i) {
  2743. const dist = this[i] - mathArray[i];
  2744. length += dist * dist;
  2745. }
  2746. return checkNumber(length);
  2747. }
  2748. dot(mathArray) {
  2749. let product = 0;
  2750. for (let i = 0; i < this.ELEMENTS; ++i) {
  2751. product += this[i] * mathArray[i];
  2752. }
  2753. return checkNumber(product);
  2754. }
  2755. normalize() {
  2756. const length = this.magnitude();
  2757. if (length !== 0) {
  2758. for (let i = 0; i < this.ELEMENTS; ++i) {
  2759. this[i] /= length;
  2760. }
  2761. }
  2762. return this.check();
  2763. }
  2764. multiply(...vectors) {
  2765. for (const vector of vectors) {
  2766. for (let i = 0; i < this.ELEMENTS; ++i) {
  2767. this[i] *= vector[i];
  2768. }
  2769. }
  2770. return this.check();
  2771. }
  2772. divide(...vectors) {
  2773. for (const vector of vectors) {
  2774. for (let i = 0; i < this.ELEMENTS; ++i) {
  2775. this[i] /= vector[i];
  2776. }
  2777. }
  2778. return this.check();
  2779. }
  2780. lengthSq() {
  2781. return this.lengthSquared();
  2782. }
  2783. distanceTo(vector) {
  2784. return this.distance(vector);
  2785. }
  2786. distanceToSquared(vector) {
  2787. return this.distanceSquared(vector);
  2788. }
  2789. getComponent(i) {
  2790. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2791. return checkNumber(this[i]);
  2792. }
  2793. setComponent(i, value) {
  2794. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2795. this[i] = value;
  2796. return this.check();
  2797. }
  2798. addVectors(a, b) {
  2799. return this.copy(a).add(b);
  2800. }
  2801. subVectors(a, b) {
  2802. return this.copy(a).subtract(b);
  2803. }
  2804. multiplyVectors(a, b) {
  2805. return this.copy(a).multiply(b);
  2806. }
  2807. addScaledVector(a, b) {
  2808. return this.add(new this.constructor(a).multiplyScalar(b));
  2809. }
  2810. }
  2811. /**
  2812. * Common utilities
  2813. * @module glMatrix
  2814. */
  2815. // Configuration Constants
  2816. var EPSILON = 0.000001;
  2817. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2818. if (!Math.hypot) Math.hypot = function () {
  2819. var y = 0,
  2820. i = arguments.length;
  2821. while (i--) {
  2822. y += arguments[i] * arguments[i];
  2823. }
  2824. return Math.sqrt(y);
  2825. };
  2826. /**
  2827. * 2 Dimensional Vector
  2828. * @module vec2
  2829. */
  2830. /**
  2831. * Creates a new, empty vec2
  2832. *
  2833. * @returns {vec2} a new 2D vector
  2834. */
  2835. function create$4() {
  2836. var out = new ARRAY_TYPE(2);
  2837. if (ARRAY_TYPE != Float32Array) {
  2838. out[0] = 0;
  2839. out[1] = 0;
  2840. }
  2841. return out;
  2842. }
  2843. /**
  2844. * Transforms the vec2 with a mat2
  2845. *
  2846. * @param {vec2} out the receiving vector
  2847. * @param {ReadonlyVec2} a the vector to transform
  2848. * @param {ReadonlyMat2} m matrix to transform with
  2849. * @returns {vec2} out
  2850. */
  2851. function transformMat2(out, a, m) {
  2852. var x = a[0],
  2853. y = a[1];
  2854. out[0] = m[0] * x + m[2] * y;
  2855. out[1] = m[1] * x + m[3] * y;
  2856. return out;
  2857. }
  2858. /**
  2859. * Transforms the vec2 with a mat2d
  2860. *
  2861. * @param {vec2} out the receiving vector
  2862. * @param {ReadonlyVec2} a the vector to transform
  2863. * @param {ReadonlyMat2d} m matrix to transform with
  2864. * @returns {vec2} out
  2865. */
  2866. function transformMat2d(out, a, m) {
  2867. var x = a[0],
  2868. y = a[1];
  2869. out[0] = m[0] * x + m[2] * y + m[4];
  2870. out[1] = m[1] * x + m[3] * y + m[5];
  2871. return out;
  2872. }
  2873. /**
  2874. * Transforms the vec2 with a mat3
  2875. * 3rd vector component is implicitly '1'
  2876. *
  2877. * @param {vec2} out the receiving vector
  2878. * @param {ReadonlyVec2} a the vector to transform
  2879. * @param {ReadonlyMat3} m matrix to transform with
  2880. * @returns {vec2} out
  2881. */
  2882. function transformMat3$1(out, a, m) {
  2883. var x = a[0],
  2884. y = a[1];
  2885. out[0] = m[0] * x + m[3] * y + m[6];
  2886. out[1] = m[1] * x + m[4] * y + m[7];
  2887. return out;
  2888. }
  2889. /**
  2890. * Transforms the vec2 with a mat4
  2891. * 3rd vector component is implicitly '0'
  2892. * 4th vector component is implicitly '1'
  2893. *
  2894. * @param {vec2} out the receiving vector
  2895. * @param {ReadonlyVec2} a the vector to transform
  2896. * @param {ReadonlyMat4} m matrix to transform with
  2897. * @returns {vec2} out
  2898. */
  2899. function transformMat4$2(out, a, m) {
  2900. var x = a[0];
  2901. var y = a[1];
  2902. out[0] = m[0] * x + m[4] * y + m[12];
  2903. out[1] = m[1] * x + m[5] * y + m[13];
  2904. return out;
  2905. }
  2906. /**
  2907. * Perform some operation over an array of vec2s.
  2908. *
  2909. * @param {Array} a the array of vectors to iterate over
  2910. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2911. * @param {Number} offset Number of elements to skip at the beginning of the array
  2912. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2913. * @param {Function} fn Function to call for each vector in the array
  2914. * @param {Object} [arg] additional argument to pass to fn
  2915. * @returns {Array} a
  2916. * @function
  2917. */
  2918. (function () {
  2919. var vec = create$4();
  2920. return function (a, stride, offset, count, fn, arg) {
  2921. var i, l;
  2922. if (!stride) {
  2923. stride = 2;
  2924. }
  2925. if (!offset) {
  2926. offset = 0;
  2927. }
  2928. if (count) {
  2929. l = Math.min(count * stride + offset, a.length);
  2930. } else {
  2931. l = a.length;
  2932. }
  2933. for (i = offset; i < l; i += stride) {
  2934. vec[0] = a[i];
  2935. vec[1] = a[i + 1];
  2936. fn(vec, vec, arg);
  2937. a[i] = vec[0];
  2938. a[i + 1] = vec[1];
  2939. }
  2940. return a;
  2941. };
  2942. })();
  2943. function vec2_transformMat4AsVector(out, a, m) {
  2944. const x = a[0];
  2945. const y = a[1];
  2946. const w = m[3] * x + m[7] * y || 1.0;
  2947. out[0] = (m[0] * x + m[4] * y) / w;
  2948. out[1] = (m[1] * x + m[5] * y) / w;
  2949. return out;
  2950. }
  2951. function vec3_transformMat4AsVector(out, a, m) {
  2952. const x = a[0];
  2953. const y = a[1];
  2954. const z = a[2];
  2955. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2956. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2957. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2958. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2959. return out;
  2960. }
  2961. function vec3_transformMat2(out, a, m) {
  2962. const x = a[0];
  2963. const y = a[1];
  2964. out[0] = m[0] * x + m[2] * y;
  2965. out[1] = m[1] * x + m[3] * y;
  2966. out[2] = a[2];
  2967. return out;
  2968. }
  2969. function vec4_transformMat2(out, a, m) {
  2970. const x = a[0];
  2971. const y = a[1];
  2972. out[0] = m[0] * x + m[2] * y;
  2973. out[1] = m[1] * x + m[3] * y;
  2974. out[2] = a[2];
  2975. out[3] = a[3];
  2976. return out;
  2977. }
  2978. function vec4_transformMat3(out, a, m) {
  2979. const x = a[0];
  2980. const y = a[1];
  2981. const z = a[2];
  2982. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2983. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2984. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2985. out[3] = a[3];
  2986. return out;
  2987. }
  2988. class Vector2 extends Vector {
  2989. constructor(x = 0, y = 0) {
  2990. super(2);
  2991. if (isArray(x) && arguments.length === 1) {
  2992. this.copy(x);
  2993. } else {
  2994. if (config.debug) {
  2995. checkNumber(x);
  2996. checkNumber(y);
  2997. }
  2998. this[0] = x;
  2999. this[1] = y;
  3000. }
  3001. }
  3002. set(x, y) {
  3003. this[0] = x;
  3004. this[1] = y;
  3005. return this.check();
  3006. }
  3007. copy(array) {
  3008. this[0] = array[0];
  3009. this[1] = array[1];
  3010. return this.check();
  3011. }
  3012. fromObject(object) {
  3013. if (config.debug) {
  3014. checkNumber(object.x);
  3015. checkNumber(object.y);
  3016. }
  3017. this[0] = object.x;
  3018. this[1] = object.y;
  3019. return this.check();
  3020. }
  3021. toObject(object) {
  3022. object.x = this[0];
  3023. object.y = this[1];
  3024. return object;
  3025. }
  3026. get ELEMENTS() {
  3027. return 2;
  3028. }
  3029. horizontalAngle() {
  3030. return Math.atan2(this.y, this.x);
  3031. }
  3032. verticalAngle() {
  3033. return Math.atan2(this.x, this.y);
  3034. }
  3035. transform(matrix4) {
  3036. return this.transformAsPoint(matrix4);
  3037. }
  3038. transformAsPoint(matrix4) {
  3039. transformMat4$2(this, this, matrix4);
  3040. return this.check();
  3041. }
  3042. transformAsVector(matrix4) {
  3043. vec2_transformMat4AsVector(this, this, matrix4);
  3044. return this.check();
  3045. }
  3046. transformByMatrix3(matrix3) {
  3047. transformMat3$1(this, this, matrix3);
  3048. return this.check();
  3049. }
  3050. transformByMatrix2x3(matrix2x3) {
  3051. transformMat2d(this, this, matrix2x3);
  3052. return this.check();
  3053. }
  3054. transformByMatrix2(matrix2) {
  3055. transformMat2(this, this, matrix2);
  3056. return this.check();
  3057. }
  3058. }
  3059. /**
  3060. * 3 Dimensional Vector
  3061. * @module vec3
  3062. */
  3063. /**
  3064. * Creates a new, empty vec3
  3065. *
  3066. * @returns {vec3} a new 3D vector
  3067. */
  3068. function create$3() {
  3069. var out = new ARRAY_TYPE(3);
  3070. if (ARRAY_TYPE != Float32Array) {
  3071. out[0] = 0;
  3072. out[1] = 0;
  3073. out[2] = 0;
  3074. }
  3075. return out;
  3076. }
  3077. /**
  3078. * Calculates the length of a vec3
  3079. *
  3080. * @param {ReadonlyVec3} a vector to calculate length of
  3081. * @returns {Number} length of a
  3082. */
  3083. function length$2(a) {
  3084. var x = a[0];
  3085. var y = a[1];
  3086. var z = a[2];
  3087. return Math.hypot(x, y, z);
  3088. }
  3089. /**
  3090. * Creates a new vec3 initialized with the given values
  3091. *
  3092. * @param {Number} x X component
  3093. * @param {Number} y Y component
  3094. * @param {Number} z Z component
  3095. * @returns {vec3} a new 3D vector
  3096. */
  3097. function fromValues(x, y, z) {
  3098. var out = new ARRAY_TYPE(3);
  3099. out[0] = x;
  3100. out[1] = y;
  3101. out[2] = z;
  3102. return out;
  3103. }
  3104. /**
  3105. * Normalize a vec3
  3106. *
  3107. * @param {vec3} out the receiving vector
  3108. * @param {ReadonlyVec3} a vector to normalize
  3109. * @returns {vec3} out
  3110. */
  3111. function normalize$2(out, a) {
  3112. var x = a[0];
  3113. var y = a[1];
  3114. var z = a[2];
  3115. var len = x * x + y * y + z * z;
  3116. if (len > 0) {
  3117. //TODO: evaluate use of glm_invsqrt here?
  3118. len = 1 / Math.sqrt(len);
  3119. }
  3120. out[0] = a[0] * len;
  3121. out[1] = a[1] * len;
  3122. out[2] = a[2] * len;
  3123. return out;
  3124. }
  3125. /**
  3126. * Calculates the dot product of two vec3's
  3127. *
  3128. * @param {ReadonlyVec3} a the first operand
  3129. * @param {ReadonlyVec3} b the second operand
  3130. * @returns {Number} dot product of a and b
  3131. */
  3132. function dot$2(a, b) {
  3133. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3134. }
  3135. /**
  3136. * Computes the cross product of two vec3's
  3137. *
  3138. * @param {vec3} out the receiving vector
  3139. * @param {ReadonlyVec3} a the first operand
  3140. * @param {ReadonlyVec3} b the second operand
  3141. * @returns {vec3} out
  3142. */
  3143. function cross(out, a, b) {
  3144. var ax = a[0],
  3145. ay = a[1],
  3146. az = a[2];
  3147. var bx = b[0],
  3148. by = b[1],
  3149. bz = b[2];
  3150. out[0] = ay * bz - az * by;
  3151. out[1] = az * bx - ax * bz;
  3152. out[2] = ax * by - ay * bx;
  3153. return out;
  3154. }
  3155. /**
  3156. * Transforms the vec3 with a mat4.
  3157. * 4th vector component is implicitly '1'
  3158. *
  3159. * @param {vec3} out the receiving vector
  3160. * @param {ReadonlyVec3} a the vector to transform
  3161. * @param {ReadonlyMat4} m matrix to transform with
  3162. * @returns {vec3} out
  3163. */
  3164. function transformMat4$1(out, a, m) {
  3165. var x = a[0],
  3166. y = a[1],
  3167. z = a[2];
  3168. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3169. w = w || 1.0;
  3170. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3171. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3172. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3173. return out;
  3174. }
  3175. /**
  3176. * Transforms the vec3 with a mat3.
  3177. *
  3178. * @param {vec3} out the receiving vector
  3179. * @param {ReadonlyVec3} a the vector to transform
  3180. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3181. * @returns {vec3} out
  3182. */
  3183. function transformMat3(out, a, m) {
  3184. var x = a[0],
  3185. y = a[1],
  3186. z = a[2];
  3187. out[0] = x * m[0] + y * m[3] + z * m[6];
  3188. out[1] = x * m[1] + y * m[4] + z * m[7];
  3189. out[2] = x * m[2] + y * m[5] + z * m[8];
  3190. return out;
  3191. }
  3192. /**
  3193. * Transforms the vec3 with a quat
  3194. * Can also be used for dual quaternions. (Multiply it with the real part)
  3195. *
  3196. * @param {vec3} out the receiving vector
  3197. * @param {ReadonlyVec3} a the vector to transform
  3198. * @param {ReadonlyQuat} q quaternion to transform with
  3199. * @returns {vec3} out
  3200. */
  3201. function transformQuat$1(out, a, q) {
  3202. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3203. var qx = q[0],
  3204. qy = q[1],
  3205. qz = q[2],
  3206. qw = q[3];
  3207. var x = a[0],
  3208. y = a[1],
  3209. z = a[2]; // var qvec = [qx, qy, qz];
  3210. // var uv = vec3.cross([], qvec, a);
  3211. var uvx = qy * z - qz * y,
  3212. uvy = qz * x - qx * z,
  3213. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3214. var uuvx = qy * uvz - qz * uvy,
  3215. uuvy = qz * uvx - qx * uvz,
  3216. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3217. var w2 = qw * 2;
  3218. uvx *= w2;
  3219. uvy *= w2;
  3220. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3221. uuvx *= 2;
  3222. uuvy *= 2;
  3223. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3224. out[0] = x + uvx + uuvx;
  3225. out[1] = y + uvy + uuvy;
  3226. out[2] = z + uvz + uuvz;
  3227. return out;
  3228. }
  3229. /**
  3230. * Rotate a 3D vector around the x-axis
  3231. * @param {vec3} out The receiving vec3
  3232. * @param {ReadonlyVec3} a The vec3 point to rotate
  3233. * @param {ReadonlyVec3} b The origin of the rotation
  3234. * @param {Number} rad The angle of rotation in radians
  3235. * @returns {vec3} out
  3236. */
  3237. function rotateX$2(out, a, b, rad) {
  3238. var p = [],
  3239. r = []; //Translate point to the origin
  3240. p[0] = a[0] - b[0];
  3241. p[1] = a[1] - b[1];
  3242. p[2] = a[2] - b[2]; //perform rotation
  3243. r[0] = p[0];
  3244. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3245. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3246. out[0] = r[0] + b[0];
  3247. out[1] = r[1] + b[1];
  3248. out[2] = r[2] + b[2];
  3249. return out;
  3250. }
  3251. /**
  3252. * Rotate a 3D vector around the y-axis
  3253. * @param {vec3} out The receiving vec3
  3254. * @param {ReadonlyVec3} a The vec3 point to rotate
  3255. * @param {ReadonlyVec3} b The origin of the rotation
  3256. * @param {Number} rad The angle of rotation in radians
  3257. * @returns {vec3} out
  3258. */
  3259. function rotateY$2(out, a, b, rad) {
  3260. var p = [],
  3261. r = []; //Translate point to the origin
  3262. p[0] = a[0] - b[0];
  3263. p[1] = a[1] - b[1];
  3264. p[2] = a[2] - b[2]; //perform rotation
  3265. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3266. r[1] = p[1];
  3267. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3268. out[0] = r[0] + b[0];
  3269. out[1] = r[1] + b[1];
  3270. out[2] = r[2] + b[2];
  3271. return out;
  3272. }
  3273. /**
  3274. * Rotate a 3D vector around the z-axis
  3275. * @param {vec3} out The receiving vec3
  3276. * @param {ReadonlyVec3} a The vec3 point to rotate
  3277. * @param {ReadonlyVec3} b The origin of the rotation
  3278. * @param {Number} rad The angle of rotation in radians
  3279. * @returns {vec3} out
  3280. */
  3281. function rotateZ$2(out, a, b, rad) {
  3282. var p = [],
  3283. r = []; //Translate point to the origin
  3284. p[0] = a[0] - b[0];
  3285. p[1] = a[1] - b[1];
  3286. p[2] = a[2] - b[2]; //perform rotation
  3287. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3288. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3289. r[2] = p[2]; //translate to correct position
  3290. out[0] = r[0] + b[0];
  3291. out[1] = r[1] + b[1];
  3292. out[2] = r[2] + b[2];
  3293. return out;
  3294. }
  3295. /**
  3296. * Get the angle between two 3D vectors
  3297. * @param {ReadonlyVec3} a The first operand
  3298. * @param {ReadonlyVec3} b The second operand
  3299. * @returns {Number} The angle in radians
  3300. */
  3301. function angle(a, b) {
  3302. var ax = a[0],
  3303. ay = a[1],
  3304. az = a[2],
  3305. bx = b[0],
  3306. by = b[1],
  3307. bz = b[2],
  3308. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3309. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3310. mag = mag1 * mag2,
  3311. cosine = mag && dot$2(a, b) / mag;
  3312. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3313. }
  3314. /**
  3315. * Alias for {@link vec3.length}
  3316. * @function
  3317. */
  3318. var len = length$2;
  3319. /**
  3320. * Perform some operation over an array of vec3s.
  3321. *
  3322. * @param {Array} a the array of vectors to iterate over
  3323. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3324. * @param {Number} offset Number of elements to skip at the beginning of the array
  3325. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3326. * @param {Function} fn Function to call for each vector in the array
  3327. * @param {Object} [arg] additional argument to pass to fn
  3328. * @returns {Array} a
  3329. * @function
  3330. */
  3331. (function () {
  3332. var vec = create$3();
  3333. return function (a, stride, offset, count, fn, arg) {
  3334. var i, l;
  3335. if (!stride) {
  3336. stride = 3;
  3337. }
  3338. if (!offset) {
  3339. offset = 0;
  3340. }
  3341. if (count) {
  3342. l = Math.min(count * stride + offset, a.length);
  3343. } else {
  3344. l = a.length;
  3345. }
  3346. for (i = offset; i < l; i += stride) {
  3347. vec[0] = a[i];
  3348. vec[1] = a[i + 1];
  3349. vec[2] = a[i + 2];
  3350. fn(vec, vec, arg);
  3351. a[i] = vec[0];
  3352. a[i + 1] = vec[1];
  3353. a[i + 2] = vec[2];
  3354. }
  3355. return a;
  3356. };
  3357. })();
  3358. const ORIGIN = [0, 0, 0];
  3359. let ZERO$2;
  3360. class Vector3 extends Vector {
  3361. static get ZERO() {
  3362. if (!ZERO$2) {
  3363. ZERO$2 = new Vector3(0, 0, 0);
  3364. Object.freeze(ZERO$2);
  3365. }
  3366. return ZERO$2;
  3367. }
  3368. constructor(x = 0, y = 0, z = 0) {
  3369. super(-0, -0, -0);
  3370. if (arguments.length === 1 && isArray(x)) {
  3371. this.copy(x);
  3372. } else {
  3373. if (config.debug) {
  3374. checkNumber(x);
  3375. checkNumber(y);
  3376. checkNumber(z);
  3377. }
  3378. this[0] = x;
  3379. this[1] = y;
  3380. this[2] = z;
  3381. }
  3382. }
  3383. set(x, y, z) {
  3384. this[0] = x;
  3385. this[1] = y;
  3386. this[2] = z;
  3387. return this.check();
  3388. }
  3389. copy(array) {
  3390. this[0] = array[0];
  3391. this[1] = array[1];
  3392. this[2] = array[2];
  3393. return this.check();
  3394. }
  3395. fromObject(object) {
  3396. if (config.debug) {
  3397. checkNumber(object.x);
  3398. checkNumber(object.y);
  3399. checkNumber(object.z);
  3400. }
  3401. this[0] = object.x;
  3402. this[1] = object.y;
  3403. this[2] = object.z;
  3404. return this.check();
  3405. }
  3406. toObject(object) {
  3407. object.x = this[0];
  3408. object.y = this[1];
  3409. object.z = this[2];
  3410. return object;
  3411. }
  3412. get ELEMENTS() {
  3413. return 3;
  3414. }
  3415. get z() {
  3416. return this[2];
  3417. }
  3418. set z(value) {
  3419. this[2] = checkNumber(value);
  3420. }
  3421. angle(vector) {
  3422. return angle(this, vector);
  3423. }
  3424. cross(vector) {
  3425. cross(this, this, vector);
  3426. return this.check();
  3427. }
  3428. rotateX({
  3429. radians,
  3430. origin = ORIGIN
  3431. }) {
  3432. rotateX$2(this, this, origin, radians);
  3433. return this.check();
  3434. }
  3435. rotateY({
  3436. radians,
  3437. origin = ORIGIN
  3438. }) {
  3439. rotateY$2(this, this, origin, radians);
  3440. return this.check();
  3441. }
  3442. rotateZ({
  3443. radians,
  3444. origin = ORIGIN
  3445. }) {
  3446. rotateZ$2(this, this, origin, radians);
  3447. return this.check();
  3448. }
  3449. transform(matrix4) {
  3450. return this.transformAsPoint(matrix4);
  3451. }
  3452. transformAsPoint(matrix4) {
  3453. transformMat4$1(this, this, matrix4);
  3454. return this.check();
  3455. }
  3456. transformAsVector(matrix4) {
  3457. vec3_transformMat4AsVector(this, this, matrix4);
  3458. return this.check();
  3459. }
  3460. transformByMatrix3(matrix3) {
  3461. transformMat3(this, this, matrix3);
  3462. return this.check();
  3463. }
  3464. transformByMatrix2(matrix2) {
  3465. vec3_transformMat2(this, this, matrix2);
  3466. return this.check();
  3467. }
  3468. transformByQuaternion(quaternion) {
  3469. transformQuat$1(this, this, quaternion);
  3470. return this.check();
  3471. }
  3472. }
  3473. let ZERO$1;
  3474. class Vector4 extends Vector {
  3475. static get ZERO() {
  3476. if (!ZERO$1) {
  3477. ZERO$1 = new Vector4(0, 0, 0, 0);
  3478. Object.freeze(ZERO$1);
  3479. }
  3480. return ZERO$1;
  3481. }
  3482. constructor(x = 0, y = 0, z = 0, w = 0) {
  3483. super(-0, -0, -0, -0);
  3484. if (isArray(x) && arguments.length === 1) {
  3485. this.copy(x);
  3486. } else {
  3487. if (config.debug) {
  3488. checkNumber(x);
  3489. checkNumber(y);
  3490. checkNumber(z);
  3491. checkNumber(w);
  3492. }
  3493. this[0] = x;
  3494. this[1] = y;
  3495. this[2] = z;
  3496. this[3] = w;
  3497. }
  3498. }
  3499. set(x, y, z, w) {
  3500. this[0] = x;
  3501. this[1] = y;
  3502. this[2] = z;
  3503. this[3] = w;
  3504. return this.check();
  3505. }
  3506. copy(array) {
  3507. this[0] = array[0];
  3508. this[1] = array[1];
  3509. this[2] = array[2];
  3510. this[3] = array[3];
  3511. return this.check();
  3512. }
  3513. fromObject(object) {
  3514. if (config.debug) {
  3515. checkNumber(object.x);
  3516. checkNumber(object.y);
  3517. checkNumber(object.z);
  3518. checkNumber(object.w);
  3519. }
  3520. this[0] = object.x;
  3521. this[1] = object.y;
  3522. this[2] = object.z;
  3523. this[3] = object.w;
  3524. return this;
  3525. }
  3526. toObject(object) {
  3527. object.x = this[0];
  3528. object.y = this[1];
  3529. object.z = this[2];
  3530. object.w = this[3];
  3531. return object;
  3532. }
  3533. get ELEMENTS() {
  3534. return 4;
  3535. }
  3536. get z() {
  3537. return this[2];
  3538. }
  3539. set z(value) {
  3540. this[2] = checkNumber(value);
  3541. }
  3542. get w() {
  3543. return this[3];
  3544. }
  3545. set w(value) {
  3546. this[3] = checkNumber(value);
  3547. }
  3548. transform(matrix4) {
  3549. transformMat4$1(this, this, matrix4);
  3550. return this.check();
  3551. }
  3552. transformByMatrix3(matrix3) {
  3553. vec4_transformMat3(this, this, matrix3);
  3554. return this.check();
  3555. }
  3556. transformByMatrix2(matrix2) {
  3557. vec4_transformMat2(this, this, matrix2);
  3558. return this.check();
  3559. }
  3560. transformByQuaternion(quaternion) {
  3561. transformQuat$1(this, this, quaternion);
  3562. return this.check();
  3563. }
  3564. applyMatrix4(m) {
  3565. m.transform(this, this);
  3566. return this;
  3567. }
  3568. }
  3569. class Matrix extends MathArray {
  3570. toString() {
  3571. let string = '[';
  3572. if (config.printRowMajor) {
  3573. string += 'row-major:';
  3574. for (let row = 0; row < this.RANK; ++row) {
  3575. for (let col = 0; col < this.RANK; ++col) {
  3576. string += " ".concat(this[col * this.RANK + row]);
  3577. }
  3578. }
  3579. } else {
  3580. string += 'column-major:';
  3581. for (let i = 0; i < this.ELEMENTS; ++i) {
  3582. string += " ".concat(this[i]);
  3583. }
  3584. }
  3585. string += ']';
  3586. return string;
  3587. }
  3588. getElementIndex(row, col) {
  3589. return col * this.RANK + row;
  3590. }
  3591. getElement(row, col) {
  3592. return this[col * this.RANK + row];
  3593. }
  3594. setElement(row, col, value) {
  3595. this[col * this.RANK + row] = checkNumber(value);
  3596. return this;
  3597. }
  3598. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3599. const firstIndex = columnIndex * this.RANK;
  3600. for (let i = 0; i < this.RANK; ++i) {
  3601. result[i] = this[firstIndex + i];
  3602. }
  3603. return result;
  3604. }
  3605. setColumn(columnIndex, columnVector) {
  3606. const firstIndex = columnIndex * this.RANK;
  3607. for (let i = 0; i < this.RANK; ++i) {
  3608. this[firstIndex + i] = columnVector[i];
  3609. }
  3610. return this;
  3611. }
  3612. }
  3613. /**
  3614. * 3x3 Matrix
  3615. * @module mat3
  3616. */
  3617. /**
  3618. * Creates a new identity mat3
  3619. *
  3620. * @returns {mat3} a new 3x3 matrix
  3621. */
  3622. function create$2() {
  3623. var out = new ARRAY_TYPE(9);
  3624. if (ARRAY_TYPE != Float32Array) {
  3625. out[1] = 0;
  3626. out[2] = 0;
  3627. out[3] = 0;
  3628. out[5] = 0;
  3629. out[6] = 0;
  3630. out[7] = 0;
  3631. }
  3632. out[0] = 1;
  3633. out[4] = 1;
  3634. out[8] = 1;
  3635. return out;
  3636. }
  3637. /**
  3638. * Transpose the values of a mat3
  3639. *
  3640. * @param {mat3} out the receiving matrix
  3641. * @param {ReadonlyMat3} a the source matrix
  3642. * @returns {mat3} out
  3643. */
  3644. function transpose$1(out, a) {
  3645. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3646. if (out === a) {
  3647. var a01 = a[1],
  3648. a02 = a[2],
  3649. a12 = a[5];
  3650. out[1] = a[3];
  3651. out[2] = a[6];
  3652. out[3] = a01;
  3653. out[5] = a[7];
  3654. out[6] = a02;
  3655. out[7] = a12;
  3656. } else {
  3657. out[0] = a[0];
  3658. out[1] = a[3];
  3659. out[2] = a[6];
  3660. out[3] = a[1];
  3661. out[4] = a[4];
  3662. out[5] = a[7];
  3663. out[6] = a[2];
  3664. out[7] = a[5];
  3665. out[8] = a[8];
  3666. }
  3667. return out;
  3668. }
  3669. /**
  3670. * Inverts a mat3
  3671. *
  3672. * @param {mat3} out the receiving matrix
  3673. * @param {ReadonlyMat3} a the source matrix
  3674. * @returns {mat3} out
  3675. */
  3676. function invert$2(out, a) {
  3677. var a00 = a[0],
  3678. a01 = a[1],
  3679. a02 = a[2];
  3680. var a10 = a[3],
  3681. a11 = a[4],
  3682. a12 = a[5];
  3683. var a20 = a[6],
  3684. a21 = a[7],
  3685. a22 = a[8];
  3686. var b01 = a22 * a11 - a12 * a21;
  3687. var b11 = -a22 * a10 + a12 * a20;
  3688. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3689. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3690. if (!det) {
  3691. return null;
  3692. }
  3693. det = 1.0 / det;
  3694. out[0] = b01 * det;
  3695. out[1] = (-a22 * a01 + a02 * a21) * det;
  3696. out[2] = (a12 * a01 - a02 * a11) * det;
  3697. out[3] = b11 * det;
  3698. out[4] = (a22 * a00 - a02 * a20) * det;
  3699. out[5] = (-a12 * a00 + a02 * a10) * det;
  3700. out[6] = b21 * det;
  3701. out[7] = (-a21 * a00 + a01 * a20) * det;
  3702. out[8] = (a11 * a00 - a01 * a10) * det;
  3703. return out;
  3704. }
  3705. /**
  3706. * Calculates the determinant of a mat3
  3707. *
  3708. * @param {ReadonlyMat3} a the source matrix
  3709. * @returns {Number} determinant of a
  3710. */
  3711. function determinant$1(a) {
  3712. var a00 = a[0],
  3713. a01 = a[1],
  3714. a02 = a[2];
  3715. var a10 = a[3],
  3716. a11 = a[4],
  3717. a12 = a[5];
  3718. var a20 = a[6],
  3719. a21 = a[7],
  3720. a22 = a[8];
  3721. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3722. }
  3723. /**
  3724. * Multiplies two mat3's
  3725. *
  3726. * @param {mat3} out the receiving matrix
  3727. * @param {ReadonlyMat3} a the first operand
  3728. * @param {ReadonlyMat3} b the second operand
  3729. * @returns {mat3} out
  3730. */
  3731. function multiply$2(out, a, b) {
  3732. var a00 = a[0],
  3733. a01 = a[1],
  3734. a02 = a[2];
  3735. var a10 = a[3],
  3736. a11 = a[4],
  3737. a12 = a[5];
  3738. var a20 = a[6],
  3739. a21 = a[7],
  3740. a22 = a[8];
  3741. var b00 = b[0],
  3742. b01 = b[1],
  3743. b02 = b[2];
  3744. var b10 = b[3],
  3745. b11 = b[4],
  3746. b12 = b[5];
  3747. var b20 = b[6],
  3748. b21 = b[7],
  3749. b22 = b[8];
  3750. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3751. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3752. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3753. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3754. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3755. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3756. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3757. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3758. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3759. return out;
  3760. }
  3761. /**
  3762. * Translate a mat3 by the given vector
  3763. *
  3764. * @param {mat3} out the receiving matrix
  3765. * @param {ReadonlyMat3} a the matrix to translate
  3766. * @param {ReadonlyVec2} v vector to translate by
  3767. * @returns {mat3} out
  3768. */
  3769. function translate$1(out, a, v) {
  3770. var a00 = a[0],
  3771. a01 = a[1],
  3772. a02 = a[2],
  3773. a10 = a[3],
  3774. a11 = a[4],
  3775. a12 = a[5],
  3776. a20 = a[6],
  3777. a21 = a[7],
  3778. a22 = a[8],
  3779. x = v[0],
  3780. y = v[1];
  3781. out[0] = a00;
  3782. out[1] = a01;
  3783. out[2] = a02;
  3784. out[3] = a10;
  3785. out[4] = a11;
  3786. out[5] = a12;
  3787. out[6] = x * a00 + y * a10 + a20;
  3788. out[7] = x * a01 + y * a11 + a21;
  3789. out[8] = x * a02 + y * a12 + a22;
  3790. return out;
  3791. }
  3792. /**
  3793. * Rotates a mat3 by the given angle
  3794. *
  3795. * @param {mat3} out the receiving matrix
  3796. * @param {ReadonlyMat3} a the matrix to rotate
  3797. * @param {Number} rad the angle to rotate the matrix by
  3798. * @returns {mat3} out
  3799. */
  3800. function rotate$1(out, a, rad) {
  3801. var a00 = a[0],
  3802. a01 = a[1],
  3803. a02 = a[2],
  3804. a10 = a[3],
  3805. a11 = a[4],
  3806. a12 = a[5],
  3807. a20 = a[6],
  3808. a21 = a[7],
  3809. a22 = a[8],
  3810. s = Math.sin(rad),
  3811. c = Math.cos(rad);
  3812. out[0] = c * a00 + s * a10;
  3813. out[1] = c * a01 + s * a11;
  3814. out[2] = c * a02 + s * a12;
  3815. out[3] = c * a10 - s * a00;
  3816. out[4] = c * a11 - s * a01;
  3817. out[5] = c * a12 - s * a02;
  3818. out[6] = a20;
  3819. out[7] = a21;
  3820. out[8] = a22;
  3821. return out;
  3822. }
  3823. /**
  3824. * Scales the mat3 by the dimensions in the given vec2
  3825. *
  3826. * @param {mat3} out the receiving matrix
  3827. * @param {ReadonlyMat3} a the matrix to rotate
  3828. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3829. * @returns {mat3} out
  3830. **/
  3831. function scale$3(out, a, v) {
  3832. var x = v[0],
  3833. y = v[1];
  3834. out[0] = x * a[0];
  3835. out[1] = x * a[1];
  3836. out[2] = x * a[2];
  3837. out[3] = y * a[3];
  3838. out[4] = y * a[4];
  3839. out[5] = y * a[5];
  3840. out[6] = a[6];
  3841. out[7] = a[7];
  3842. out[8] = a[8];
  3843. return out;
  3844. }
  3845. /**
  3846. * Calculates a 3x3 matrix from the given quaternion
  3847. *
  3848. * @param {mat3} out mat3 receiving operation result
  3849. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3850. *
  3851. * @returns {mat3} out
  3852. */
  3853. function fromQuat$1(out, q) {
  3854. var x = q[0],
  3855. y = q[1],
  3856. z = q[2],
  3857. w = q[3];
  3858. var x2 = x + x;
  3859. var y2 = y + y;
  3860. var z2 = z + z;
  3861. var xx = x * x2;
  3862. var yx = y * x2;
  3863. var yy = y * y2;
  3864. var zx = z * x2;
  3865. var zy = z * y2;
  3866. var zz = z * z2;
  3867. var wx = w * x2;
  3868. var wy = w * y2;
  3869. var wz = w * z2;
  3870. out[0] = 1 - yy - zz;
  3871. out[3] = yx - wz;
  3872. out[6] = zx + wy;
  3873. out[1] = yx + wz;
  3874. out[4] = 1 - xx - zz;
  3875. out[7] = zy - wx;
  3876. out[2] = zx - wy;
  3877. out[5] = zy + wx;
  3878. out[8] = 1 - xx - yy;
  3879. return out;
  3880. }
  3881. var INDICES$1;
  3882. (function (INDICES) {
  3883. INDICES[INDICES["COL0ROW0"] = 0] = "COL0ROW0";
  3884. INDICES[INDICES["COL0ROW1"] = 1] = "COL0ROW1";
  3885. INDICES[INDICES["COL0ROW2"] = 2] = "COL0ROW2";
  3886. INDICES[INDICES["COL1ROW0"] = 3] = "COL1ROW0";
  3887. INDICES[INDICES["COL1ROW1"] = 4] = "COL1ROW1";
  3888. INDICES[INDICES["COL1ROW2"] = 5] = "COL1ROW2";
  3889. INDICES[INDICES["COL2ROW0"] = 6] = "COL2ROW0";
  3890. INDICES[INDICES["COL2ROW1"] = 7] = "COL2ROW1";
  3891. INDICES[INDICES["COL2ROW2"] = 8] = "COL2ROW2";
  3892. })(INDICES$1 || (INDICES$1 = {}));
  3893. const IDENTITY_MATRIX$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3894. class Matrix3 extends Matrix {
  3895. static get IDENTITY() {
  3896. return getIdentityMatrix$1();
  3897. }
  3898. static get ZERO() {
  3899. return getZeroMatrix$1();
  3900. }
  3901. get ELEMENTS() {
  3902. return 9;
  3903. }
  3904. get RANK() {
  3905. return 3;
  3906. }
  3907. get INDICES() {
  3908. return INDICES$1;
  3909. }
  3910. constructor(array, ...args) {
  3911. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3912. if (arguments.length === 1 && Array.isArray(array)) {
  3913. this.copy(array);
  3914. } else if (args.length > 0) {
  3915. this.copy([array, ...args]);
  3916. } else {
  3917. this.identity();
  3918. }
  3919. }
  3920. copy(array) {
  3921. this[0] = array[0];
  3922. this[1] = array[1];
  3923. this[2] = array[2];
  3924. this[3] = array[3];
  3925. this[4] = array[4];
  3926. this[5] = array[5];
  3927. this[6] = array[6];
  3928. this[7] = array[7];
  3929. this[8] = array[8];
  3930. return this.check();
  3931. }
  3932. identity() {
  3933. return this.copy(IDENTITY_MATRIX$1);
  3934. }
  3935. fromObject(object) {
  3936. return this.check();
  3937. }
  3938. fromQuaternion(q) {
  3939. fromQuat$1(this, q);
  3940. return this.check();
  3941. }
  3942. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3943. this[0] = m00;
  3944. this[1] = m10;
  3945. this[2] = m20;
  3946. this[3] = m01;
  3947. this[4] = m11;
  3948. this[5] = m21;
  3949. this[6] = m02;
  3950. this[7] = m12;
  3951. this[8] = m22;
  3952. return this.check();
  3953. }
  3954. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3955. this[0] = m00;
  3956. this[1] = m10;
  3957. this[2] = m20;
  3958. this[3] = m01;
  3959. this[4] = m11;
  3960. this[5] = m21;
  3961. this[6] = m02;
  3962. this[7] = m12;
  3963. this[8] = m22;
  3964. return this.check();
  3965. }
  3966. determinant() {
  3967. return determinant$1(this);
  3968. }
  3969. transpose() {
  3970. transpose$1(this, this);
  3971. return this.check();
  3972. }
  3973. invert() {
  3974. invert$2(this, this);
  3975. return this.check();
  3976. }
  3977. multiplyLeft(a) {
  3978. multiply$2(this, a, this);
  3979. return this.check();
  3980. }
  3981. multiplyRight(a) {
  3982. multiply$2(this, this, a);
  3983. return this.check();
  3984. }
  3985. rotate(radians) {
  3986. rotate$1(this, this, radians);
  3987. return this.check();
  3988. }
  3989. scale(factor) {
  3990. if (Array.isArray(factor)) {
  3991. scale$3(this, this, factor);
  3992. } else {
  3993. scale$3(this, this, [factor, factor]);
  3994. }
  3995. return this.check();
  3996. }
  3997. translate(vec) {
  3998. translate$1(this, this, vec);
  3999. return this.check();
  4000. }
  4001. transform(vector, result) {
  4002. let out;
  4003. switch (vector.length) {
  4004. case 2:
  4005. out = transformMat3$1(result || [-0, -0], vector, this);
  4006. break;
  4007. case 3:
  4008. out = transformMat3(result || [-0, -0, -0], vector, this);
  4009. break;
  4010. case 4:
  4011. out = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  4012. break;
  4013. default:
  4014. throw new Error('Illegal vector');
  4015. }
  4016. checkVector(out, vector.length);
  4017. return out;
  4018. }
  4019. transformVector(vector, result) {
  4020. return this.transform(vector, result);
  4021. }
  4022. transformVector2(vector, result) {
  4023. return this.transform(vector, result);
  4024. }
  4025. transformVector3(vector, result) {
  4026. return this.transform(vector, result);
  4027. }
  4028. }
  4029. let ZERO_MATRIX3;
  4030. let IDENTITY_MATRIX3;
  4031. function getZeroMatrix$1() {
  4032. if (!ZERO_MATRIX3) {
  4033. ZERO_MATRIX3 = new Matrix3([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4034. Object.freeze(ZERO_MATRIX3);
  4035. }
  4036. return ZERO_MATRIX3;
  4037. }
  4038. function getIdentityMatrix$1() {
  4039. if (!IDENTITY_MATRIX3) {
  4040. IDENTITY_MATRIX3 = new Matrix3();
  4041. Object.freeze(IDENTITY_MATRIX3);
  4042. }
  4043. return IDENTITY_MATRIX3;
  4044. }
  4045. /**
  4046. * Set a mat4 to the identity matrix
  4047. *
  4048. * @param {mat4} out the receiving matrix
  4049. * @returns {mat4} out
  4050. */
  4051. function identity$2(out) {
  4052. out[0] = 1;
  4053. out[1] = 0;
  4054. out[2] = 0;
  4055. out[3] = 0;
  4056. out[4] = 0;
  4057. out[5] = 1;
  4058. out[6] = 0;
  4059. out[7] = 0;
  4060. out[8] = 0;
  4061. out[9] = 0;
  4062. out[10] = 1;
  4063. out[11] = 0;
  4064. out[12] = 0;
  4065. out[13] = 0;
  4066. out[14] = 0;
  4067. out[15] = 1;
  4068. return out;
  4069. }
  4070. /**
  4071. * Transpose the values of a mat4
  4072. *
  4073. * @param {mat4} out the receiving matrix
  4074. * @param {ReadonlyMat4} a the source matrix
  4075. * @returns {mat4} out
  4076. */
  4077. function transpose(out, a) {
  4078. // If we are transposing ourselves we can skip a few steps but have to cache some values
  4079. if (out === a) {
  4080. var a01 = a[1],
  4081. a02 = a[2],
  4082. a03 = a[3];
  4083. var a12 = a[6],
  4084. a13 = a[7];
  4085. var a23 = a[11];
  4086. out[1] = a[4];
  4087. out[2] = a[8];
  4088. out[3] = a[12];
  4089. out[4] = a01;
  4090. out[6] = a[9];
  4091. out[7] = a[13];
  4092. out[8] = a02;
  4093. out[9] = a12;
  4094. out[11] = a[14];
  4095. out[12] = a03;
  4096. out[13] = a13;
  4097. out[14] = a23;
  4098. } else {
  4099. out[0] = a[0];
  4100. out[1] = a[4];
  4101. out[2] = a[8];
  4102. out[3] = a[12];
  4103. out[4] = a[1];
  4104. out[5] = a[5];
  4105. out[6] = a[9];
  4106. out[7] = a[13];
  4107. out[8] = a[2];
  4108. out[9] = a[6];
  4109. out[10] = a[10];
  4110. out[11] = a[14];
  4111. out[12] = a[3];
  4112. out[13] = a[7];
  4113. out[14] = a[11];
  4114. out[15] = a[15];
  4115. }
  4116. return out;
  4117. }
  4118. /**
  4119. * Inverts a mat4
  4120. *
  4121. * @param {mat4} out the receiving matrix
  4122. * @param {ReadonlyMat4} a the source matrix
  4123. * @returns {mat4} out
  4124. */
  4125. function invert$1(out, a) {
  4126. var a00 = a[0],
  4127. a01 = a[1],
  4128. a02 = a[2],
  4129. a03 = a[3];
  4130. var a10 = a[4],
  4131. a11 = a[5],
  4132. a12 = a[6],
  4133. a13 = a[7];
  4134. var a20 = a[8],
  4135. a21 = a[9],
  4136. a22 = a[10],
  4137. a23 = a[11];
  4138. var a30 = a[12],
  4139. a31 = a[13],
  4140. a32 = a[14],
  4141. a33 = a[15];
  4142. var b00 = a00 * a11 - a01 * a10;
  4143. var b01 = a00 * a12 - a02 * a10;
  4144. var b02 = a00 * a13 - a03 * a10;
  4145. var b03 = a01 * a12 - a02 * a11;
  4146. var b04 = a01 * a13 - a03 * a11;
  4147. var b05 = a02 * a13 - a03 * a12;
  4148. var b06 = a20 * a31 - a21 * a30;
  4149. var b07 = a20 * a32 - a22 * a30;
  4150. var b08 = a20 * a33 - a23 * a30;
  4151. var b09 = a21 * a32 - a22 * a31;
  4152. var b10 = a21 * a33 - a23 * a31;
  4153. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4154. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4155. if (!det) {
  4156. return null;
  4157. }
  4158. det = 1.0 / det;
  4159. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  4160. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  4161. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4162. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4163. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4164. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4165. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4166. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4167. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4168. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4169. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4170. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4171. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4172. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4173. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4174. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4175. return out;
  4176. }
  4177. /**
  4178. * Calculates the determinant of a mat4
  4179. *
  4180. * @param {ReadonlyMat4} a the source matrix
  4181. * @returns {Number} determinant of a
  4182. */
  4183. function determinant(a) {
  4184. var a00 = a[0],
  4185. a01 = a[1],
  4186. a02 = a[2],
  4187. a03 = a[3];
  4188. var a10 = a[4],
  4189. a11 = a[5],
  4190. a12 = a[6],
  4191. a13 = a[7];
  4192. var a20 = a[8],
  4193. a21 = a[9],
  4194. a22 = a[10],
  4195. a23 = a[11];
  4196. var a30 = a[12],
  4197. a31 = a[13],
  4198. a32 = a[14],
  4199. a33 = a[15];
  4200. var b00 = a00 * a11 - a01 * a10;
  4201. var b01 = a00 * a12 - a02 * a10;
  4202. var b02 = a00 * a13 - a03 * a10;
  4203. var b03 = a01 * a12 - a02 * a11;
  4204. var b04 = a01 * a13 - a03 * a11;
  4205. var b05 = a02 * a13 - a03 * a12;
  4206. var b06 = a20 * a31 - a21 * a30;
  4207. var b07 = a20 * a32 - a22 * a30;
  4208. var b08 = a20 * a33 - a23 * a30;
  4209. var b09 = a21 * a32 - a22 * a31;
  4210. var b10 = a21 * a33 - a23 * a31;
  4211. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4212. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4213. }
  4214. /**
  4215. * Multiplies two mat4s
  4216. *
  4217. * @param {mat4} out the receiving matrix
  4218. * @param {ReadonlyMat4} a the first operand
  4219. * @param {ReadonlyMat4} b the second operand
  4220. * @returns {mat4} out
  4221. */
  4222. function multiply$1(out, a, b) {
  4223. var a00 = a[0],
  4224. a01 = a[1],
  4225. a02 = a[2],
  4226. a03 = a[3];
  4227. var a10 = a[4],
  4228. a11 = a[5],
  4229. a12 = a[6],
  4230. a13 = a[7];
  4231. var a20 = a[8],
  4232. a21 = a[9],
  4233. a22 = a[10],
  4234. a23 = a[11];
  4235. var a30 = a[12],
  4236. a31 = a[13],
  4237. a32 = a[14],
  4238. a33 = a[15]; // Cache only the current line of the second matrix
  4239. var b0 = b[0],
  4240. b1 = b[1],
  4241. b2 = b[2],
  4242. b3 = b[3];
  4243. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4244. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4245. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4246. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4247. b0 = b[4];
  4248. b1 = b[5];
  4249. b2 = b[6];
  4250. b3 = b[7];
  4251. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4252. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4253. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4254. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4255. b0 = b[8];
  4256. b1 = b[9];
  4257. b2 = b[10];
  4258. b3 = b[11];
  4259. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4260. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4261. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4262. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4263. b0 = b[12];
  4264. b1 = b[13];
  4265. b2 = b[14];
  4266. b3 = b[15];
  4267. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4268. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4269. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4270. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4271. return out;
  4272. }
  4273. /**
  4274. * Translate a mat4 by the given vector
  4275. *
  4276. * @param {mat4} out the receiving matrix
  4277. * @param {ReadonlyMat4} a the matrix to translate
  4278. * @param {ReadonlyVec3} v vector to translate by
  4279. * @returns {mat4} out
  4280. */
  4281. function translate(out, a, v) {
  4282. var x = v[0],
  4283. y = v[1],
  4284. z = v[2];
  4285. var a00, a01, a02, a03;
  4286. var a10, a11, a12, a13;
  4287. var a20, a21, a22, a23;
  4288. if (a === out) {
  4289. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4290. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4291. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4292. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4293. } else {
  4294. a00 = a[0];
  4295. a01 = a[1];
  4296. a02 = a[2];
  4297. a03 = a[3];
  4298. a10 = a[4];
  4299. a11 = a[5];
  4300. a12 = a[6];
  4301. a13 = a[7];
  4302. a20 = a[8];
  4303. a21 = a[9];
  4304. a22 = a[10];
  4305. a23 = a[11];
  4306. out[0] = a00;
  4307. out[1] = a01;
  4308. out[2] = a02;
  4309. out[3] = a03;
  4310. out[4] = a10;
  4311. out[5] = a11;
  4312. out[6] = a12;
  4313. out[7] = a13;
  4314. out[8] = a20;
  4315. out[9] = a21;
  4316. out[10] = a22;
  4317. out[11] = a23;
  4318. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4319. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4320. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4321. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4322. }
  4323. return out;
  4324. }
  4325. /**
  4326. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4327. *
  4328. * @param {mat4} out the receiving matrix
  4329. * @param {ReadonlyMat4} a the matrix to scale
  4330. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4331. * @returns {mat4} out
  4332. **/
  4333. function scale$2(out, a, v) {
  4334. var x = v[0],
  4335. y = v[1],
  4336. z = v[2];
  4337. out[0] = a[0] * x;
  4338. out[1] = a[1] * x;
  4339. out[2] = a[2] * x;
  4340. out[3] = a[3] * x;
  4341. out[4] = a[4] * y;
  4342. out[5] = a[5] * y;
  4343. out[6] = a[6] * y;
  4344. out[7] = a[7] * y;
  4345. out[8] = a[8] * z;
  4346. out[9] = a[9] * z;
  4347. out[10] = a[10] * z;
  4348. out[11] = a[11] * z;
  4349. out[12] = a[12];
  4350. out[13] = a[13];
  4351. out[14] = a[14];
  4352. out[15] = a[15];
  4353. return out;
  4354. }
  4355. /**
  4356. * Rotates a mat4 by the given angle around the given axis
  4357. *
  4358. * @param {mat4} out the receiving matrix
  4359. * @param {ReadonlyMat4} a the matrix to rotate
  4360. * @param {Number} rad the angle to rotate the matrix by
  4361. * @param {ReadonlyVec3} axis the axis to rotate around
  4362. * @returns {mat4} out
  4363. */
  4364. function rotate(out, a, rad, axis) {
  4365. var x = axis[0],
  4366. y = axis[1],
  4367. z = axis[2];
  4368. var len = Math.hypot(x, y, z);
  4369. var s, c, t;
  4370. var a00, a01, a02, a03;
  4371. var a10, a11, a12, a13;
  4372. var a20, a21, a22, a23;
  4373. var b00, b01, b02;
  4374. var b10, b11, b12;
  4375. var b20, b21, b22;
  4376. if (len < EPSILON) {
  4377. return null;
  4378. }
  4379. len = 1 / len;
  4380. x *= len;
  4381. y *= len;
  4382. z *= len;
  4383. s = Math.sin(rad);
  4384. c = Math.cos(rad);
  4385. t = 1 - c;
  4386. a00 = a[0];
  4387. a01 = a[1];
  4388. a02 = a[2];
  4389. a03 = a[3];
  4390. a10 = a[4];
  4391. a11 = a[5];
  4392. a12 = a[6];
  4393. a13 = a[7];
  4394. a20 = a[8];
  4395. a21 = a[9];
  4396. a22 = a[10];
  4397. a23 = a[11]; // Construct the elements of the rotation matrix
  4398. b00 = x * x * t + c;
  4399. b01 = y * x * t + z * s;
  4400. b02 = z * x * t - y * s;
  4401. b10 = x * y * t - z * s;
  4402. b11 = y * y * t + c;
  4403. b12 = z * y * t + x * s;
  4404. b20 = x * z * t + y * s;
  4405. b21 = y * z * t - x * s;
  4406. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4407. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4408. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4409. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4410. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4411. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4412. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4413. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4414. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4415. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4416. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4417. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4418. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4419. if (a !== out) {
  4420. // If the source and destination differ, copy the unchanged last row
  4421. out[12] = a[12];
  4422. out[13] = a[13];
  4423. out[14] = a[14];
  4424. out[15] = a[15];
  4425. }
  4426. return out;
  4427. }
  4428. /**
  4429. * Rotates a matrix by the given angle around the X axis
  4430. *
  4431. * @param {mat4} out the receiving matrix
  4432. * @param {ReadonlyMat4} a the matrix to rotate
  4433. * @param {Number} rad the angle to rotate the matrix by
  4434. * @returns {mat4} out
  4435. */
  4436. function rotateX$1(out, a, rad) {
  4437. var s = Math.sin(rad);
  4438. var c = Math.cos(rad);
  4439. var a10 = a[4];
  4440. var a11 = a[5];
  4441. var a12 = a[6];
  4442. var a13 = a[7];
  4443. var a20 = a[8];
  4444. var a21 = a[9];
  4445. var a22 = a[10];
  4446. var a23 = a[11];
  4447. if (a !== out) {
  4448. // If the source and destination differ, copy the unchanged rows
  4449. out[0] = a[0];
  4450. out[1] = a[1];
  4451. out[2] = a[2];
  4452. out[3] = a[3];
  4453. out[12] = a[12];
  4454. out[13] = a[13];
  4455. out[14] = a[14];
  4456. out[15] = a[15];
  4457. } // Perform axis-specific matrix multiplication
  4458. out[4] = a10 * c + a20 * s;
  4459. out[5] = a11 * c + a21 * s;
  4460. out[6] = a12 * c + a22 * s;
  4461. out[7] = a13 * c + a23 * s;
  4462. out[8] = a20 * c - a10 * s;
  4463. out[9] = a21 * c - a11 * s;
  4464. out[10] = a22 * c - a12 * s;
  4465. out[11] = a23 * c - a13 * s;
  4466. return out;
  4467. }
  4468. /**
  4469. * Rotates a matrix by the given angle around the Y axis
  4470. *
  4471. * @param {mat4} out the receiving matrix
  4472. * @param {ReadonlyMat4} a the matrix to rotate
  4473. * @param {Number} rad the angle to rotate the matrix by
  4474. * @returns {mat4} out
  4475. */
  4476. function rotateY$1(out, a, rad) {
  4477. var s = Math.sin(rad);
  4478. var c = Math.cos(rad);
  4479. var a00 = a[0];
  4480. var a01 = a[1];
  4481. var a02 = a[2];
  4482. var a03 = a[3];
  4483. var a20 = a[8];
  4484. var a21 = a[9];
  4485. var a22 = a[10];
  4486. var a23 = a[11];
  4487. if (a !== out) {
  4488. // If the source and destination differ, copy the unchanged rows
  4489. out[4] = a[4];
  4490. out[5] = a[5];
  4491. out[6] = a[6];
  4492. out[7] = a[7];
  4493. out[12] = a[12];
  4494. out[13] = a[13];
  4495. out[14] = a[14];
  4496. out[15] = a[15];
  4497. } // Perform axis-specific matrix multiplication
  4498. out[0] = a00 * c - a20 * s;
  4499. out[1] = a01 * c - a21 * s;
  4500. out[2] = a02 * c - a22 * s;
  4501. out[3] = a03 * c - a23 * s;
  4502. out[8] = a00 * s + a20 * c;
  4503. out[9] = a01 * s + a21 * c;
  4504. out[10] = a02 * s + a22 * c;
  4505. out[11] = a03 * s + a23 * c;
  4506. return out;
  4507. }
  4508. /**
  4509. * Rotates a matrix by the given angle around the Z axis
  4510. *
  4511. * @param {mat4} out the receiving matrix
  4512. * @param {ReadonlyMat4} a the matrix to rotate
  4513. * @param {Number} rad the angle to rotate the matrix by
  4514. * @returns {mat4} out
  4515. */
  4516. function rotateZ$1(out, a, rad) {
  4517. var s = Math.sin(rad);
  4518. var c = Math.cos(rad);
  4519. var a00 = a[0];
  4520. var a01 = a[1];
  4521. var a02 = a[2];
  4522. var a03 = a[3];
  4523. var a10 = a[4];
  4524. var a11 = a[5];
  4525. var a12 = a[6];
  4526. var a13 = a[7];
  4527. if (a !== out) {
  4528. // If the source and destination differ, copy the unchanged last row
  4529. out[8] = a[8];
  4530. out[9] = a[9];
  4531. out[10] = a[10];
  4532. out[11] = a[11];
  4533. out[12] = a[12];
  4534. out[13] = a[13];
  4535. out[14] = a[14];
  4536. out[15] = a[15];
  4537. } // Perform axis-specific matrix multiplication
  4538. out[0] = a00 * c + a10 * s;
  4539. out[1] = a01 * c + a11 * s;
  4540. out[2] = a02 * c + a12 * s;
  4541. out[3] = a03 * c + a13 * s;
  4542. out[4] = a10 * c - a00 * s;
  4543. out[5] = a11 * c - a01 * s;
  4544. out[6] = a12 * c - a02 * s;
  4545. out[7] = a13 * c - a03 * s;
  4546. return out;
  4547. }
  4548. /**
  4549. * Returns the scaling factor component of a transformation
  4550. * matrix. If a matrix is built with fromRotationTranslationScale
  4551. * with a normalized Quaternion paramter, the returned vector will be
  4552. * the same as the scaling vector
  4553. * originally supplied.
  4554. * @param {vec3} out Vector to receive scaling factor component
  4555. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4556. * @return {vec3} out
  4557. */
  4558. function getScaling(out, mat) {
  4559. var m11 = mat[0];
  4560. var m12 = mat[1];
  4561. var m13 = mat[2];
  4562. var m21 = mat[4];
  4563. var m22 = mat[5];
  4564. var m23 = mat[6];
  4565. var m31 = mat[8];
  4566. var m32 = mat[9];
  4567. var m33 = mat[10];
  4568. out[0] = Math.hypot(m11, m12, m13);
  4569. out[1] = Math.hypot(m21, m22, m23);
  4570. out[2] = Math.hypot(m31, m32, m33);
  4571. return out;
  4572. }
  4573. /**
  4574. * Calculates a 4x4 matrix from the given quaternion
  4575. *
  4576. * @param {mat4} out mat4 receiving operation result
  4577. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4578. *
  4579. * @returns {mat4} out
  4580. */
  4581. function fromQuat(out, q) {
  4582. var x = q[0],
  4583. y = q[1],
  4584. z = q[2],
  4585. w = q[3];
  4586. var x2 = x + x;
  4587. var y2 = y + y;
  4588. var z2 = z + z;
  4589. var xx = x * x2;
  4590. var yx = y * x2;
  4591. var yy = y * y2;
  4592. var zx = z * x2;
  4593. var zy = z * y2;
  4594. var zz = z * z2;
  4595. var wx = w * x2;
  4596. var wy = w * y2;
  4597. var wz = w * z2;
  4598. out[0] = 1 - yy - zz;
  4599. out[1] = yx + wz;
  4600. out[2] = zx - wy;
  4601. out[3] = 0;
  4602. out[4] = yx - wz;
  4603. out[5] = 1 - xx - zz;
  4604. out[6] = zy + wx;
  4605. out[7] = 0;
  4606. out[8] = zx + wy;
  4607. out[9] = zy - wx;
  4608. out[10] = 1 - xx - yy;
  4609. out[11] = 0;
  4610. out[12] = 0;
  4611. out[13] = 0;
  4612. out[14] = 0;
  4613. out[15] = 1;
  4614. return out;
  4615. }
  4616. /**
  4617. * Generates a frustum matrix with the given bounds
  4618. *
  4619. * @param {mat4} out mat4 frustum matrix will be written into
  4620. * @param {Number} left Left bound of the frustum
  4621. * @param {Number} right Right bound of the frustum
  4622. * @param {Number} bottom Bottom bound of the frustum
  4623. * @param {Number} top Top bound of the frustum
  4624. * @param {Number} near Near bound of the frustum
  4625. * @param {Number} far Far bound of the frustum
  4626. * @returns {mat4} out
  4627. */
  4628. function frustum(out, left, right, bottom, top, near, far) {
  4629. var rl = 1 / (right - left);
  4630. var tb = 1 / (top - bottom);
  4631. var nf = 1 / (near - far);
  4632. out[0] = near * 2 * rl;
  4633. out[1] = 0;
  4634. out[2] = 0;
  4635. out[3] = 0;
  4636. out[4] = 0;
  4637. out[5] = near * 2 * tb;
  4638. out[6] = 0;
  4639. out[7] = 0;
  4640. out[8] = (right + left) * rl;
  4641. out[9] = (top + bottom) * tb;
  4642. out[10] = (far + near) * nf;
  4643. out[11] = -1;
  4644. out[12] = 0;
  4645. out[13] = 0;
  4646. out[14] = far * near * 2 * nf;
  4647. out[15] = 0;
  4648. return out;
  4649. }
  4650. /**
  4651. * Generates a perspective projection matrix with the given bounds.
  4652. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  4653. * which matches WebGL/OpenGL's clip volume.
  4654. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4655. *
  4656. * @param {mat4} out mat4 frustum matrix will be written into
  4657. * @param {number} fovy Vertical field of view in radians
  4658. * @param {number} aspect Aspect ratio. typically viewport width/height
  4659. * @param {number} near Near bound of the frustum
  4660. * @param {number} far Far bound of the frustum, can be null or Infinity
  4661. * @returns {mat4} out
  4662. */
  4663. function perspectiveNO(out, fovy, aspect, near, far) {
  4664. var f = 1.0 / Math.tan(fovy / 2),
  4665. nf;
  4666. out[0] = f / aspect;
  4667. out[1] = 0;
  4668. out[2] = 0;
  4669. out[3] = 0;
  4670. out[4] = 0;
  4671. out[5] = f;
  4672. out[6] = 0;
  4673. out[7] = 0;
  4674. out[8] = 0;
  4675. out[9] = 0;
  4676. out[11] = -1;
  4677. out[12] = 0;
  4678. out[13] = 0;
  4679. out[15] = 0;
  4680. if (far != null && far !== Infinity) {
  4681. nf = 1 / (near - far);
  4682. out[10] = (far + near) * nf;
  4683. out[14] = 2 * far * near * nf;
  4684. } else {
  4685. out[10] = -1;
  4686. out[14] = -2 * near;
  4687. }
  4688. return out;
  4689. }
  4690. /**
  4691. * Alias for {@link mat4.perspectiveNO}
  4692. * @function
  4693. */
  4694. var perspective = perspectiveNO;
  4695. /**
  4696. * Generates a orthogonal projection matrix with the given bounds.
  4697. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  4698. * which matches WebGL/OpenGL's clip volume.
  4699. *
  4700. * @param {mat4} out mat4 frustum matrix will be written into
  4701. * @param {number} left Left bound of the frustum
  4702. * @param {number} right Right bound of the frustum
  4703. * @param {number} bottom Bottom bound of the frustum
  4704. * @param {number} top Top bound of the frustum
  4705. * @param {number} near Near bound of the frustum
  4706. * @param {number} far Far bound of the frustum
  4707. * @returns {mat4} out
  4708. */
  4709. function orthoNO(out, left, right, bottom, top, near, far) {
  4710. var lr = 1 / (left - right);
  4711. var bt = 1 / (bottom - top);
  4712. var nf = 1 / (near - far);
  4713. out[0] = -2 * lr;
  4714. out[1] = 0;
  4715. out[2] = 0;
  4716. out[3] = 0;
  4717. out[4] = 0;
  4718. out[5] = -2 * bt;
  4719. out[6] = 0;
  4720. out[7] = 0;
  4721. out[8] = 0;
  4722. out[9] = 0;
  4723. out[10] = 2 * nf;
  4724. out[11] = 0;
  4725. out[12] = (left + right) * lr;
  4726. out[13] = (top + bottom) * bt;
  4727. out[14] = (far + near) * nf;
  4728. out[15] = 1;
  4729. return out;
  4730. }
  4731. /**
  4732. * Alias for {@link mat4.orthoNO}
  4733. * @function
  4734. */
  4735. var ortho = orthoNO;
  4736. /**
  4737. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4738. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4739. *
  4740. * @param {mat4} out mat4 frustum matrix will be written into
  4741. * @param {ReadonlyVec3} eye Position of the viewer
  4742. * @param {ReadonlyVec3} center Point the viewer is looking at
  4743. * @param {ReadonlyVec3} up vec3 pointing up
  4744. * @returns {mat4} out
  4745. */
  4746. function lookAt(out, eye, center, up) {
  4747. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4748. var eyex = eye[0];
  4749. var eyey = eye[1];
  4750. var eyez = eye[2];
  4751. var upx = up[0];
  4752. var upy = up[1];
  4753. var upz = up[2];
  4754. var centerx = center[0];
  4755. var centery = center[1];
  4756. var centerz = center[2];
  4757. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4758. return identity$2(out);
  4759. }
  4760. z0 = eyex - centerx;
  4761. z1 = eyey - centery;
  4762. z2 = eyez - centerz;
  4763. len = 1 / Math.hypot(z0, z1, z2);
  4764. z0 *= len;
  4765. z1 *= len;
  4766. z2 *= len;
  4767. x0 = upy * z2 - upz * z1;
  4768. x1 = upz * z0 - upx * z2;
  4769. x2 = upx * z1 - upy * z0;
  4770. len = Math.hypot(x0, x1, x2);
  4771. if (!len) {
  4772. x0 = 0;
  4773. x1 = 0;
  4774. x2 = 0;
  4775. } else {
  4776. len = 1 / len;
  4777. x0 *= len;
  4778. x1 *= len;
  4779. x2 *= len;
  4780. }
  4781. y0 = z1 * x2 - z2 * x1;
  4782. y1 = z2 * x0 - z0 * x2;
  4783. y2 = z0 * x1 - z1 * x0;
  4784. len = Math.hypot(y0, y1, y2);
  4785. if (!len) {
  4786. y0 = 0;
  4787. y1 = 0;
  4788. y2 = 0;
  4789. } else {
  4790. len = 1 / len;
  4791. y0 *= len;
  4792. y1 *= len;
  4793. y2 *= len;
  4794. }
  4795. out[0] = x0;
  4796. out[1] = y0;
  4797. out[2] = z0;
  4798. out[3] = 0;
  4799. out[4] = x1;
  4800. out[5] = y1;
  4801. out[6] = z1;
  4802. out[7] = 0;
  4803. out[8] = x2;
  4804. out[9] = y2;
  4805. out[10] = z2;
  4806. out[11] = 0;
  4807. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4808. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4809. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4810. out[15] = 1;
  4811. return out;
  4812. }
  4813. /**
  4814. * 4 Dimensional Vector
  4815. * @module vec4
  4816. */
  4817. /**
  4818. * Creates a new, empty vec4
  4819. *
  4820. * @returns {vec4} a new 4D vector
  4821. */
  4822. function create$1() {
  4823. var out = new ARRAY_TYPE(4);
  4824. if (ARRAY_TYPE != Float32Array) {
  4825. out[0] = 0;
  4826. out[1] = 0;
  4827. out[2] = 0;
  4828. out[3] = 0;
  4829. }
  4830. return out;
  4831. }
  4832. /**
  4833. * Adds two vec4's
  4834. *
  4835. * @param {vec4} out the receiving vector
  4836. * @param {ReadonlyVec4} a the first operand
  4837. * @param {ReadonlyVec4} b the second operand
  4838. * @returns {vec4} out
  4839. */
  4840. function add$1(out, a, b) {
  4841. out[0] = a[0] + b[0];
  4842. out[1] = a[1] + b[1];
  4843. out[2] = a[2] + b[2];
  4844. out[3] = a[3] + b[3];
  4845. return out;
  4846. }
  4847. /**
  4848. * Scales a vec4 by a scalar number
  4849. *
  4850. * @param {vec4} out the receiving vector
  4851. * @param {ReadonlyVec4} a the vector to scale
  4852. * @param {Number} b amount to scale the vector by
  4853. * @returns {vec4} out
  4854. */
  4855. function scale$1(out, a, b) {
  4856. out[0] = a[0] * b;
  4857. out[1] = a[1] * b;
  4858. out[2] = a[2] * b;
  4859. out[3] = a[3] * b;
  4860. return out;
  4861. }
  4862. /**
  4863. * Calculates the length of a vec4
  4864. *
  4865. * @param {ReadonlyVec4} a vector to calculate length of
  4866. * @returns {Number} length of a
  4867. */
  4868. function length$1(a) {
  4869. var x = a[0];
  4870. var y = a[1];
  4871. var z = a[2];
  4872. var w = a[3];
  4873. return Math.hypot(x, y, z, w);
  4874. }
  4875. /**
  4876. * Calculates the squared length of a vec4
  4877. *
  4878. * @param {ReadonlyVec4} a vector to calculate squared length of
  4879. * @returns {Number} squared length of a
  4880. */
  4881. function squaredLength$1(a) {
  4882. var x = a[0];
  4883. var y = a[1];
  4884. var z = a[2];
  4885. var w = a[3];
  4886. return x * x + y * y + z * z + w * w;
  4887. }
  4888. /**
  4889. * Normalize a vec4
  4890. *
  4891. * @param {vec4} out the receiving vector
  4892. * @param {ReadonlyVec4} a vector to normalize
  4893. * @returns {vec4} out
  4894. */
  4895. function normalize$1(out, a) {
  4896. var x = a[0];
  4897. var y = a[1];
  4898. var z = a[2];
  4899. var w = a[3];
  4900. var len = x * x + y * y + z * z + w * w;
  4901. if (len > 0) {
  4902. len = 1 / Math.sqrt(len);
  4903. }
  4904. out[0] = x * len;
  4905. out[1] = y * len;
  4906. out[2] = z * len;
  4907. out[3] = w * len;
  4908. return out;
  4909. }
  4910. /**
  4911. * Calculates the dot product of two vec4's
  4912. *
  4913. * @param {ReadonlyVec4} a the first operand
  4914. * @param {ReadonlyVec4} b the second operand
  4915. * @returns {Number} dot product of a and b
  4916. */
  4917. function dot$1(a, b) {
  4918. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4919. }
  4920. /**
  4921. * Performs a linear interpolation between two vec4's
  4922. *
  4923. * @param {vec4} out the receiving vector
  4924. * @param {ReadonlyVec4} a the first operand
  4925. * @param {ReadonlyVec4} b the second operand
  4926. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4927. * @returns {vec4} out
  4928. */
  4929. function lerp$1(out, a, b, t) {
  4930. var ax = a[0];
  4931. var ay = a[1];
  4932. var az = a[2];
  4933. var aw = a[3];
  4934. out[0] = ax + t * (b[0] - ax);
  4935. out[1] = ay + t * (b[1] - ay);
  4936. out[2] = az + t * (b[2] - az);
  4937. out[3] = aw + t * (b[3] - aw);
  4938. return out;
  4939. }
  4940. /**
  4941. * Transforms the vec4 with a mat4.
  4942. *
  4943. * @param {vec4} out the receiving vector
  4944. * @param {ReadonlyVec4} a the vector to transform
  4945. * @param {ReadonlyMat4} m matrix to transform with
  4946. * @returns {vec4} out
  4947. */
  4948. function transformMat4(out, a, m) {
  4949. var x = a[0],
  4950. y = a[1],
  4951. z = a[2],
  4952. w = a[3];
  4953. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4954. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4955. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4956. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4957. return out;
  4958. }
  4959. /**
  4960. * Transforms the vec4 with a quat
  4961. *
  4962. * @param {vec4} out the receiving vector
  4963. * @param {ReadonlyVec4} a the vector to transform
  4964. * @param {ReadonlyQuat} q quaternion to transform with
  4965. * @returns {vec4} out
  4966. */
  4967. function transformQuat(out, a, q) {
  4968. var x = a[0],
  4969. y = a[1],
  4970. z = a[2];
  4971. var qx = q[0],
  4972. qy = q[1],
  4973. qz = q[2],
  4974. qw = q[3]; // calculate quat * vec
  4975. var ix = qw * x + qy * z - qz * y;
  4976. var iy = qw * y + qz * x - qx * z;
  4977. var iz = qw * z + qx * y - qy * x;
  4978. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4979. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4980. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4981. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4982. out[3] = a[3];
  4983. return out;
  4984. }
  4985. /**
  4986. * Perform some operation over an array of vec4s.
  4987. *
  4988. * @param {Array} a the array of vectors to iterate over
  4989. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4990. * @param {Number} offset Number of elements to skip at the beginning of the array
  4991. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4992. * @param {Function} fn Function to call for each vector in the array
  4993. * @param {Object} [arg] additional argument to pass to fn
  4994. * @returns {Array} a
  4995. * @function
  4996. */
  4997. (function () {
  4998. var vec = create$1();
  4999. return function (a, stride, offset, count, fn, arg) {
  5000. var i, l;
  5001. if (!stride) {
  5002. stride = 4;
  5003. }
  5004. if (!offset) {
  5005. offset = 0;
  5006. }
  5007. if (count) {
  5008. l = Math.min(count * stride + offset, a.length);
  5009. } else {
  5010. l = a.length;
  5011. }
  5012. for (i = offset; i < l; i += stride) {
  5013. vec[0] = a[i];
  5014. vec[1] = a[i + 1];
  5015. vec[2] = a[i + 2];
  5016. vec[3] = a[i + 3];
  5017. fn(vec, vec, arg);
  5018. a[i] = vec[0];
  5019. a[i + 1] = vec[1];
  5020. a[i + 2] = vec[2];
  5021. a[i + 3] = vec[3];
  5022. }
  5023. return a;
  5024. };
  5025. })();
  5026. var INDICES;
  5027. (function (INDICES) {
  5028. INDICES[INDICES["COL0ROW0"] = 0] = "COL0ROW0";
  5029. INDICES[INDICES["COL0ROW1"] = 1] = "COL0ROW1";
  5030. INDICES[INDICES["COL0ROW2"] = 2] = "COL0ROW2";
  5031. INDICES[INDICES["COL0ROW3"] = 3] = "COL0ROW3";
  5032. INDICES[INDICES["COL1ROW0"] = 4] = "COL1ROW0";
  5033. INDICES[INDICES["COL1ROW1"] = 5] = "COL1ROW1";
  5034. INDICES[INDICES["COL1ROW2"] = 6] = "COL1ROW2";
  5035. INDICES[INDICES["COL1ROW3"] = 7] = "COL1ROW3";
  5036. INDICES[INDICES["COL2ROW0"] = 8] = "COL2ROW0";
  5037. INDICES[INDICES["COL2ROW1"] = 9] = "COL2ROW1";
  5038. INDICES[INDICES["COL2ROW2"] = 10] = "COL2ROW2";
  5039. INDICES[INDICES["COL2ROW3"] = 11] = "COL2ROW3";
  5040. INDICES[INDICES["COL3ROW0"] = 12] = "COL3ROW0";
  5041. INDICES[INDICES["COL3ROW1"] = 13] = "COL3ROW1";
  5042. INDICES[INDICES["COL3ROW2"] = 14] = "COL3ROW2";
  5043. INDICES[INDICES["COL3ROW3"] = 15] = "COL3ROW3";
  5044. })(INDICES || (INDICES = {}));
  5045. const DEFAULT_FOVY = 45 * Math.PI / 180;
  5046. const DEFAULT_ASPECT = 1;
  5047. const DEFAULT_NEAR = 0.1;
  5048. const DEFAULT_FAR = 500;
  5049. const IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  5050. class Matrix4 extends Matrix {
  5051. static get IDENTITY() {
  5052. return getIdentityMatrix();
  5053. }
  5054. static get ZERO() {
  5055. return getZeroMatrix();
  5056. }
  5057. get ELEMENTS() {
  5058. return 16;
  5059. }
  5060. get RANK() {
  5061. return 4;
  5062. }
  5063. get INDICES() {
  5064. return INDICES;
  5065. }
  5066. constructor(array) {
  5067. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  5068. if (arguments.length === 1 && Array.isArray(array)) {
  5069. this.copy(array);
  5070. } else {
  5071. this.identity();
  5072. }
  5073. }
  5074. copy(array) {
  5075. this[0] = array[0];
  5076. this[1] = array[1];
  5077. this[2] = array[2];
  5078. this[3] = array[3];
  5079. this[4] = array[4];
  5080. this[5] = array[5];
  5081. this[6] = array[6];
  5082. this[7] = array[7];
  5083. this[8] = array[8];
  5084. this[9] = array[9];
  5085. this[10] = array[10];
  5086. this[11] = array[11];
  5087. this[12] = array[12];
  5088. this[13] = array[13];
  5089. this[14] = array[14];
  5090. this[15] = array[15];
  5091. return this.check();
  5092. }
  5093. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  5094. this[0] = m00;
  5095. this[1] = m10;
  5096. this[2] = m20;
  5097. this[3] = m30;
  5098. this[4] = m01;
  5099. this[5] = m11;
  5100. this[6] = m21;
  5101. this[7] = m31;
  5102. this[8] = m02;
  5103. this[9] = m12;
  5104. this[10] = m22;
  5105. this[11] = m32;
  5106. this[12] = m03;
  5107. this[13] = m13;
  5108. this[14] = m23;
  5109. this[15] = m33;
  5110. return this.check();
  5111. }
  5112. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  5113. this[0] = m00;
  5114. this[1] = m10;
  5115. this[2] = m20;
  5116. this[3] = m30;
  5117. this[4] = m01;
  5118. this[5] = m11;
  5119. this[6] = m21;
  5120. this[7] = m31;
  5121. this[8] = m02;
  5122. this[9] = m12;
  5123. this[10] = m22;
  5124. this[11] = m32;
  5125. this[12] = m03;
  5126. this[13] = m13;
  5127. this[14] = m23;
  5128. this[15] = m33;
  5129. return this.check();
  5130. }
  5131. toRowMajor(result) {
  5132. result[0] = this[0];
  5133. result[1] = this[4];
  5134. result[2] = this[8];
  5135. result[3] = this[12];
  5136. result[4] = this[1];
  5137. result[5] = this[5];
  5138. result[6] = this[9];
  5139. result[7] = this[13];
  5140. result[8] = this[2];
  5141. result[9] = this[6];
  5142. result[10] = this[10];
  5143. result[11] = this[14];
  5144. result[12] = this[3];
  5145. result[13] = this[7];
  5146. result[14] = this[11];
  5147. result[15] = this[15];
  5148. return result;
  5149. }
  5150. identity() {
  5151. return this.copy(IDENTITY_MATRIX);
  5152. }
  5153. fromObject(object) {
  5154. return this.check();
  5155. }
  5156. fromQuaternion(quaternion) {
  5157. fromQuat(this, quaternion);
  5158. return this.check();
  5159. }
  5160. frustum(view) {
  5161. const {
  5162. left,
  5163. right,
  5164. bottom,
  5165. top,
  5166. near = DEFAULT_NEAR,
  5167. far = DEFAULT_FAR
  5168. } = view;
  5169. if (far === Infinity) {
  5170. computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  5171. } else {
  5172. frustum(this, left, right, bottom, top, near, far);
  5173. }
  5174. return this.check();
  5175. }
  5176. lookAt(view) {
  5177. const {
  5178. eye,
  5179. center = [0, 0, 0],
  5180. up = [0, 1, 0]
  5181. } = view;
  5182. lookAt(this, eye, center, up);
  5183. return this.check();
  5184. }
  5185. ortho(view) {
  5186. const {
  5187. left,
  5188. right,
  5189. bottom,
  5190. top,
  5191. near = DEFAULT_NEAR,
  5192. far = DEFAULT_FAR
  5193. } = view;
  5194. ortho(this, left, right, bottom, top, near, far);
  5195. return this.check();
  5196. }
  5197. orthographic(view) {
  5198. const {
  5199. fovy = DEFAULT_FOVY,
  5200. aspect = DEFAULT_ASPECT,
  5201. focalDistance = 1,
  5202. near = DEFAULT_NEAR,
  5203. far = DEFAULT_FAR
  5204. } = view;
  5205. checkRadians(fovy);
  5206. const halfY = fovy / 2;
  5207. const top = focalDistance * Math.tan(halfY);
  5208. const right = top * aspect;
  5209. return this.ortho({
  5210. left: -right,
  5211. right,
  5212. bottom: -top,
  5213. top,
  5214. near,
  5215. far
  5216. });
  5217. }
  5218. perspective(view) {
  5219. const {
  5220. fovy = 45 * Math.PI / 180,
  5221. aspect = 1,
  5222. near = 0.1,
  5223. far = 500
  5224. } = view;
  5225. checkRadians(fovy);
  5226. perspective(this, fovy, aspect, near, far);
  5227. return this.check();
  5228. }
  5229. determinant() {
  5230. return determinant(this);
  5231. }
  5232. getScale(result = [-0, -0, -0]) {
  5233. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5234. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5235. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5236. return result;
  5237. }
  5238. getTranslation(result = [-0, -0, -0]) {
  5239. result[0] = this[12];
  5240. result[1] = this[13];
  5241. result[2] = this[14];
  5242. return result;
  5243. }
  5244. getRotation(result, scaleResult) {
  5245. result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];
  5246. scaleResult = scaleResult || [-0, -0, -0];
  5247. const scale = this.getScale(scaleResult);
  5248. const inverseScale0 = 1 / scale[0];
  5249. const inverseScale1 = 1 / scale[1];
  5250. const inverseScale2 = 1 / scale[2];
  5251. result[0] = this[0] * inverseScale0;
  5252. result[1] = this[1] * inverseScale1;
  5253. result[2] = this[2] * inverseScale2;
  5254. result[3] = 0;
  5255. result[4] = this[4] * inverseScale0;
  5256. result[5] = this[5] * inverseScale1;
  5257. result[6] = this[6] * inverseScale2;
  5258. result[7] = 0;
  5259. result[8] = this[8] * inverseScale0;
  5260. result[9] = this[9] * inverseScale1;
  5261. result[10] = this[10] * inverseScale2;
  5262. result[11] = 0;
  5263. result[12] = 0;
  5264. result[13] = 0;
  5265. result[14] = 0;
  5266. result[15] = 1;
  5267. return result;
  5268. }
  5269. getRotationMatrix3(result, scaleResult) {
  5270. result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0];
  5271. scaleResult = scaleResult || [-0, -0, -0];
  5272. const scale = this.getScale(scaleResult);
  5273. const inverseScale0 = 1 / scale[0];
  5274. const inverseScale1 = 1 / scale[1];
  5275. const inverseScale2 = 1 / scale[2];
  5276. result[0] = this[0] * inverseScale0;
  5277. result[1] = this[1] * inverseScale1;
  5278. result[2] = this[2] * inverseScale2;
  5279. result[3] = this[4] * inverseScale0;
  5280. result[4] = this[5] * inverseScale1;
  5281. result[5] = this[6] * inverseScale2;
  5282. result[6] = this[8] * inverseScale0;
  5283. result[7] = this[9] * inverseScale1;
  5284. result[8] = this[10] * inverseScale2;
  5285. return result;
  5286. }
  5287. transpose() {
  5288. transpose(this, this);
  5289. return this.check();
  5290. }
  5291. invert() {
  5292. invert$1(this, this);
  5293. return this.check();
  5294. }
  5295. multiplyLeft(a) {
  5296. multiply$1(this, a, this);
  5297. return this.check();
  5298. }
  5299. multiplyRight(a) {
  5300. multiply$1(this, this, a);
  5301. return this.check();
  5302. }
  5303. rotateX(radians) {
  5304. rotateX$1(this, this, radians);
  5305. return this.check();
  5306. }
  5307. rotateY(radians) {
  5308. rotateY$1(this, this, radians);
  5309. return this.check();
  5310. }
  5311. rotateZ(radians) {
  5312. rotateZ$1(this, this, radians);
  5313. return this.check();
  5314. }
  5315. rotateXYZ(angleXYZ) {
  5316. return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]);
  5317. }
  5318. rotateAxis(radians, axis) {
  5319. rotate(this, this, radians, axis);
  5320. return this.check();
  5321. }
  5322. scale(factor) {
  5323. scale$2(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]);
  5324. return this.check();
  5325. }
  5326. translate(vector) {
  5327. translate(this, this, vector);
  5328. return this.check();
  5329. }
  5330. transform(vector, result) {
  5331. if (vector.length === 4) {
  5332. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5333. checkVector(result, 4);
  5334. return result;
  5335. }
  5336. return this.transformAsPoint(vector, result);
  5337. }
  5338. transformAsPoint(vector, result) {
  5339. const {
  5340. length
  5341. } = vector;
  5342. let out;
  5343. switch (length) {
  5344. case 2:
  5345. out = transformMat4$2(result || [-0, -0], vector, this);
  5346. break;
  5347. case 3:
  5348. out = transformMat4$1(result || [-0, -0, -0], vector, this);
  5349. break;
  5350. default:
  5351. throw new Error('Illegal vector');
  5352. }
  5353. checkVector(out, vector.length);
  5354. return out;
  5355. }
  5356. transformAsVector(vector, result) {
  5357. let out;
  5358. switch (vector.length) {
  5359. case 2:
  5360. out = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5361. break;
  5362. case 3:
  5363. out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5364. break;
  5365. default:
  5366. throw new Error('Illegal vector');
  5367. }
  5368. checkVector(out, vector.length);
  5369. return out;
  5370. }
  5371. transformPoint(vector, result) {
  5372. return this.transformAsPoint(vector, result);
  5373. }
  5374. transformVector(vector, result) {
  5375. return this.transformAsPoint(vector, result);
  5376. }
  5377. transformDirection(vector, result) {
  5378. return this.transformAsVector(vector, result);
  5379. }
  5380. makeRotationX(radians) {
  5381. return this.identity().rotateX(radians);
  5382. }
  5383. makeTranslation(x, y, z) {
  5384. return this.identity().translate([x, y, z]);
  5385. }
  5386. }
  5387. let ZERO;
  5388. let IDENTITY;
  5389. function getZeroMatrix() {
  5390. if (!ZERO) {
  5391. ZERO = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  5392. Object.freeze(ZERO);
  5393. }
  5394. return ZERO;
  5395. }
  5396. function getIdentityMatrix() {
  5397. if (!IDENTITY) {
  5398. IDENTITY = new Matrix4();
  5399. Object.freeze(IDENTITY);
  5400. }
  5401. return IDENTITY;
  5402. }
  5403. function checkRadians(possiblyDegrees) {
  5404. if (possiblyDegrees > Math.PI * 2) {
  5405. throw Error('expected radians');
  5406. }
  5407. }
  5408. function computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  5409. const column0Row0 = 2 * near / (right - left);
  5410. const column1Row1 = 2 * near / (top - bottom);
  5411. const column2Row0 = (right + left) / (right - left);
  5412. const column2Row1 = (top + bottom) / (top - bottom);
  5413. const column2Row2 = -1;
  5414. const column2Row3 = -1;
  5415. const column3Row2 = -2 * near;
  5416. result[0] = column0Row0;
  5417. result[1] = 0;
  5418. result[2] = 0;
  5419. result[3] = 0;
  5420. result[4] = 0;
  5421. result[5] = column1Row1;
  5422. result[6] = 0;
  5423. result[7] = 0;
  5424. result[8] = column2Row0;
  5425. result[9] = column2Row1;
  5426. result[10] = column2Row2;
  5427. result[11] = column2Row3;
  5428. result[12] = 0;
  5429. result[13] = 0;
  5430. result[14] = column3Row2;
  5431. result[15] = 0;
  5432. return result;
  5433. }
  5434. /**
  5435. * Quaternion
  5436. * @module quat
  5437. */
  5438. /**
  5439. * Creates a new identity quat
  5440. *
  5441. * @returns {quat} a new quaternion
  5442. */
  5443. function create() {
  5444. var out = new ARRAY_TYPE(4);
  5445. if (ARRAY_TYPE != Float32Array) {
  5446. out[0] = 0;
  5447. out[1] = 0;
  5448. out[2] = 0;
  5449. }
  5450. out[3] = 1;
  5451. return out;
  5452. }
  5453. /**
  5454. * Set a quat to the identity quaternion
  5455. *
  5456. * @param {quat} out the receiving quaternion
  5457. * @returns {quat} out
  5458. */
  5459. function identity$1(out) {
  5460. out[0] = 0;
  5461. out[1] = 0;
  5462. out[2] = 0;
  5463. out[3] = 1;
  5464. return out;
  5465. }
  5466. /**
  5467. * Sets a quat from the given angle and rotation axis,
  5468. * then returns it.
  5469. *
  5470. * @param {quat} out the receiving quaternion
  5471. * @param {ReadonlyVec3} axis the axis around which to rotate
  5472. * @param {Number} rad the angle in radians
  5473. * @returns {quat} out
  5474. **/
  5475. function setAxisAngle(out, axis, rad) {
  5476. rad = rad * 0.5;
  5477. var s = Math.sin(rad);
  5478. out[0] = s * axis[0];
  5479. out[1] = s * axis[1];
  5480. out[2] = s * axis[2];
  5481. out[3] = Math.cos(rad);
  5482. return out;
  5483. }
  5484. /**
  5485. * Multiplies two quat's
  5486. *
  5487. * @param {quat} out the receiving quaternion
  5488. * @param {ReadonlyQuat} a the first operand
  5489. * @param {ReadonlyQuat} b the second operand
  5490. * @returns {quat} out
  5491. */
  5492. function multiply(out, a, b) {
  5493. var ax = a[0],
  5494. ay = a[1],
  5495. az = a[2],
  5496. aw = a[3];
  5497. var bx = b[0],
  5498. by = b[1],
  5499. bz = b[2],
  5500. bw = b[3];
  5501. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5502. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5503. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5504. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5505. return out;
  5506. }
  5507. /**
  5508. * Rotates a quaternion by the given angle about the X axis
  5509. *
  5510. * @param {quat} out quat receiving operation result
  5511. * @param {ReadonlyQuat} a quat to rotate
  5512. * @param {number} rad angle (in radians) to rotate
  5513. * @returns {quat} out
  5514. */
  5515. function rotateX(out, a, rad) {
  5516. rad *= 0.5;
  5517. var ax = a[0],
  5518. ay = a[1],
  5519. az = a[2],
  5520. aw = a[3];
  5521. var bx = Math.sin(rad),
  5522. bw = Math.cos(rad);
  5523. out[0] = ax * bw + aw * bx;
  5524. out[1] = ay * bw + az * bx;
  5525. out[2] = az * bw - ay * bx;
  5526. out[3] = aw * bw - ax * bx;
  5527. return out;
  5528. }
  5529. /**
  5530. * Rotates a quaternion by the given angle about the Y axis
  5531. *
  5532. * @param {quat} out quat receiving operation result
  5533. * @param {ReadonlyQuat} a quat to rotate
  5534. * @param {number} rad angle (in radians) to rotate
  5535. * @returns {quat} out
  5536. */
  5537. function rotateY(out, a, rad) {
  5538. rad *= 0.5;
  5539. var ax = a[0],
  5540. ay = a[1],
  5541. az = a[2],
  5542. aw = a[3];
  5543. var by = Math.sin(rad),
  5544. bw = Math.cos(rad);
  5545. out[0] = ax * bw - az * by;
  5546. out[1] = ay * bw + aw * by;
  5547. out[2] = az * bw + ax * by;
  5548. out[3] = aw * bw - ay * by;
  5549. return out;
  5550. }
  5551. /**
  5552. * Rotates a quaternion by the given angle about the Z axis
  5553. *
  5554. * @param {quat} out quat receiving operation result
  5555. * @param {ReadonlyQuat} a quat to rotate
  5556. * @param {number} rad angle (in radians) to rotate
  5557. * @returns {quat} out
  5558. */
  5559. function rotateZ(out, a, rad) {
  5560. rad *= 0.5;
  5561. var ax = a[0],
  5562. ay = a[1],
  5563. az = a[2],
  5564. aw = a[3];
  5565. var bz = Math.sin(rad),
  5566. bw = Math.cos(rad);
  5567. out[0] = ax * bw + ay * bz;
  5568. out[1] = ay * bw - ax * bz;
  5569. out[2] = az * bw + aw * bz;
  5570. out[3] = aw * bw - az * bz;
  5571. return out;
  5572. }
  5573. /**
  5574. * Calculates the W component of a quat from the X, Y, and Z components.
  5575. * Assumes that quaternion is 1 unit in length.
  5576. * Any existing W component will be ignored.
  5577. *
  5578. * @param {quat} out the receiving quaternion
  5579. * @param {ReadonlyQuat} a quat to calculate W component of
  5580. * @returns {quat} out
  5581. */
  5582. function calculateW(out, a) {
  5583. var x = a[0],
  5584. y = a[1],
  5585. z = a[2];
  5586. out[0] = x;
  5587. out[1] = y;
  5588. out[2] = z;
  5589. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5590. return out;
  5591. }
  5592. /**
  5593. * Performs a spherical linear interpolation between two quat
  5594. *
  5595. * @param {quat} out the receiving quaternion
  5596. * @param {ReadonlyQuat} a the first operand
  5597. * @param {ReadonlyQuat} b the second operand
  5598. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5599. * @returns {quat} out
  5600. */
  5601. function slerp(out, a, b, t) {
  5602. // benchmarks:
  5603. // http://jsperf.com/quaternion-slerp-implementations
  5604. var ax = a[0],
  5605. ay = a[1],
  5606. az = a[2],
  5607. aw = a[3];
  5608. var bx = b[0],
  5609. by = b[1],
  5610. bz = b[2],
  5611. bw = b[3];
  5612. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5613. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5614. if (cosom < 0.0) {
  5615. cosom = -cosom;
  5616. bx = -bx;
  5617. by = -by;
  5618. bz = -bz;
  5619. bw = -bw;
  5620. } // calculate coefficients
  5621. if (1.0 - cosom > EPSILON) {
  5622. // standard case (slerp)
  5623. omega = Math.acos(cosom);
  5624. sinom = Math.sin(omega);
  5625. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5626. scale1 = Math.sin(t * omega) / sinom;
  5627. } else {
  5628. // "from" and "to" quaternions are very close
  5629. // ... so we can do a linear interpolation
  5630. scale0 = 1.0 - t;
  5631. scale1 = t;
  5632. } // calculate final values
  5633. out[0] = scale0 * ax + scale1 * bx;
  5634. out[1] = scale0 * ay + scale1 * by;
  5635. out[2] = scale0 * az + scale1 * bz;
  5636. out[3] = scale0 * aw + scale1 * bw;
  5637. return out;
  5638. }
  5639. /**
  5640. * Calculates the inverse of a quat
  5641. *
  5642. * @param {quat} out the receiving quaternion
  5643. * @param {ReadonlyQuat} a quat to calculate inverse of
  5644. * @returns {quat} out
  5645. */
  5646. function invert(out, a) {
  5647. var a0 = a[0],
  5648. a1 = a[1],
  5649. a2 = a[2],
  5650. a3 = a[3];
  5651. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5652. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5653. out[0] = -a0 * invDot;
  5654. out[1] = -a1 * invDot;
  5655. out[2] = -a2 * invDot;
  5656. out[3] = a3 * invDot;
  5657. return out;
  5658. }
  5659. /**
  5660. * Calculates the conjugate of a quat
  5661. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5662. *
  5663. * @param {quat} out the receiving quaternion
  5664. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5665. * @returns {quat} out
  5666. */
  5667. function conjugate(out, a) {
  5668. out[0] = -a[0];
  5669. out[1] = -a[1];
  5670. out[2] = -a[2];
  5671. out[3] = a[3];
  5672. return out;
  5673. }
  5674. /**
  5675. * Creates a quaternion from the given 3x3 rotation matrix.
  5676. *
  5677. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5678. * to renormalize the quaternion yourself where necessary.
  5679. *
  5680. * @param {quat} out the receiving quaternion
  5681. * @param {ReadonlyMat3} m rotation matrix
  5682. * @returns {quat} out
  5683. * @function
  5684. */
  5685. function fromMat3(out, m) {
  5686. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5687. // article "Quaternion Calculus and Fast Animation".
  5688. var fTrace = m[0] + m[4] + m[8];
  5689. var fRoot;
  5690. if (fTrace > 0.0) {
  5691. // |w| > 1/2, may as well choose w > 1/2
  5692. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5693. out[3] = 0.5 * fRoot;
  5694. fRoot = 0.5 / fRoot; // 1/(4w)
  5695. out[0] = (m[5] - m[7]) * fRoot;
  5696. out[1] = (m[6] - m[2]) * fRoot;
  5697. out[2] = (m[1] - m[3]) * fRoot;
  5698. } else {
  5699. // |w| <= 1/2
  5700. var i = 0;
  5701. if (m[4] > m[0]) i = 1;
  5702. if (m[8] > m[i * 3 + i]) i = 2;
  5703. var j = (i + 1) % 3;
  5704. var k = (i + 2) % 3;
  5705. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5706. out[i] = 0.5 * fRoot;
  5707. fRoot = 0.5 / fRoot;
  5708. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5709. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5710. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5711. }
  5712. return out;
  5713. }
  5714. /**
  5715. * Adds two quat's
  5716. *
  5717. * @param {quat} out the receiving quaternion
  5718. * @param {ReadonlyQuat} a the first operand
  5719. * @param {ReadonlyQuat} b the second operand
  5720. * @returns {quat} out
  5721. * @function
  5722. */
  5723. var add = add$1;
  5724. /**
  5725. * Scales a quat by a scalar number
  5726. *
  5727. * @param {quat} out the receiving vector
  5728. * @param {ReadonlyQuat} a the vector to scale
  5729. * @param {Number} b amount to scale the vector by
  5730. * @returns {quat} out
  5731. * @function
  5732. */
  5733. var scale = scale$1;
  5734. /**
  5735. * Calculates the dot product of two quat's
  5736. *
  5737. * @param {ReadonlyQuat} a the first operand
  5738. * @param {ReadonlyQuat} b the second operand
  5739. * @returns {Number} dot product of a and b
  5740. * @function
  5741. */
  5742. var dot = dot$1;
  5743. /**
  5744. * Performs a linear interpolation between two quat's
  5745. *
  5746. * @param {quat} out the receiving quaternion
  5747. * @param {ReadonlyQuat} a the first operand
  5748. * @param {ReadonlyQuat} b the second operand
  5749. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5750. * @returns {quat} out
  5751. * @function
  5752. */
  5753. var lerp = lerp$1;
  5754. /**
  5755. * Calculates the length of a quat
  5756. *
  5757. * @param {ReadonlyQuat} a vector to calculate length of
  5758. * @returns {Number} length of a
  5759. */
  5760. var length = length$1;
  5761. /**
  5762. * Calculates the squared length of a quat
  5763. *
  5764. * @param {ReadonlyQuat} a vector to calculate squared length of
  5765. * @returns {Number} squared length of a
  5766. * @function
  5767. */
  5768. var squaredLength = squaredLength$1;
  5769. /**
  5770. * Normalize a quat
  5771. *
  5772. * @param {quat} out the receiving quaternion
  5773. * @param {ReadonlyQuat} a quaternion to normalize
  5774. * @returns {quat} out
  5775. * @function
  5776. */
  5777. var normalize = normalize$1;
  5778. /**
  5779. * Sets a quaternion to represent the shortest rotation from one
  5780. * vector to another.
  5781. *
  5782. * Both vectors are assumed to be unit length.
  5783. *
  5784. * @param {quat} out the receiving quaternion.
  5785. * @param {ReadonlyVec3} a the initial vector
  5786. * @param {ReadonlyVec3} b the destination vector
  5787. * @returns {quat} out
  5788. */
  5789. var rotationTo = function () {
  5790. var tmpvec3 = create$3();
  5791. var xUnitVec3 = fromValues(1, 0, 0);
  5792. var yUnitVec3 = fromValues(0, 1, 0);
  5793. return function (out, a, b) {
  5794. var dot = dot$2(a, b);
  5795. if (dot < -0.999999) {
  5796. cross(tmpvec3, xUnitVec3, a);
  5797. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5798. normalize$2(tmpvec3, tmpvec3);
  5799. setAxisAngle(out, tmpvec3, Math.PI);
  5800. return out;
  5801. } else if (dot > 0.999999) {
  5802. out[0] = 0;
  5803. out[1] = 0;
  5804. out[2] = 0;
  5805. out[3] = 1;
  5806. return out;
  5807. } else {
  5808. cross(tmpvec3, a, b);
  5809. out[0] = tmpvec3[0];
  5810. out[1] = tmpvec3[1];
  5811. out[2] = tmpvec3[2];
  5812. out[3] = 1 + dot;
  5813. return normalize(out, out);
  5814. }
  5815. };
  5816. }();
  5817. /**
  5818. * Performs a spherical linear interpolation with two control points
  5819. *
  5820. * @param {quat} out the receiving quaternion
  5821. * @param {ReadonlyQuat} a the first operand
  5822. * @param {ReadonlyQuat} b the second operand
  5823. * @param {ReadonlyQuat} c the third operand
  5824. * @param {ReadonlyQuat} d the fourth operand
  5825. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5826. * @returns {quat} out
  5827. */
  5828. (function () {
  5829. var temp1 = create();
  5830. var temp2 = create();
  5831. return function (out, a, b, c, d, t) {
  5832. slerp(temp1, a, d, t);
  5833. slerp(temp2, b, c, t);
  5834. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5835. return out;
  5836. };
  5837. })();
  5838. /**
  5839. * Sets the specified quaternion with values corresponding to the given
  5840. * axes. Each axis is a vec3 and is expected to be unit length and
  5841. * perpendicular to all other specified axes.
  5842. *
  5843. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5844. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5845. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5846. * @returns {quat} out
  5847. */
  5848. (function () {
  5849. var matr = create$2();
  5850. return function (out, view, right, up) {
  5851. matr[0] = right[0];
  5852. matr[3] = right[1];
  5853. matr[6] = right[2];
  5854. matr[1] = up[0];
  5855. matr[4] = up[1];
  5856. matr[7] = up[2];
  5857. matr[2] = -view[0];
  5858. matr[5] = -view[1];
  5859. matr[8] = -view[2];
  5860. return normalize(out, fromMat3(out, matr));
  5861. };
  5862. })();
  5863. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5864. class Quaternion extends MathArray {
  5865. constructor(x = 0, y = 0, z = 0, w = 1) {
  5866. super(-0, -0, -0, -0);
  5867. if (Array.isArray(x) && arguments.length === 1) {
  5868. this.copy(x);
  5869. } else {
  5870. this.set(x, y, z, w);
  5871. }
  5872. }
  5873. copy(array) {
  5874. this[0] = array[0];
  5875. this[1] = array[1];
  5876. this[2] = array[2];
  5877. this[3] = array[3];
  5878. return this.check();
  5879. }
  5880. set(x, y, z, w) {
  5881. this[0] = x;
  5882. this[1] = y;
  5883. this[2] = z;
  5884. this[3] = w;
  5885. return this.check();
  5886. }
  5887. fromObject(object) {
  5888. this[0] = object.x;
  5889. this[1] = object.y;
  5890. this[2] = object.z;
  5891. this[3] = object.w;
  5892. return this.check();
  5893. }
  5894. fromMatrix3(m) {
  5895. fromMat3(this, m);
  5896. return this.check();
  5897. }
  5898. fromAxisRotation(axis, rad) {
  5899. setAxisAngle(this, axis, rad);
  5900. return this.check();
  5901. }
  5902. identity() {
  5903. identity$1(this);
  5904. return this.check();
  5905. }
  5906. setAxisAngle(axis, rad) {
  5907. return this.fromAxisRotation(axis, rad);
  5908. }
  5909. get ELEMENTS() {
  5910. return 4;
  5911. }
  5912. get x() {
  5913. return this[0];
  5914. }
  5915. set x(value) {
  5916. this[0] = checkNumber(value);
  5917. }
  5918. get y() {
  5919. return this[1];
  5920. }
  5921. set y(value) {
  5922. this[1] = checkNumber(value);
  5923. }
  5924. get z() {
  5925. return this[2];
  5926. }
  5927. set z(value) {
  5928. this[2] = checkNumber(value);
  5929. }
  5930. get w() {
  5931. return this[3];
  5932. }
  5933. set w(value) {
  5934. this[3] = checkNumber(value);
  5935. }
  5936. len() {
  5937. return length(this);
  5938. }
  5939. lengthSquared() {
  5940. return squaredLength(this);
  5941. }
  5942. dot(a) {
  5943. return dot(this, a);
  5944. }
  5945. rotationTo(vectorA, vectorB) {
  5946. rotationTo(this, vectorA, vectorB);
  5947. return this.check();
  5948. }
  5949. add(a) {
  5950. add(this, this, a);
  5951. return this.check();
  5952. }
  5953. calculateW() {
  5954. calculateW(this, this);
  5955. return this.check();
  5956. }
  5957. conjugate() {
  5958. conjugate(this, this);
  5959. return this.check();
  5960. }
  5961. invert() {
  5962. invert(this, this);
  5963. return this.check();
  5964. }
  5965. lerp(a, b, t) {
  5966. if (t === undefined) {
  5967. return this.lerp(this, a, b);
  5968. }
  5969. lerp(this, a, b, t);
  5970. return this.check();
  5971. }
  5972. multiplyRight(a) {
  5973. multiply(this, this, a);
  5974. return this.check();
  5975. }
  5976. multiplyLeft(a) {
  5977. multiply(this, a, this);
  5978. return this.check();
  5979. }
  5980. normalize() {
  5981. const length = this.len();
  5982. const l = length > 0 ? 1 / length : 0;
  5983. this[0] = this[0] * l;
  5984. this[1] = this[1] * l;
  5985. this[2] = this[2] * l;
  5986. this[3] = this[3] * l;
  5987. if (length === 0) {
  5988. this[3] = 1;
  5989. }
  5990. return this.check();
  5991. }
  5992. rotateX(rad) {
  5993. rotateX(this, this, rad);
  5994. return this.check();
  5995. }
  5996. rotateY(rad) {
  5997. rotateY(this, this, rad);
  5998. return this.check();
  5999. }
  6000. rotateZ(rad) {
  6001. rotateZ(this, this, rad);
  6002. return this.check();
  6003. }
  6004. scale(b) {
  6005. scale(this, this, b);
  6006. return this.check();
  6007. }
  6008. slerp(arg0, arg1, arg2) {
  6009. let start;
  6010. let target;
  6011. let ratio;
  6012. switch (arguments.length) {
  6013. case 1:
  6014. ({
  6015. start = IDENTITY_QUATERNION,
  6016. target,
  6017. ratio
  6018. } = arg0);
  6019. break;
  6020. case 2:
  6021. start = this;
  6022. target = arg0;
  6023. ratio = arg1;
  6024. break;
  6025. default:
  6026. start = arg0;
  6027. target = arg1;
  6028. ratio = arg2;
  6029. }
  6030. slerp(this, start, target, ratio);
  6031. return this.check();
  6032. }
  6033. transformVector4(vector, result = new Vector4()) {
  6034. transformQuat(result, vector, this);
  6035. return checkVector(result, 4);
  6036. }
  6037. lengthSq() {
  6038. return this.lengthSquared();
  6039. }
  6040. setFromAxisAngle(axis, rad) {
  6041. return this.setAxisAngle(axis, rad);
  6042. }
  6043. premultiply(a) {
  6044. return this.multiplyLeft(a);
  6045. }
  6046. multiply(a) {
  6047. return this.multiplyRight(a);
  6048. }
  6049. }
  6050. var _MathUtils = {
  6051. EPSILON1: 1e-1,
  6052. EPSILON2: 1e-2,
  6053. EPSILON3: 1e-3,
  6054. EPSILON4: 1e-4,
  6055. EPSILON5: 1e-5,
  6056. EPSILON6: 1e-6,
  6057. EPSILON7: 1e-7,
  6058. EPSILON8: 1e-8,
  6059. EPSILON9: 1e-9,
  6060. EPSILON10: 1e-10,
  6061. EPSILON11: 1e-11,
  6062. EPSILON12: 1e-12,
  6063. EPSILON13: 1e-13,
  6064. EPSILON14: 1e-14,
  6065. EPSILON15: 1e-15,
  6066. EPSILON16: 1e-16,
  6067. EPSILON17: 1e-17,
  6068. EPSILON18: 1e-18,
  6069. EPSILON19: 1e-19,
  6070. EPSILON20: 1e-20,
  6071. PI_OVER_TWO: Math.PI / 2,
  6072. PI_OVER_FOUR: Math.PI / 4,
  6073. PI_OVER_SIX: Math.PI / 6,
  6074. TWO_PI: Math.PI * 2
  6075. };
  6076. const WGS84_RADIUS_X$1 = 6378137.0;
  6077. const WGS84_RADIUS_Y$1 = 6378137.0;
  6078. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  6079. function identity(x) {
  6080. return x;
  6081. }
  6082. new Vector3();
  6083. function fromCartographic(cartographic, result = [], map = identity) {
  6084. if ('longitude' in cartographic) {
  6085. result[0] = map(cartographic.longitude);
  6086. result[1] = map(cartographic.latitude);
  6087. result[2] = cartographic.height;
  6088. } else if ('x' in cartographic) {
  6089. result[0] = map(cartographic.x);
  6090. result[1] = map(cartographic.y);
  6091. result[2] = cartographic.z;
  6092. } else {
  6093. result[0] = map(cartographic[0]);
  6094. result[1] = map(cartographic[1]);
  6095. result[2] = cartographic[2];
  6096. }
  6097. return result;
  6098. }
  6099. function fromCartographicToRadians(cartographic, vector = []) {
  6100. return fromCartographic(cartographic, vector, config._cartographicRadians ? identity : toRadians);
  6101. }
  6102. function toCartographic(vector, cartographic, map = identity) {
  6103. if ('longitude' in cartographic) {
  6104. cartographic.longitude = map(vector[0]);
  6105. cartographic.latitude = map(vector[1]);
  6106. cartographic.height = vector[2];
  6107. } else if ('x' in cartographic) {
  6108. cartographic.x = map(vector[0]);
  6109. cartographic.y = map(vector[1]);
  6110. cartographic.z = vector[2];
  6111. } else {
  6112. cartographic[0] = map(vector[0]);
  6113. cartographic[1] = map(vector[1]);
  6114. cartographic[2] = vector[2];
  6115. }
  6116. return cartographic;
  6117. }
  6118. function toCartographicFromRadians(vector, cartographic) {
  6119. return toCartographic(vector, cartographic, config._cartographicRadians ? identity : toDegrees);
  6120. }
  6121. const scratchVector$5 = new Vector3();
  6122. const scaleToGeodeticSurfaceIntersection = new Vector3();
  6123. const scaleToGeodeticSurfaceGradient = new Vector3();
  6124. function scaleToGeodeticSurface(cartesian, ellipsoid, result = []) {
  6125. const {
  6126. oneOverRadii,
  6127. oneOverRadiiSquared,
  6128. centerToleranceSquared
  6129. } = ellipsoid;
  6130. scratchVector$5.from(cartesian);
  6131. const positionX = scratchVector$5.x;
  6132. const positionY = scratchVector$5.y;
  6133. const positionZ = scratchVector$5.z;
  6134. const oneOverRadiiX = oneOverRadii.x;
  6135. const oneOverRadiiY = oneOverRadii.y;
  6136. const oneOverRadiiZ = oneOverRadii.z;
  6137. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  6138. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  6139. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  6140. const squaredNorm = x2 + y2 + z2;
  6141. const ratio = Math.sqrt(1.0 / squaredNorm);
  6142. if (!Number.isFinite(ratio)) {
  6143. return undefined;
  6144. }
  6145. const intersection = scaleToGeodeticSurfaceIntersection;
  6146. intersection.copy(cartesian).scale(ratio);
  6147. if (squaredNorm < centerToleranceSquared) {
  6148. return intersection.to(result);
  6149. }
  6150. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  6151. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  6152. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  6153. const gradient = scaleToGeodeticSurfaceGradient;
  6154. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  6155. let lambda = (1.0 - ratio) * scratchVector$5.len() / (0.5 * gradient.len());
  6156. let correction = 0.0;
  6157. let xMultiplier;
  6158. let yMultiplier;
  6159. let zMultiplier;
  6160. let func;
  6161. do {
  6162. lambda -= correction;
  6163. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  6164. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  6165. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  6166. const xMultiplier2 = xMultiplier * xMultiplier;
  6167. const yMultiplier2 = yMultiplier * yMultiplier;
  6168. const zMultiplier2 = zMultiplier * zMultiplier;
  6169. const xMultiplier3 = xMultiplier2 * xMultiplier;
  6170. const yMultiplier3 = yMultiplier2 * yMultiplier;
  6171. const zMultiplier3 = zMultiplier2 * zMultiplier;
  6172. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  6173. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  6174. const derivative = -2.0 * denominator;
  6175. correction = func / derivative;
  6176. } while (Math.abs(func) > _MathUtils.EPSILON12);
  6177. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  6178. }
  6179. const EPSILON14 = 1e-14;
  6180. const scratchOrigin = new Vector3();
  6181. const VECTOR_PRODUCT_LOCAL_FRAME = {
  6182. up: {
  6183. south: 'east',
  6184. north: 'west',
  6185. west: 'south',
  6186. east: 'north'
  6187. },
  6188. down: {
  6189. south: 'west',
  6190. north: 'east',
  6191. west: 'north',
  6192. east: 'south'
  6193. },
  6194. south: {
  6195. up: 'west',
  6196. down: 'east',
  6197. west: 'down',
  6198. east: 'up'
  6199. },
  6200. north: {
  6201. up: 'east',
  6202. down: 'west',
  6203. west: 'up',
  6204. east: 'down'
  6205. },
  6206. west: {
  6207. up: 'north',
  6208. down: 'south',
  6209. north: 'down',
  6210. south: 'up'
  6211. },
  6212. east: {
  6213. up: 'south',
  6214. down: 'north',
  6215. north: 'up',
  6216. south: 'down'
  6217. }
  6218. };
  6219. const degeneratePositionLocalFrame = {
  6220. north: [-1, 0, 0],
  6221. east: [0, 1, 0],
  6222. up: [0, 0, 1],
  6223. south: [1, 0, 0],
  6224. west: [0, -1, 0],
  6225. down: [0, 0, -1]
  6226. };
  6227. const scratchAxisVectors = {
  6228. east: new Vector3(),
  6229. north: new Vector3(),
  6230. up: new Vector3(),
  6231. west: new Vector3(),
  6232. south: new Vector3(),
  6233. down: new Vector3()
  6234. };
  6235. const scratchVector1 = new Vector3();
  6236. const scratchVector2$1 = new Vector3();
  6237. const scratchVector3$1 = new Vector3();
  6238. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6239. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6240. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6241. let firstAxisVector;
  6242. let secondAxisVector;
  6243. let thirdAxisVector;
  6244. const origin = scratchOrigin.copy(cartesianOrigin);
  6245. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6246. if (atPole) {
  6247. const sign = Math.sign(origin.z);
  6248. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6249. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6250. firstAxisVector.scale(sign);
  6251. }
  6252. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6253. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6254. secondAxisVector.scale(sign);
  6255. }
  6256. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6257. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6258. thirdAxisVector.scale(sign);
  6259. }
  6260. } else {
  6261. const {
  6262. up,
  6263. east,
  6264. north
  6265. } = scratchAxisVectors;
  6266. east.set(-origin.y, origin.x, 0.0).normalize();
  6267. ellipsoid.geodeticSurfaceNormal(origin, up);
  6268. north.copy(up).cross(east);
  6269. const {
  6270. down,
  6271. west,
  6272. south
  6273. } = scratchAxisVectors;
  6274. down.copy(up).scale(-1);
  6275. west.copy(east).scale(-1);
  6276. south.copy(north).scale(-1);
  6277. firstAxisVector = scratchAxisVectors[firstAxis];
  6278. secondAxisVector = scratchAxisVectors[secondAxis];
  6279. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6280. }
  6281. result[0] = firstAxisVector.x;
  6282. result[1] = firstAxisVector.y;
  6283. result[2] = firstAxisVector.z;
  6284. result[3] = 0.0;
  6285. result[4] = secondAxisVector.x;
  6286. result[5] = secondAxisVector.y;
  6287. result[6] = secondAxisVector.z;
  6288. result[7] = 0.0;
  6289. result[8] = thirdAxisVector.x;
  6290. result[9] = thirdAxisVector.y;
  6291. result[10] = thirdAxisVector.z;
  6292. result[11] = 0.0;
  6293. result[12] = origin.x;
  6294. result[13] = origin.y;
  6295. result[14] = origin.z;
  6296. result[15] = 1.0;
  6297. return result;
  6298. }
  6299. const scratchVector$4 = new Vector3();
  6300. const scratchNormal$2 = new Vector3();
  6301. const scratchK = new Vector3();
  6302. const scratchPosition$2 = new Vector3();
  6303. const scratchHeight = new Vector3();
  6304. const scratchCartesian = new Vector3();
  6305. class Ellipsoid {
  6306. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6307. _defineProperty(this, "radii", void 0);
  6308. _defineProperty(this, "radiiSquared", void 0);
  6309. _defineProperty(this, "radiiToTheFourth", void 0);
  6310. _defineProperty(this, "oneOverRadii", void 0);
  6311. _defineProperty(this, "oneOverRadiiSquared", void 0);
  6312. _defineProperty(this, "minimumRadius", void 0);
  6313. _defineProperty(this, "maximumRadius", void 0);
  6314. _defineProperty(this, "centerToleranceSquared", _MathUtils.EPSILON1);
  6315. _defineProperty(this, "squaredXOverSquaredZ", void 0);
  6316. assert$4(x >= 0.0);
  6317. assert$4(y >= 0.0);
  6318. assert$4(z >= 0.0);
  6319. this.radii = new Vector3(x, y, z);
  6320. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6321. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6322. this.oneOverRadii = new Vector3(x === 0.0 ? 0.0 : 1.0 / x, y === 0.0 ? 0.0 : 1.0 / y, z === 0.0 ? 0.0 : 1.0 / z);
  6323. this.oneOverRadiiSquared = new Vector3(x === 0.0 ? 0.0 : 1.0 / (x * x), y === 0.0 ? 0.0 : 1.0 / (y * y), z === 0.0 ? 0.0 : 1.0 / (z * z));
  6324. this.minimumRadius = Math.min(x, y, z);
  6325. this.maximumRadius = Math.max(x, y, z);
  6326. if (this.radiiSquared.z !== 0) {
  6327. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6328. }
  6329. Object.freeze(this);
  6330. }
  6331. equals(right) {
  6332. return this === right || Boolean(right && this.radii.equals(right.radii));
  6333. }
  6334. toString() {
  6335. return this.radii.toString();
  6336. }
  6337. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6338. const normal = scratchNormal$2;
  6339. const k = scratchK;
  6340. const [,, height] = cartographic;
  6341. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6342. k.copy(this.radiiSquared).scale(normal);
  6343. const gamma = Math.sqrt(normal.dot(k));
  6344. k.scale(1 / gamma);
  6345. normal.scale(height);
  6346. k.add(normal);
  6347. return k.to(result);
  6348. }
  6349. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6350. scratchCartesian.from(cartesian);
  6351. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6352. if (!point) {
  6353. return undefined;
  6354. }
  6355. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6356. const h = scratchHeight;
  6357. h.copy(scratchCartesian).subtract(point);
  6358. const longitude = Math.atan2(normal.y, normal.x);
  6359. const latitude = Math.asin(normal.z);
  6360. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6361. return toCartographicFromRadians([longitude, latitude, height], result);
  6362. }
  6363. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6364. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6365. }
  6366. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6367. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6368. }
  6369. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6370. return scratchVector$4.from(cartesian).normalize().to(result);
  6371. }
  6372. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6373. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6374. const longitude = cartographicVectorRadians[0];
  6375. const latitude = cartographicVectorRadians[1];
  6376. const cosLatitude = Math.cos(latitude);
  6377. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6378. return scratchVector$4.to(result);
  6379. }
  6380. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6381. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6382. }
  6383. scaleToGeodeticSurface(cartesian, result) {
  6384. return scaleToGeodeticSurface(cartesian, this, result);
  6385. }
  6386. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6387. scratchPosition$2.from(cartesian);
  6388. const positionX = scratchPosition$2.x;
  6389. const positionY = scratchPosition$2.y;
  6390. const positionZ = scratchPosition$2.z;
  6391. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6392. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6393. return scratchPosition$2.multiplyScalar(beta).to(result);
  6394. }
  6395. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6396. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6397. }
  6398. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6399. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6400. }
  6401. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0, result = [0, 0, 0]) {
  6402. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6403. assert$4(this.radii.z > 0);
  6404. scratchPosition$2.from(position);
  6405. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6406. if (Math.abs(z) >= this.radii.z - buffer) {
  6407. return undefined;
  6408. }
  6409. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6410. }
  6411. }
  6412. _defineProperty(Ellipsoid, "WGS84", new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1));
  6413. class DoublyLinkedListNode {
  6414. constructor(item, previous, next) {
  6415. _defineProperty(this, "item", void 0);
  6416. _defineProperty(this, "previous", void 0);
  6417. _defineProperty(this, "next", void 0);
  6418. this.item = item;
  6419. this.previous = previous;
  6420. this.next = next;
  6421. }
  6422. }
  6423. class DoublyLinkedList {
  6424. constructor() {
  6425. _defineProperty(this, "head", null);
  6426. _defineProperty(this, "tail", null);
  6427. _defineProperty(this, "_length", 0);
  6428. }
  6429. get length() {
  6430. return this._length;
  6431. }
  6432. add(item) {
  6433. const node = new DoublyLinkedListNode(item, this.tail, null);
  6434. if (this.tail) {
  6435. this.tail.next = node;
  6436. this.tail = node;
  6437. } else {
  6438. this.head = node;
  6439. this.tail = node;
  6440. }
  6441. ++this._length;
  6442. return node;
  6443. }
  6444. remove(node) {
  6445. if (!node) {
  6446. return;
  6447. }
  6448. if (node.previous && node.next) {
  6449. node.previous.next = node.next;
  6450. node.next.previous = node.previous;
  6451. } else if (node.previous) {
  6452. node.previous.next = null;
  6453. this.tail = node.previous;
  6454. } else if (node.next) {
  6455. node.next.previous = null;
  6456. this.head = node.next;
  6457. } else {
  6458. this.head = null;
  6459. this.tail = null;
  6460. }
  6461. node.next = null;
  6462. node.previous = null;
  6463. --this._length;
  6464. }
  6465. splice(node, nextNode) {
  6466. if (node === nextNode) {
  6467. return;
  6468. }
  6469. this.remove(nextNode);
  6470. this._insert(node, nextNode);
  6471. }
  6472. _insert(node, nextNode) {
  6473. const oldNodeNext = node.next;
  6474. node.next = nextNode;
  6475. if (this.tail === node) {
  6476. this.tail = nextNode;
  6477. } else {
  6478. oldNodeNext.previous = nextNode;
  6479. }
  6480. nextNode.next = oldNodeNext;
  6481. nextNode.previous = node;
  6482. ++this._length;
  6483. }
  6484. }
  6485. function defined$5(x) {
  6486. return x !== undefined && x !== null;
  6487. }
  6488. class TilesetCache {
  6489. constructor() {
  6490. _defineProperty(this, "_list", void 0);
  6491. _defineProperty(this, "_sentinel", void 0);
  6492. _defineProperty(this, "_trimTiles", void 0);
  6493. this._list = new DoublyLinkedList();
  6494. this._sentinel = this._list.add('sentinel');
  6495. this._trimTiles = false;
  6496. }
  6497. reset() {
  6498. this._list.splice(this._list.tail, this._sentinel);
  6499. }
  6500. touch(tile) {
  6501. const node = tile._cacheNode;
  6502. if (defined$5(node)) {
  6503. this._list.splice(this._sentinel, node);
  6504. }
  6505. }
  6506. add(tileset, tile, addCallback) {
  6507. if (!defined$5(tile._cacheNode)) {
  6508. tile._cacheNode = this._list.add(tile);
  6509. if (addCallback) {
  6510. addCallback(tileset, tile);
  6511. }
  6512. }
  6513. }
  6514. unloadTile(tileset, tile, unloadCallback) {
  6515. const node = tile._cacheNode;
  6516. if (!defined$5(node)) {
  6517. return;
  6518. }
  6519. this._list.remove(node);
  6520. tile._cacheNode = undefined;
  6521. if (unloadCallback) {
  6522. unloadCallback(tileset, tile);
  6523. }
  6524. }
  6525. unloadTiles(tileset, unloadCallback) {
  6526. const trimTiles = this._trimTiles;
  6527. this._trimTiles = false;
  6528. const list = this._list;
  6529. const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
  6530. const sentinel = this._sentinel;
  6531. let node = list.head;
  6532. while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6533. const tile = node.item;
  6534. node = node.next;
  6535. this.unloadTile(tileset, tile, unloadCallback);
  6536. }
  6537. }
  6538. trim() {
  6539. this._trimTiles = true;
  6540. }
  6541. }
  6542. function calculateTransformProps(tileHeader, tile) {
  6543. assert$7(tileHeader);
  6544. assert$7(tile);
  6545. const {
  6546. rtcCenter,
  6547. gltfUpAxis
  6548. } = tile;
  6549. const {
  6550. computedTransform,
  6551. boundingVolume: {
  6552. center
  6553. }
  6554. } = tileHeader;
  6555. let modelMatrix = new Matrix4(computedTransform);
  6556. if (rtcCenter) {
  6557. modelMatrix.translate(rtcCenter);
  6558. }
  6559. switch (gltfUpAxis) {
  6560. case 'Z':
  6561. break;
  6562. case 'Y':
  6563. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6564. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6565. break;
  6566. case 'X':
  6567. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6568. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6569. break;
  6570. }
  6571. if (tile.isQuantized) {
  6572. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6573. }
  6574. const cartesianOrigin = new Vector3(center);
  6575. tile.cartesianModelMatrix = modelMatrix;
  6576. tile.cartesianOrigin = cartesianOrigin;
  6577. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6578. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6579. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6580. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6581. tile.cartographicOrigin = cartographicOrigin;
  6582. if (!tile.coordinateSystem) {
  6583. tile.modelMatrix = tile.cartographicModelMatrix;
  6584. }
  6585. }
  6586. const INTERSECTION = {
  6587. OUTSIDE: -1,
  6588. INTERSECTING: 0,
  6589. INSIDE: 1
  6590. };
  6591. new Vector3();
  6592. new Vector3();
  6593. const scratchVector$3 = new Vector3();
  6594. const scratchVector2 = new Vector3();
  6595. class BoundingSphere {
  6596. constructor(center = [0, 0, 0], radius = 0.0) {
  6597. _defineProperty(this, "center", void 0);
  6598. _defineProperty(this, "radius", void 0);
  6599. this.radius = -0;
  6600. this.center = new Vector3();
  6601. this.fromCenterRadius(center, radius);
  6602. }
  6603. fromCenterRadius(center, radius) {
  6604. this.center.from(center);
  6605. this.radius = radius;
  6606. return this;
  6607. }
  6608. fromCornerPoints(corner, oppositeCorner) {
  6609. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6610. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6611. this.radius = this.center.distance(oppositeCorner);
  6612. return this;
  6613. }
  6614. equals(right) {
  6615. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6616. }
  6617. clone() {
  6618. return new BoundingSphere(this.center, this.radius);
  6619. }
  6620. union(boundingSphere) {
  6621. const leftCenter = this.center;
  6622. const leftRadius = this.radius;
  6623. const rightCenter = boundingSphere.center;
  6624. const rightRadius = boundingSphere.radius;
  6625. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6626. const centerSeparation = toRightCenter.magnitude();
  6627. if (leftRadius >= centerSeparation + rightRadius) {
  6628. return this.clone();
  6629. }
  6630. if (rightRadius >= centerSeparation + leftRadius) {
  6631. return boundingSphere.clone();
  6632. }
  6633. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6634. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6635. this.center.copy(scratchVector2);
  6636. this.radius = halfDistanceBetweenTangentPoints;
  6637. return this;
  6638. }
  6639. expand(point) {
  6640. const scratchPoint = scratchVector$3.from(point);
  6641. const radius = scratchPoint.subtract(this.center).magnitude();
  6642. if (radius > this.radius) {
  6643. this.radius = radius;
  6644. }
  6645. return this;
  6646. }
  6647. transform(transform) {
  6648. this.center.transform(transform);
  6649. const scale = getScaling(scratchVector$3, transform);
  6650. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6651. return this;
  6652. }
  6653. distanceSquaredTo(point) {
  6654. const d = this.distanceTo(point);
  6655. return d * d;
  6656. }
  6657. distanceTo(point) {
  6658. const scratchPoint = scratchVector$3.from(point);
  6659. const delta = scratchPoint.subtract(this.center);
  6660. return Math.max(0, delta.len() - this.radius);
  6661. }
  6662. intersectPlane(plane) {
  6663. const center = this.center;
  6664. const radius = this.radius;
  6665. const normal = plane.normal;
  6666. const distanceToPlane = normal.dot(center) + plane.distance;
  6667. if (distanceToPlane < -radius) {
  6668. return INTERSECTION.OUTSIDE;
  6669. }
  6670. if (distanceToPlane < radius) {
  6671. return INTERSECTION.INTERSECTING;
  6672. }
  6673. return INTERSECTION.INSIDE;
  6674. }
  6675. }
  6676. const scratchVector3 = new Vector3();
  6677. const scratchOffset = new Vector3();
  6678. const scratchVectorU = new Vector3();
  6679. const scratchVectorV = new Vector3();
  6680. const scratchVectorW = new Vector3();
  6681. const scratchCorner = new Vector3();
  6682. const scratchToCenter = new Vector3();
  6683. const MATRIX3 = {
  6684. COLUMN0ROW0: 0,
  6685. COLUMN0ROW1: 1,
  6686. COLUMN0ROW2: 2,
  6687. COLUMN1ROW0: 3,
  6688. COLUMN1ROW1: 4,
  6689. COLUMN1ROW2: 5,
  6690. COLUMN2ROW0: 6,
  6691. COLUMN2ROW1: 7,
  6692. COLUMN2ROW2: 8
  6693. };
  6694. class OrientedBoundingBox {
  6695. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6696. _defineProperty(this, "center", void 0);
  6697. _defineProperty(this, "halfAxes", void 0);
  6698. this.center = new Vector3().from(center);
  6699. this.halfAxes = new Matrix3(halfAxes);
  6700. }
  6701. get halfSize() {
  6702. const xAxis = this.halfAxes.getColumn(0);
  6703. const yAxis = this.halfAxes.getColumn(1);
  6704. const zAxis = this.halfAxes.getColumn(2);
  6705. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6706. }
  6707. get quaternion() {
  6708. const xAxis = this.halfAxes.getColumn(0);
  6709. const yAxis = this.halfAxes.getColumn(1);
  6710. const zAxis = this.halfAxes.getColumn(2);
  6711. const normXAxis = new Vector3(xAxis).normalize();
  6712. const normYAxis = new Vector3(yAxis).normalize();
  6713. const normZAxis = new Vector3(zAxis).normalize();
  6714. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6715. }
  6716. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6717. const quaternionObject = new Quaternion(quaternion);
  6718. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6719. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6720. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6721. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6722. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6723. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6724. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6725. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6726. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6727. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6728. this.center = new Vector3().from(center);
  6729. this.halfAxes = directionsMatrix;
  6730. return this;
  6731. }
  6732. clone() {
  6733. return new OrientedBoundingBox(this.center, this.halfAxes);
  6734. }
  6735. equals(right) {
  6736. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6737. }
  6738. getBoundingSphere(result = new BoundingSphere()) {
  6739. const halfAxes = this.halfAxes;
  6740. const u = halfAxes.getColumn(0, scratchVectorU);
  6741. const v = halfAxes.getColumn(1, scratchVectorV);
  6742. const w = halfAxes.getColumn(2, scratchVectorW);
  6743. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6744. result.center.copy(this.center);
  6745. result.radius = cornerVector.magnitude();
  6746. return result;
  6747. }
  6748. intersectPlane(plane) {
  6749. const center = this.center;
  6750. const normal = plane.normal;
  6751. const halfAxes = this.halfAxes;
  6752. const normalX = normal.x;
  6753. const normalY = normal.y;
  6754. const normalZ = normal.z;
  6755. const radEffective = Math.abs(normalX * halfAxes[MATRIX3.COLUMN0ROW0] + normalY * halfAxes[MATRIX3.COLUMN0ROW1] + normalZ * halfAxes[MATRIX3.COLUMN0ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN1ROW0] + normalY * halfAxes[MATRIX3.COLUMN1ROW1] + normalZ * halfAxes[MATRIX3.COLUMN1ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN2ROW0] + normalY * halfAxes[MATRIX3.COLUMN2ROW1] + normalZ * halfAxes[MATRIX3.COLUMN2ROW2]);
  6756. const distanceToPlane = normal.dot(center) + plane.distance;
  6757. if (distanceToPlane <= -radEffective) {
  6758. return INTERSECTION.OUTSIDE;
  6759. } else if (distanceToPlane >= radEffective) {
  6760. return INTERSECTION.INSIDE;
  6761. }
  6762. return INTERSECTION.INTERSECTING;
  6763. }
  6764. distanceTo(point) {
  6765. return Math.sqrt(this.distanceSquaredTo(point));
  6766. }
  6767. distanceSquaredTo(point) {
  6768. const offset = scratchOffset.from(point).subtract(this.center);
  6769. const halfAxes = this.halfAxes;
  6770. const u = halfAxes.getColumn(0, scratchVectorU);
  6771. const v = halfAxes.getColumn(1, scratchVectorV);
  6772. const w = halfAxes.getColumn(2, scratchVectorW);
  6773. const uHalf = u.magnitude();
  6774. const vHalf = v.magnitude();
  6775. const wHalf = w.magnitude();
  6776. u.normalize();
  6777. v.normalize();
  6778. w.normalize();
  6779. let distanceSquared = 0.0;
  6780. let d;
  6781. d = Math.abs(offset.dot(u)) - uHalf;
  6782. if (d > 0) {
  6783. distanceSquared += d * d;
  6784. }
  6785. d = Math.abs(offset.dot(v)) - vHalf;
  6786. if (d > 0) {
  6787. distanceSquared += d * d;
  6788. }
  6789. d = Math.abs(offset.dot(w)) - wHalf;
  6790. if (d > 0) {
  6791. distanceSquared += d * d;
  6792. }
  6793. return distanceSquared;
  6794. }
  6795. computePlaneDistances(position, direction, result = [-0, -0]) {
  6796. let minDist = Number.POSITIVE_INFINITY;
  6797. let maxDist = Number.NEGATIVE_INFINITY;
  6798. const center = this.center;
  6799. const halfAxes = this.halfAxes;
  6800. const u = halfAxes.getColumn(0, scratchVectorU);
  6801. const v = halfAxes.getColumn(1, scratchVectorV);
  6802. const w = halfAxes.getColumn(2, scratchVectorW);
  6803. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6804. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6805. let mag = direction.dot(toCenter);
  6806. minDist = Math.min(mag, minDist);
  6807. maxDist = Math.max(mag, maxDist);
  6808. corner.copy(center).add(u).add(v).subtract(w);
  6809. toCenter.copy(corner).subtract(position);
  6810. mag = direction.dot(toCenter);
  6811. minDist = Math.min(mag, minDist);
  6812. maxDist = Math.max(mag, maxDist);
  6813. corner.copy(center).add(u).subtract(v).add(w);
  6814. toCenter.copy(corner).subtract(position);
  6815. mag = direction.dot(toCenter);
  6816. minDist = Math.min(mag, minDist);
  6817. maxDist = Math.max(mag, maxDist);
  6818. corner.copy(center).add(u).subtract(v).subtract(w);
  6819. toCenter.copy(corner).subtract(position);
  6820. mag = direction.dot(toCenter);
  6821. minDist = Math.min(mag, minDist);
  6822. maxDist = Math.max(mag, maxDist);
  6823. center.copy(corner).subtract(u).add(v).add(w);
  6824. toCenter.copy(corner).subtract(position);
  6825. mag = direction.dot(toCenter);
  6826. minDist = Math.min(mag, minDist);
  6827. maxDist = Math.max(mag, maxDist);
  6828. center.copy(corner).subtract(u).add(v).subtract(w);
  6829. toCenter.copy(corner).subtract(position);
  6830. mag = direction.dot(toCenter);
  6831. minDist = Math.min(mag, minDist);
  6832. maxDist = Math.max(mag, maxDist);
  6833. center.copy(corner).subtract(u).subtract(v).add(w);
  6834. toCenter.copy(corner).subtract(position);
  6835. mag = direction.dot(toCenter);
  6836. minDist = Math.min(mag, minDist);
  6837. maxDist = Math.max(mag, maxDist);
  6838. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6839. toCenter.copy(corner).subtract(position);
  6840. mag = direction.dot(toCenter);
  6841. minDist = Math.min(mag, minDist);
  6842. maxDist = Math.max(mag, maxDist);
  6843. result[0] = minDist;
  6844. result[1] = maxDist;
  6845. return result;
  6846. }
  6847. transform(transformation) {
  6848. this.center.transformAsPoint(transformation);
  6849. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6850. xAxis.transformAsPoint(transformation);
  6851. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6852. yAxis.transformAsPoint(transformation);
  6853. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6854. zAxis.transformAsPoint(transformation);
  6855. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6856. return this;
  6857. }
  6858. getTransform() {
  6859. throw new Error('not implemented');
  6860. }
  6861. }
  6862. const scratchPosition$1 = new Vector3();
  6863. const scratchNormal$1 = new Vector3();
  6864. class Plane {
  6865. constructor(normal = [0, 0, 1], distance = 0) {
  6866. _defineProperty(this, "normal", void 0);
  6867. _defineProperty(this, "distance", void 0);
  6868. this.normal = new Vector3();
  6869. this.distance = -0;
  6870. this.fromNormalDistance(normal, distance);
  6871. }
  6872. fromNormalDistance(normal, distance) {
  6873. assert$4(Number.isFinite(distance));
  6874. this.normal.from(normal).normalize();
  6875. this.distance = distance;
  6876. return this;
  6877. }
  6878. fromPointNormal(point, normal) {
  6879. point = scratchPosition$1.from(point);
  6880. this.normal.from(normal).normalize();
  6881. const distance = -this.normal.dot(point);
  6882. this.distance = distance;
  6883. return this;
  6884. }
  6885. fromCoefficients(a, b, c, d) {
  6886. this.normal.set(a, b, c);
  6887. assert$4(equals(this.normal.len(), 1));
  6888. this.distance = d;
  6889. return this;
  6890. }
  6891. clone() {
  6892. return new Plane(this.normal, this.distance);
  6893. }
  6894. equals(right) {
  6895. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6896. }
  6897. getPointDistance(point) {
  6898. return this.normal.dot(point) + this.distance;
  6899. }
  6900. transform(matrix4) {
  6901. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6902. const point = this.normal.scale(-this.distance).transform(matrix4);
  6903. return this.fromPointNormal(point, normal);
  6904. }
  6905. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6906. point = scratchPosition$1.from(point);
  6907. const pointDistance = this.getPointDistance(point);
  6908. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6909. return point.subtract(scaledNormal).to(result);
  6910. }
  6911. }
  6912. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6913. const scratchPlaneCenter = new Vector3();
  6914. const scratchPlaneNormal$1 = new Vector3();
  6915. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6916. class CullingVolume {
  6917. constructor(planes = []) {
  6918. _defineProperty(this, "planes", void 0);
  6919. this.planes = planes;
  6920. }
  6921. fromBoundingSphere(boundingSphere) {
  6922. this.planes.length = 2 * faces.length;
  6923. const center = boundingSphere.center;
  6924. const radius = boundingSphere.radius;
  6925. let planeIndex = 0;
  6926. for (const faceNormal of faces) {
  6927. let plane0 = this.planes[planeIndex];
  6928. let plane1 = this.planes[planeIndex + 1];
  6929. if (!plane0) {
  6930. plane0 = this.planes[planeIndex] = new Plane();
  6931. }
  6932. if (!plane1) {
  6933. plane1 = this.planes[planeIndex + 1] = new Plane();
  6934. }
  6935. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6936. -faceNormal.dot(plane0Center);
  6937. plane0.fromPointNormal(plane0Center, faceNormal);
  6938. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6939. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6940. -negatedFaceNormal.dot(plane1Center);
  6941. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6942. planeIndex += 2;
  6943. }
  6944. return this;
  6945. }
  6946. computeVisibility(boundingVolume) {
  6947. let intersect = INTERSECTION.INSIDE;
  6948. for (const plane of this.planes) {
  6949. const result = boundingVolume.intersectPlane(plane);
  6950. switch (result) {
  6951. case INTERSECTION.OUTSIDE:
  6952. return INTERSECTION.OUTSIDE;
  6953. case INTERSECTION.INTERSECTING:
  6954. intersect = INTERSECTION.INTERSECTING;
  6955. break;
  6956. }
  6957. }
  6958. return intersect;
  6959. }
  6960. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6961. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6962. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6963. return parentPlaneMask;
  6964. }
  6965. let mask = CullingVolume.MASK_INSIDE;
  6966. const planes = this.planes;
  6967. for (let k = 0; k < this.planes.length; ++k) {
  6968. const flag = k < 31 ? 1 << k : 0;
  6969. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6970. continue;
  6971. }
  6972. const plane = planes[k];
  6973. const result = boundingVolume.intersectPlane(plane);
  6974. if (result === INTERSECTION.OUTSIDE) {
  6975. return CullingVolume.MASK_OUTSIDE;
  6976. } else if (result === INTERSECTION.INTERSECTING) {
  6977. mask |= flag;
  6978. }
  6979. }
  6980. return mask;
  6981. }
  6982. }
  6983. _defineProperty(CullingVolume, "MASK_OUTSIDE", 0xffffffff);
  6984. _defineProperty(CullingVolume, "MASK_INSIDE", 0x00000000);
  6985. _defineProperty(CullingVolume, "MASK_INDETERMINATE", 0x7fffffff);
  6986. const scratchPlaneUpVector = new Vector3();
  6987. const scratchPlaneRightVector = new Vector3();
  6988. const scratchPlaneNearCenter = new Vector3();
  6989. const scratchPlaneFarCenter = new Vector3();
  6990. const scratchPlaneNormal = new Vector3();
  6991. class PerspectiveOffCenterFrustum {
  6992. constructor(options = {}) {
  6993. _defineProperty(this, "left", void 0);
  6994. _defineProperty(this, "_left", void 0);
  6995. _defineProperty(this, "right", void 0);
  6996. _defineProperty(this, "_right", void 0);
  6997. _defineProperty(this, "top", void 0);
  6998. _defineProperty(this, "_top", void 0);
  6999. _defineProperty(this, "bottom", void 0);
  7000. _defineProperty(this, "_bottom", void 0);
  7001. _defineProperty(this, "near", void 0);
  7002. _defineProperty(this, "_near", void 0);
  7003. _defineProperty(this, "far", void 0);
  7004. _defineProperty(this, "_far", void 0);
  7005. _defineProperty(this, "_cullingVolume", new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]));
  7006. _defineProperty(this, "_perspectiveMatrix", new Matrix4());
  7007. _defineProperty(this, "_infinitePerspective", new Matrix4());
  7008. const {
  7009. near = 1.0,
  7010. far = 500000000.0
  7011. } = options;
  7012. this.left = options.left;
  7013. this._left = undefined;
  7014. this.right = options.right;
  7015. this._right = undefined;
  7016. this.top = options.top;
  7017. this._top = undefined;
  7018. this.bottom = options.bottom;
  7019. this._bottom = undefined;
  7020. this.near = near;
  7021. this._near = near;
  7022. this.far = far;
  7023. this._far = far;
  7024. }
  7025. clone() {
  7026. return new PerspectiveOffCenterFrustum({
  7027. right: this.right,
  7028. left: this.left,
  7029. top: this.top,
  7030. bottom: this.bottom,
  7031. near: this.near,
  7032. far: this.far
  7033. });
  7034. }
  7035. equals(other) {
  7036. return other && other instanceof PerspectiveOffCenterFrustum && this.right === other.right && this.left === other.left && this.top === other.top && this.bottom === other.bottom && this.near === other.near && this.far === other.far;
  7037. }
  7038. get projectionMatrix() {
  7039. this._update();
  7040. return this._perspectiveMatrix;
  7041. }
  7042. get infiniteProjectionMatrix() {
  7043. this._update();
  7044. return this._infinitePerspective;
  7045. }
  7046. computeCullingVolume(position, direction, up) {
  7047. assert$4(position, 'position is required.');
  7048. assert$4(direction, 'direction is required.');
  7049. assert$4(up, 'up is required.');
  7050. const planes = this._cullingVolume.planes;
  7051. up = scratchPlaneUpVector.copy(up).normalize();
  7052. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  7053. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  7054. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  7055. let normal = scratchPlaneNormal;
  7056. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  7057. planes[0].fromPointNormal(position, normal);
  7058. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  7059. planes[1].fromPointNormal(position, normal);
  7060. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  7061. planes[2].fromPointNormal(position, normal);
  7062. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  7063. planes[3].fromPointNormal(position, normal);
  7064. normal = new Vector3().copy(direction);
  7065. planes[4].fromPointNormal(nearCenter, normal);
  7066. normal.negate();
  7067. planes[5].fromPointNormal(farCenter, normal);
  7068. return this._cullingVolume;
  7069. }
  7070. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7071. this._update();
  7072. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  7073. assert$4(drawingBufferWidth > 0);
  7074. assert$4(drawingBufferHeight > 0);
  7075. assert$4(distance > 0);
  7076. assert$4(result);
  7077. const inverseNear = 1.0 / this.near;
  7078. let tanTheta = this.top * inverseNear;
  7079. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  7080. tanTheta = this.right * inverseNear;
  7081. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  7082. result.x = pixelWidth;
  7083. result.y = pixelHeight;
  7084. return result;
  7085. }
  7086. _update() {
  7087. assert$4(Number.isFinite(this.right) && Number.isFinite(this.left) && Number.isFinite(this.top) && Number.isFinite(this.bottom) && Number.isFinite(this.near) && Number.isFinite(this.far));
  7088. const {
  7089. top,
  7090. bottom,
  7091. right,
  7092. left,
  7093. near,
  7094. far
  7095. } = this;
  7096. if (top !== this._top || bottom !== this._bottom || left !== this._left || right !== this._right || near !== this._near || far !== this._far) {
  7097. assert$4(this.near > 0 && this.near < this.far, 'near must be greater than zero and less than far.');
  7098. this._left = left;
  7099. this._right = right;
  7100. this._top = top;
  7101. this._bottom = bottom;
  7102. this._near = near;
  7103. this._far = far;
  7104. this._perspectiveMatrix = new Matrix4().frustum({
  7105. left,
  7106. right,
  7107. bottom,
  7108. top,
  7109. near,
  7110. far
  7111. });
  7112. this._infinitePerspective = new Matrix4().frustum({
  7113. left,
  7114. right,
  7115. bottom,
  7116. top,
  7117. near,
  7118. far: Infinity
  7119. });
  7120. }
  7121. }
  7122. }
  7123. const defined$4 = val => val !== null && typeof val !== 'undefined';
  7124. class PerspectiveFrustum {
  7125. constructor(options = {}) {
  7126. _defineProperty(this, "_offCenterFrustum", new PerspectiveOffCenterFrustum());
  7127. _defineProperty(this, "fov", void 0);
  7128. _defineProperty(this, "_fov", void 0);
  7129. _defineProperty(this, "_fovy", void 0);
  7130. _defineProperty(this, "_sseDenominator", void 0);
  7131. _defineProperty(this, "aspectRatio", void 0);
  7132. _defineProperty(this, "_aspectRatio", void 0);
  7133. _defineProperty(this, "near", void 0);
  7134. _defineProperty(this, "_near", void 0);
  7135. _defineProperty(this, "far", void 0);
  7136. _defineProperty(this, "_far", void 0);
  7137. _defineProperty(this, "xOffset", void 0);
  7138. _defineProperty(this, "_xOffset", void 0);
  7139. _defineProperty(this, "yOffset", void 0);
  7140. _defineProperty(this, "_yOffset", void 0);
  7141. const {
  7142. fov,
  7143. aspectRatio,
  7144. near = 1.0,
  7145. far = 500000000.0,
  7146. xOffset = 0.0,
  7147. yOffset = 0.0
  7148. } = options;
  7149. this.fov = fov;
  7150. this.aspectRatio = aspectRatio;
  7151. this.near = near;
  7152. this.far = far;
  7153. this.xOffset = xOffset;
  7154. this.yOffset = yOffset;
  7155. }
  7156. clone() {
  7157. return new PerspectiveFrustum({
  7158. aspectRatio: this.aspectRatio,
  7159. fov: this.fov,
  7160. near: this.near,
  7161. far: this.far
  7162. });
  7163. }
  7164. equals(other) {
  7165. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  7166. return false;
  7167. }
  7168. this._update();
  7169. other._update();
  7170. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  7171. }
  7172. get projectionMatrix() {
  7173. this._update();
  7174. return this._offCenterFrustum.projectionMatrix;
  7175. }
  7176. get infiniteProjectionMatrix() {
  7177. this._update();
  7178. return this._offCenterFrustum.infiniteProjectionMatrix;
  7179. }
  7180. get fovy() {
  7181. this._update();
  7182. return this._fovy;
  7183. }
  7184. get sseDenominator() {
  7185. this._update();
  7186. return this._sseDenominator;
  7187. }
  7188. computeCullingVolume(position, direction, up) {
  7189. this._update();
  7190. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  7191. }
  7192. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7193. this._update();
  7194. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result || new Vector2());
  7195. }
  7196. _update() {
  7197. assert$4(Number.isFinite(this.fov) && Number.isFinite(this.aspectRatio) && Number.isFinite(this.near) && Number.isFinite(this.far));
  7198. const f = this._offCenterFrustum;
  7199. if (this.fov !== this._fov || this.aspectRatio !== this._aspectRatio || this.near !== this._near || this.far !== this._far || this.xOffset !== this._xOffset || this.yOffset !== this._yOffset) {
  7200. assert$4(this.fov >= 0 && this.fov < Math.PI);
  7201. assert$4(this.aspectRatio > 0);
  7202. assert$4(this.near >= 0 && this.near < this.far);
  7203. this._aspectRatio = this.aspectRatio;
  7204. this._fov = this.fov;
  7205. this._fovy = this.aspectRatio <= 1 ? this.fov : Math.atan(Math.tan(this.fov * 0.5) / this.aspectRatio) * 2.0;
  7206. this._near = this.near;
  7207. this._far = this.far;
  7208. this._sseDenominator = 2.0 * Math.tan(0.5 * this._fovy);
  7209. this._xOffset = this.xOffset;
  7210. this._yOffset = this.yOffset;
  7211. f.top = this.near * Math.tan(0.5 * this._fovy);
  7212. f.bottom = -f.top;
  7213. f.right = this.aspectRatio * f.top;
  7214. f.left = -f.right;
  7215. f.near = this.near;
  7216. f.far = this.far;
  7217. f.right += this.xOffset;
  7218. f.left += this.xOffset;
  7219. f.top += this.yOffset;
  7220. f.bottom += this.yOffset;
  7221. }
  7222. }
  7223. }
  7224. new Vector3();
  7225. new Vector3();
  7226. new Vector3();
  7227. new Vector3();
  7228. new Vector3();
  7229. new Vector3();
  7230. new Vector3();
  7231. new Vector3();
  7232. new Vector3();
  7233. new Vector3();
  7234. new Vector3();
  7235. new Vector3();
  7236. new Matrix3();
  7237. new Matrix3();
  7238. new Matrix3();
  7239. new Matrix3();
  7240. new Matrix3();
  7241. new Vector3();
  7242. new Vector3();
  7243. new Vector3();
  7244. new Vector3();
  7245. new Vector3();
  7246. new Matrix3();
  7247. ({
  7248. diagonal: new Matrix3(),
  7249. unitary: new Matrix3()
  7250. });
  7251. const scratchVector$2 = new Vector3();
  7252. const scratchPosition = new Vector3();
  7253. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7254. function getFrameState(viewport, frameNumber) {
  7255. const {
  7256. cameraDirection,
  7257. cameraUp,
  7258. height
  7259. } = viewport;
  7260. const {
  7261. metersPerUnit
  7262. } = viewport.distanceScales;
  7263. const viewportCenterCartesian = worldToCartesian(viewport, viewport.center);
  7264. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7265. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7266. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7267. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7268. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7269. commonSpacePlanesToWGS84(viewport);
  7270. const ViewportClass = viewport.constructor;
  7271. const {
  7272. longitude,
  7273. latitude,
  7274. width,
  7275. bearing,
  7276. zoom
  7277. } = viewport;
  7278. const topDownViewport = new ViewportClass({
  7279. longitude,
  7280. latitude,
  7281. height,
  7282. width,
  7283. bearing,
  7284. zoom,
  7285. pitch: 0
  7286. });
  7287. return {
  7288. camera: {
  7289. position: cameraPositionCartesian,
  7290. direction: cameraDirectionCartesian,
  7291. up: cameraUpCartesian
  7292. },
  7293. viewport,
  7294. topDownViewport,
  7295. height,
  7296. cullingVolume,
  7297. frameNumber,
  7298. sseDenominator: 1.15
  7299. };
  7300. }
  7301. function limitSelectedTiles(tiles, frameState, maximumTilesSelected) {
  7302. if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) {
  7303. return [tiles, []];
  7304. }
  7305. const tuples = [];
  7306. const {
  7307. longitude: viewportLongitude,
  7308. latitude: viewportLatitude
  7309. } = frameState.viewport;
  7310. for (const [index, tile] of tiles.entries()) {
  7311. const [longitude, latitude] = tile.header.mbs;
  7312. const deltaLon = Math.abs(viewportLongitude - longitude);
  7313. const deltaLat = Math.abs(viewportLatitude - latitude);
  7314. const distance = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon);
  7315. tuples.push([index, distance]);
  7316. }
  7317. const tuplesSorted = tuples.sort((a, b) => a[1] - b[1]);
  7318. const selectedTiles = [];
  7319. for (let i = 0; i < maximumTilesSelected; i++) {
  7320. selectedTiles.push(tiles[tuplesSorted[i][0]]);
  7321. }
  7322. const unselectedTiles = [];
  7323. for (let i = maximumTilesSelected; i < tuplesSorted.length; i++) {
  7324. unselectedTiles.push(tiles[tuplesSorted[i][0]]);
  7325. }
  7326. return [selectedTiles, unselectedTiles];
  7327. }
  7328. function commonSpacePlanesToWGS84(viewport) {
  7329. const frustumPlanes = viewport.getFrustumPlanes();
  7330. const nearCenterCommon = closestPointOnPlane(frustumPlanes.near, viewport.cameraPosition);
  7331. const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon);
  7332. const cameraCartesian = worldToCartesian(viewport, viewport.cameraPosition, scratchPosition);
  7333. let i = 0;
  7334. cullingVolume.planes[i++].fromPointNormal(nearCenterCartesian, scratchVector$2.copy(nearCenterCartesian).subtract(cameraCartesian));
  7335. for (const dir in frustumPlanes) {
  7336. if (dir === 'near') {
  7337. continue;
  7338. }
  7339. const plane = frustumPlanes[dir];
  7340. const posCommon = closestPointOnPlane(plane, nearCenterCommon, scratchPosition);
  7341. const cartesianPos = worldToCartesian(viewport, posCommon, scratchPosition);
  7342. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(nearCenterCartesian).subtract(cartesianPos));
  7343. }
  7344. }
  7345. function closestPointOnPlane(plane, refPoint, out = new Vector3()) {
  7346. const distanceToRef = plane.normal.dot(refPoint);
  7347. out.copy(plane.normal).scale(plane.distance - distanceToRef).add(refPoint);
  7348. return out;
  7349. }
  7350. function worldToCartesian(viewport, point, out = new Vector3()) {
  7351. const cartographicPos = viewport.unprojectPosition(point);
  7352. return Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, out);
  7353. }
  7354. const WGS84_RADIUS_X = 6378137.0;
  7355. const WGS84_RADIUS_Y = 6378137.0;
  7356. const WGS84_RADIUS_Z = 6356752.3142451793;
  7357. const scratchVector$1 = new Vector3();
  7358. function getZoomFromBoundingVolume(boundingVolume, cartorgraphicCenter) {
  7359. if (boundingVolume instanceof OrientedBoundingBox) {
  7360. const {
  7361. halfAxes
  7362. } = boundingVolume;
  7363. const obbSize = getObbSize(halfAxes);
  7364. return Math.log2(WGS84_RADIUS_Z / (obbSize + cartorgraphicCenter[2]));
  7365. } else if (boundingVolume instanceof BoundingSphere) {
  7366. const {
  7367. radius
  7368. } = boundingVolume;
  7369. return Math.log2(WGS84_RADIUS_Z / (radius + cartorgraphicCenter[2]));
  7370. } else if (boundingVolume.width && boundingVolume.height) {
  7371. const {
  7372. width,
  7373. height
  7374. } = boundingVolume;
  7375. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7376. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7377. return (zoomX + zoomY) / 2;
  7378. }
  7379. return 1;
  7380. }
  7381. function getZoomFromFullExtent(fullExtent, cartorgraphicCenter, cartesianCenter) {
  7382. const extentVertex = Ellipsoid.WGS84.cartographicToCartesian([fullExtent.xmax, fullExtent.ymax, fullExtent.zmax], new Vector3());
  7383. const extentSize = Math.sqrt(Math.pow(extentVertex[0] - cartesianCenter[0], 2) + Math.pow(extentVertex[1] - cartesianCenter[1], 2) + Math.pow(extentVertex[2] - cartesianCenter[2], 2));
  7384. return Math.log2(WGS84_RADIUS_Z / (extentSize + cartorgraphicCenter[2]));
  7385. }
  7386. function getZoomFromExtent(extent, cartorgraphicCenter, cartesianCenter) {
  7387. const [xmin, ymin, xmax, ymax] = extent;
  7388. return getZoomFromFullExtent({
  7389. xmin,
  7390. xmax,
  7391. ymin,
  7392. ymax,
  7393. zmin: 0,
  7394. zmax: 0
  7395. }, cartorgraphicCenter, cartesianCenter);
  7396. }
  7397. function getObbSize(halfAxes) {
  7398. halfAxes.getColumn(0, scratchVector$1);
  7399. const axeY = halfAxes.getColumn(1);
  7400. const axeZ = halfAxes.getColumn(2);
  7401. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7402. const size = farthestVertex.len();
  7403. return size;
  7404. }
  7405. const TILE_CONTENT_STATE = {
  7406. UNLOADED: 0,
  7407. LOADING: 1,
  7408. PROCESSING: 2,
  7409. READY: 3,
  7410. EXPIRED: 4,
  7411. FAILED: 5
  7412. };
  7413. const TILE_REFINEMENT = {
  7414. ADD: 1,
  7415. REPLACE: 2
  7416. };
  7417. const TILE_TYPE = {
  7418. EMPTY: 'empty',
  7419. SCENEGRAPH: 'scenegraph',
  7420. POINTCLOUD: 'pointcloud',
  7421. MESH: 'mesh'
  7422. };
  7423. const TILESET_TYPE = {
  7424. I3S: 'I3S',
  7425. TILES3D: 'TILES3D'
  7426. };
  7427. const LOD_METRIC_TYPE = {
  7428. GEOMETRIC_ERROR: 'geometricError',
  7429. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7430. };
  7431. const TILE3D_OPTIMIZATION_HINT = {
  7432. NOT_COMPUTED: -1,
  7433. USE_OPTIMIZATION: 1,
  7434. SKIP_OPTIMIZATION: 0
  7435. };
  7436. function defined$3(x) {
  7437. return x !== undefined && x !== null;
  7438. }
  7439. const scratchScale = new Vector3();
  7440. const scratchNorthWest = new Vector3();
  7441. const scratchSouthEast = new Vector3();
  7442. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7443. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7444. if (boundingVolumeHeader.box) {
  7445. return createBox(boundingVolumeHeader.box, transform, result);
  7446. }
  7447. if (boundingVolumeHeader.region) {
  7448. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7449. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7450. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7451. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7452. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7453. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7454. }
  7455. if (boundingVolumeHeader.sphere) {
  7456. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7457. }
  7458. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7459. }
  7460. function createBox(box, transform, result) {
  7461. const center = new Vector3(box[0], box[1], box[2]);
  7462. transform.transform(center, center);
  7463. let origin = [];
  7464. if (box.length === 10) {
  7465. const halfSize = box.slice(3, 6);
  7466. const quaternion = new Quaternion();
  7467. quaternion.fromArray(box, 6);
  7468. const x = new Vector3([1, 0, 0]);
  7469. const y = new Vector3([0, 1, 0]);
  7470. const z = new Vector3([0, 0, 1]);
  7471. x.transformByQuaternion(quaternion);
  7472. x.scale(halfSize[0]);
  7473. y.transformByQuaternion(quaternion);
  7474. y.scale(halfSize[1]);
  7475. z.transformByQuaternion(quaternion);
  7476. z.scale(halfSize[2]);
  7477. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7478. } else {
  7479. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7480. }
  7481. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7482. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7483. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7484. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7485. if (defined$3(result)) {
  7486. result.center = center;
  7487. result.halfAxes = halfAxes;
  7488. return result;
  7489. }
  7490. return new OrientedBoundingBox(center, halfAxes);
  7491. }
  7492. function createSphere(sphere, transform, result) {
  7493. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7494. transform.transform(center, center);
  7495. const scale = transform.getScale(scratchScale);
  7496. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7497. const radius = sphere[3] * uniformScale;
  7498. if (defined$3(result)) {
  7499. result.center = center;
  7500. result.radius = radius;
  7501. return result;
  7502. }
  7503. return new BoundingSphere(center, radius);
  7504. }
  7505. new Vector3();
  7506. new Vector3();
  7507. new Matrix4();
  7508. new Vector3();
  7509. new Vector3();
  7510. new Vector3();
  7511. function fog(distanceToCamera, density) {
  7512. const scalar = distanceToCamera * density;
  7513. return 1.0 - Math.exp(-(scalar * scalar));
  7514. }
  7515. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7516. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7517. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7518. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7519. const dynamicError = fog(distanceToCamera, density) * factor;
  7520. return dynamicError;
  7521. }
  7522. return 0;
  7523. }
  7524. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7525. const tileset = tile.tileset;
  7526. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7527. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7528. if (lodMetricValue === 0.0) {
  7529. return 0.0;
  7530. }
  7531. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7532. const {
  7533. height,
  7534. sseDenominator
  7535. } = frameState;
  7536. const {
  7537. viewDistanceScale
  7538. } = tileset.options;
  7539. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7540. error -= getDynamicScreenSpaceError(tileset, distance);
  7541. return error;
  7542. }
  7543. const cameraPositionCartesian = new Vector3();
  7544. const toEye = new Vector3();
  7545. const cameraPositionEnu = new Vector3();
  7546. const extraVertexEnu = new Vector3();
  7547. const projectedOriginVector = new Vector3();
  7548. const enuToCartesianMatrix = new Matrix4();
  7549. const cartesianToEnuMatrix = new Matrix4();
  7550. function getLodStatus(tile, frameState) {
  7551. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7552. return 'DIG';
  7553. }
  7554. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7555. if (screenSize < 2) {
  7556. return 'OUT';
  7557. }
  7558. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7559. return 'DRAW';
  7560. } else if (tile.header.children) {
  7561. return 'DIG';
  7562. }
  7563. return 'OUT';
  7564. }
  7565. function getProjectedRadius(tile, frameState) {
  7566. const {
  7567. topDownViewport: viewport
  7568. } = frameState;
  7569. const mbsLat = tile.header.mbs[1];
  7570. const mbsLon = tile.header.mbs[0];
  7571. const mbsZ = tile.header.mbs[2];
  7572. const mbsR = tile.header.mbs[3];
  7573. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7574. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7575. Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian);
  7576. toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7577. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7578. cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert();
  7579. cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7580. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7581. const extraZ = projection * projection / cameraPositionEnu[2];
  7582. extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7583. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7584. const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize();
  7585. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7586. const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian);
  7587. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7588. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7589. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7590. const projectedRadius = projectedOriginVector.copy(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7591. return projectedRadius;
  7592. }
  7593. function get3dTilesOptions(tileset) {
  7594. return {
  7595. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7596. };
  7597. }
  7598. class ManagedArray {
  7599. constructor(length = 0) {
  7600. _defineProperty(this, "_map", new Map());
  7601. _defineProperty(this, "_array", void 0);
  7602. _defineProperty(this, "_length", void 0);
  7603. this._array = new Array(length);
  7604. this._length = length;
  7605. }
  7606. get length() {
  7607. return this._length;
  7608. }
  7609. set length(length) {
  7610. this._length = length;
  7611. if (length > this._array.length) {
  7612. this._array.length = length;
  7613. }
  7614. }
  7615. get values() {
  7616. return this._array;
  7617. }
  7618. get(index) {
  7619. assert$7(index < this._array.length);
  7620. return this._array[index];
  7621. }
  7622. set(index, element) {
  7623. assert$7(index >= 0);
  7624. if (index >= this.length) {
  7625. this.length = index + 1;
  7626. }
  7627. if (this._map.has(this._array[index])) {
  7628. this._map.delete(this._array[index]);
  7629. }
  7630. this._array[index] = element;
  7631. this._map.set(element, index);
  7632. }
  7633. delete(element) {
  7634. const index = this._map.get(element);
  7635. if (index >= 0) {
  7636. this._array.splice(index, 1);
  7637. this._map.delete(element);
  7638. this.length--;
  7639. }
  7640. }
  7641. peek() {
  7642. return this._array[this._length - 1];
  7643. }
  7644. push(element) {
  7645. if (!this._map.has(element)) {
  7646. const index = this.length++;
  7647. this._array[index] = element;
  7648. this._map.set(element, index);
  7649. }
  7650. }
  7651. pop() {
  7652. const element = this._array[--this.length];
  7653. this._map.delete(element);
  7654. return element;
  7655. }
  7656. reserve(length) {
  7657. assert$7(length >= 0);
  7658. if (length > this._array.length) {
  7659. this._array.length = length;
  7660. }
  7661. }
  7662. resize(length) {
  7663. assert$7(length >= 0);
  7664. this.length = length;
  7665. }
  7666. trim(length) {
  7667. if (length === null || length === undefined) {
  7668. length = this.length;
  7669. }
  7670. this._array.length = length;
  7671. }
  7672. reset() {
  7673. this._array = [];
  7674. this._map = new Map();
  7675. this._length = 0;
  7676. }
  7677. find(target) {
  7678. return this._map.has(target);
  7679. }
  7680. }
  7681. const DEFAULT_PROPS$1 = {
  7682. loadSiblings: false,
  7683. skipLevelOfDetail: false,
  7684. maximumScreenSpaceError: 2,
  7685. updateTransforms: true,
  7686. onTraversalEnd: () => {},
  7687. viewportTraversersMap: {},
  7688. basePath: ''
  7689. };
  7690. class TilesetTraverser {
  7691. traversalFinished(frameState) {
  7692. return true;
  7693. }
  7694. constructor(options) {
  7695. _defineProperty(this, "options", void 0);
  7696. _defineProperty(this, "root", void 0);
  7697. _defineProperty(this, "requestedTiles", void 0);
  7698. _defineProperty(this, "selectedTiles", void 0);
  7699. _defineProperty(this, "emptyTiles", void 0);
  7700. _defineProperty(this, "lastUpdate", new Date().getTime());
  7701. _defineProperty(this, "updateDebounceTime", 1000);
  7702. _defineProperty(this, "_traversalStack", void 0);
  7703. _defineProperty(this, "_emptyTraversalStack", void 0);
  7704. _defineProperty(this, "_frameNumber", void 0);
  7705. this.options = { ...DEFAULT_PROPS$1,
  7706. ...options
  7707. };
  7708. this._traversalStack = new ManagedArray();
  7709. this._emptyTraversalStack = new ManagedArray();
  7710. this._frameNumber = null;
  7711. this.root = null;
  7712. this.selectedTiles = {};
  7713. this.requestedTiles = {};
  7714. this.emptyTiles = {};
  7715. }
  7716. traverse(root, frameState, options) {
  7717. this.root = root;
  7718. this.options = { ...this.options,
  7719. ...options
  7720. };
  7721. this.reset();
  7722. this.updateTile(root, frameState);
  7723. this._frameNumber = frameState.frameNumber;
  7724. this.executeTraversal(root, frameState);
  7725. }
  7726. reset() {
  7727. this.requestedTiles = {};
  7728. this.selectedTiles = {};
  7729. this.emptyTiles = {};
  7730. this._traversalStack.reset();
  7731. this._emptyTraversalStack.reset();
  7732. }
  7733. executeTraversal(root, frameState) {
  7734. const stack = this._traversalStack;
  7735. root._selectionDepth = 1;
  7736. stack.push(root);
  7737. while (stack.length > 0) {
  7738. const tile = stack.pop();
  7739. let shouldRefine = false;
  7740. if (this.canTraverse(tile, frameState)) {
  7741. this.updateChildTiles(tile, frameState);
  7742. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7743. }
  7744. const parent = tile.parent;
  7745. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7746. const stoppedRefining = !shouldRefine;
  7747. if (!tile.hasRenderContent) {
  7748. this.emptyTiles[tile.id] = tile;
  7749. this.loadTile(tile, frameState);
  7750. if (stoppedRefining) {
  7751. this.selectTile(tile, frameState);
  7752. }
  7753. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7754. this.loadTile(tile, frameState);
  7755. this.selectTile(tile, frameState);
  7756. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7757. this.loadTile(tile, frameState);
  7758. if (stoppedRefining) {
  7759. this.selectTile(tile, frameState);
  7760. }
  7761. }
  7762. this.touchTile(tile, frameState);
  7763. tile._shouldRefine = shouldRefine && parentRefines;
  7764. }
  7765. const newTime = new Date().getTime();
  7766. if (this.traversalFinished(frameState) || newTime - this.lastUpdate > this.updateDebounceTime) {
  7767. this.lastUpdate = newTime;
  7768. this.options.onTraversalEnd(frameState);
  7769. }
  7770. }
  7771. updateChildTiles(tile, frameState) {
  7772. const children = tile.children;
  7773. for (const child of children) {
  7774. this.updateTile(child, frameState);
  7775. }
  7776. return true;
  7777. }
  7778. updateAndPushChildren(tile, frameState, stack, depth) {
  7779. const {
  7780. loadSiblings,
  7781. skipLevelOfDetail
  7782. } = this.options;
  7783. const children = tile.children;
  7784. children.sort(this.compareDistanceToCamera.bind(this));
  7785. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7786. let hasVisibleChild = false;
  7787. let refines = true;
  7788. for (const child of children) {
  7789. child._selectionDepth = depth;
  7790. if (child.isVisibleAndInRequestVolume) {
  7791. if (stack.find(child)) {
  7792. stack.delete(child);
  7793. }
  7794. stack.push(child);
  7795. hasVisibleChild = true;
  7796. } else if (checkRefines || loadSiblings) {
  7797. this.loadTile(child, frameState);
  7798. this.touchTile(child, frameState);
  7799. }
  7800. if (checkRefines) {
  7801. let childRefines;
  7802. if (!child._inRequestVolume) {
  7803. childRefines = false;
  7804. } else if (!child.hasRenderContent) {
  7805. childRefines = this.executeEmptyTraversal(child, frameState);
  7806. } else {
  7807. childRefines = child.contentAvailable;
  7808. }
  7809. refines = refines && childRefines;
  7810. if (!refines) {
  7811. return false;
  7812. }
  7813. }
  7814. }
  7815. if (!hasVisibleChild) {
  7816. refines = false;
  7817. }
  7818. return refines;
  7819. }
  7820. updateTile(tile, frameState) {
  7821. this.updateTileVisibility(tile, frameState);
  7822. }
  7823. selectTile(tile, frameState) {
  7824. if (this.shouldSelectTile(tile)) {
  7825. tile._selectedFrame = frameState.frameNumber;
  7826. this.selectedTiles[tile.id] = tile;
  7827. }
  7828. }
  7829. loadTile(tile, frameState) {
  7830. if (this.shouldLoadTile(tile)) {
  7831. tile._requestedFrame = frameState.frameNumber;
  7832. tile._priority = tile._getPriority();
  7833. this.requestedTiles[tile.id] = tile;
  7834. }
  7835. }
  7836. touchTile(tile, frameState) {
  7837. tile.tileset._cache.touch(tile);
  7838. tile._touchedFrame = frameState.frameNumber;
  7839. }
  7840. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7841. if (!tile.hasChildren) {
  7842. return false;
  7843. }
  7844. if (tile.hasTilesetContent) {
  7845. return !tile.contentExpired;
  7846. }
  7847. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7848. return false;
  7849. }
  7850. return this.shouldRefine(tile, frameState, useParentMetric);
  7851. }
  7852. shouldLoadTile(tile) {
  7853. return tile.hasUnloadedContent || tile.contentExpired;
  7854. }
  7855. shouldSelectTile(tile) {
  7856. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7857. }
  7858. shouldRefine(tile, frameState, useParentMetric) {
  7859. let screenSpaceError = tile._screenSpaceError;
  7860. if (useParentMetric) {
  7861. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7862. }
  7863. return screenSpaceError > this.options.maximumScreenSpaceError;
  7864. }
  7865. updateTileVisibility(tile, frameState) {
  7866. const viewportIds = [];
  7867. if (this.options.viewportTraversersMap) {
  7868. for (const key in this.options.viewportTraversersMap) {
  7869. const value = this.options.viewportTraversersMap[key];
  7870. if (value === frameState.viewport.id) {
  7871. viewportIds.push(key);
  7872. }
  7873. }
  7874. } else {
  7875. viewportIds.push(frameState.viewport.id);
  7876. }
  7877. tile.updateVisibility(frameState, viewportIds);
  7878. }
  7879. compareDistanceToCamera(b, a) {
  7880. return b._distanceToCamera - a._distanceToCamera;
  7881. }
  7882. anyChildrenVisible(tile, frameState) {
  7883. let anyVisible = false;
  7884. for (const child of tile.children) {
  7885. child.updateVisibility(frameState);
  7886. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7887. }
  7888. return anyVisible;
  7889. }
  7890. executeEmptyTraversal(root, frameState) {
  7891. let allDescendantsLoaded = true;
  7892. const stack = this._emptyTraversalStack;
  7893. stack.push(root);
  7894. while (stack.length > 0 && allDescendantsLoaded) {
  7895. const tile = stack.pop();
  7896. this.updateTile(tile, frameState);
  7897. if (!tile.isVisibleAndInRequestVolume) {
  7898. this.loadTile(tile, frameState);
  7899. }
  7900. this.touchTile(tile, frameState);
  7901. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7902. if (traverse) {
  7903. const children = tile.children;
  7904. for (const child of children) {
  7905. if (stack.find(child)) {
  7906. stack.delete(child);
  7907. }
  7908. stack.push(child);
  7909. }
  7910. } else if (!tile.contentAvailable) {
  7911. allDescendantsLoaded = false;
  7912. }
  7913. }
  7914. return allDescendantsLoaded;
  7915. }
  7916. }
  7917. const scratchVector = new Vector3();
  7918. function defined$2(x) {
  7919. return x !== undefined && x !== null;
  7920. }
  7921. class TileHeader {
  7922. constructor(tileset, header, parentHeader, extendedId = '') {
  7923. _defineProperty(this, "tileset", void 0);
  7924. _defineProperty(this, "header", void 0);
  7925. _defineProperty(this, "id", void 0);
  7926. _defineProperty(this, "url", void 0);
  7927. _defineProperty(this, "parent", void 0);
  7928. _defineProperty(this, "refine", void 0);
  7929. _defineProperty(this, "type", void 0);
  7930. _defineProperty(this, "contentUrl", void 0);
  7931. _defineProperty(this, "lodMetricType", void 0);
  7932. _defineProperty(this, "lodMetricValue", void 0);
  7933. _defineProperty(this, "boundingVolume", void 0);
  7934. _defineProperty(this, "content", void 0);
  7935. _defineProperty(this, "contentState", void 0);
  7936. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7937. _defineProperty(this, "children", void 0);
  7938. _defineProperty(this, "depth", void 0);
  7939. _defineProperty(this, "viewportIds", void 0);
  7940. _defineProperty(this, "transform", void 0);
  7941. _defineProperty(this, "extensions", void 0);
  7942. _defineProperty(this, "userData", void 0);
  7943. _defineProperty(this, "computedTransform", void 0);
  7944. _defineProperty(this, "hasEmptyContent", void 0);
  7945. _defineProperty(this, "hasTilesetContent", void 0);
  7946. _defineProperty(this, "traverser", void 0);
  7947. _defineProperty(this, "_cacheNode", void 0);
  7948. _defineProperty(this, "_frameNumber", void 0);
  7949. _defineProperty(this, "_lodJudge", void 0);
  7950. _defineProperty(this, "_expireDate", void 0);
  7951. _defineProperty(this, "_expiredContent", void 0);
  7952. _defineProperty(this, "_shouldRefine", void 0);
  7953. _defineProperty(this, "_distanceToCamera", void 0);
  7954. _defineProperty(this, "_centerZDepth", void 0);
  7955. _defineProperty(this, "_screenSpaceError", void 0);
  7956. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7957. _defineProperty(this, "_visible", void 0);
  7958. _defineProperty(this, "_inRequestVolume", void 0);
  7959. _defineProperty(this, "_stackLength", void 0);
  7960. _defineProperty(this, "_selectionDepth", void 0);
  7961. _defineProperty(this, "_touchedFrame", void 0);
  7962. _defineProperty(this, "_visitedFrame", void 0);
  7963. _defineProperty(this, "_selectedFrame", void 0);
  7964. _defineProperty(this, "_requestedFrame", void 0);
  7965. _defineProperty(this, "_priority", void 0);
  7966. _defineProperty(this, "_contentBoundingVolume", void 0);
  7967. _defineProperty(this, "_viewerRequestVolume", void 0);
  7968. _defineProperty(this, "_initialTransform", void 0);
  7969. this.header = header;
  7970. this.tileset = tileset;
  7971. this.id = extendedId || header.id;
  7972. this.url = header.url;
  7973. this.parent = parentHeader;
  7974. this.refine = this._getRefine(header.refine);
  7975. this.type = header.type;
  7976. this.contentUrl = header.contentUrl;
  7977. this.lodMetricType = 'geometricError';
  7978. this.lodMetricValue = 0;
  7979. this.boundingVolume = null;
  7980. this.content = null;
  7981. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7982. this.gpuMemoryUsageInBytes = 0;
  7983. this.children = [];
  7984. this.hasEmptyContent = false;
  7985. this.hasTilesetContent = false;
  7986. this.depth = 0;
  7987. this.viewportIds = [];
  7988. this.userData = {};
  7989. this.extensions = null;
  7990. this._priority = 0;
  7991. this._touchedFrame = 0;
  7992. this._visitedFrame = 0;
  7993. this._selectedFrame = 0;
  7994. this._requestedFrame = 0;
  7995. this._screenSpaceError = 0;
  7996. this._cacheNode = null;
  7997. this._frameNumber = null;
  7998. this._cacheNode = null;
  7999. this.traverser = new TilesetTraverser({});
  8000. this._shouldRefine = false;
  8001. this._distanceToCamera = 0;
  8002. this._centerZDepth = 0;
  8003. this._visible = undefined;
  8004. this._inRequestVolume = false;
  8005. this._stackLength = 0;
  8006. this._selectionDepth = 0;
  8007. this._initialTransform = new Matrix4();
  8008. this.transform = new Matrix4();
  8009. this._initializeLodMetric(header);
  8010. this._initializeTransforms(header);
  8011. this._initializeBoundingVolumes(header);
  8012. this._initializeContent(header);
  8013. this._initializeRenderingState(header);
  8014. this._lodJudge = null;
  8015. this._expireDate = null;
  8016. this._expiredContent = null;
  8017. Object.seal(this);
  8018. }
  8019. destroy() {
  8020. this.header = null;
  8021. }
  8022. isDestroyed() {
  8023. return this.header === null;
  8024. }
  8025. get selected() {
  8026. return this._selectedFrame === this.tileset._frameNumber;
  8027. }
  8028. get isVisible() {
  8029. return this._visible;
  8030. }
  8031. get isVisibleAndInRequestVolume() {
  8032. return this._visible && this._inRequestVolume;
  8033. }
  8034. get hasRenderContent() {
  8035. return !this.hasEmptyContent && !this.hasTilesetContent;
  8036. }
  8037. get hasChildren() {
  8038. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  8039. }
  8040. get contentReady() {
  8041. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  8042. }
  8043. get contentAvailable() {
  8044. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  8045. }
  8046. get hasUnloadedContent() {
  8047. return this.hasRenderContent && this.contentUnloaded;
  8048. }
  8049. get contentUnloaded() {
  8050. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  8051. }
  8052. get contentExpired() {
  8053. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  8054. }
  8055. get contentFailed() {
  8056. return this.contentState === TILE_CONTENT_STATE.FAILED;
  8057. }
  8058. getScreenSpaceError(frameState, useParentLodMetric) {
  8059. switch (this.tileset.type) {
  8060. case TILESET_TYPE.I3S:
  8061. return getProjectedRadius(this, frameState);
  8062. case TILESET_TYPE.TILES3D:
  8063. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  8064. default:
  8065. throw new Error('Unsupported tileset type');
  8066. }
  8067. }
  8068. unselect() {
  8069. this._selectedFrame = 0;
  8070. }
  8071. _getPriority() {
  8072. const traverser = this.tileset._traverser;
  8073. const {
  8074. skipLevelOfDetail
  8075. } = traverser.options;
  8076. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  8077. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  8078. return -1;
  8079. }
  8080. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  8081. return -1;
  8082. }
  8083. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  8084. return -1;
  8085. }
  8086. const parent = this.parent;
  8087. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  8088. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  8089. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  8090. return Math.max(rootScreenSpaceError - screenSpaceError, 0);
  8091. }
  8092. async loadContent() {
  8093. if (this.hasEmptyContent) {
  8094. return false;
  8095. }
  8096. if (this.content) {
  8097. return true;
  8098. }
  8099. const expired = this.contentExpired;
  8100. if (expired) {
  8101. this._expireDate = null;
  8102. }
  8103. this.contentState = TILE_CONTENT_STATE.LOADING;
  8104. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  8105. if (!requestToken) {
  8106. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8107. return false;
  8108. }
  8109. try {
  8110. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  8111. const loader = this.tileset.loader;
  8112. const options = { ...this.tileset.loadOptions,
  8113. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  8114. isTileset: this.type === 'json',
  8115. ...this._getLoaderSpecificOptions(loader.id)
  8116. }
  8117. };
  8118. this.content = await load(contentUrl, loader, options);
  8119. if (this.tileset.options.contentLoader) {
  8120. await this.tileset.options.contentLoader(this);
  8121. }
  8122. if (this._isTileset()) {
  8123. this.tileset._initializeTileHeaders(this.content, this);
  8124. }
  8125. this.contentState = TILE_CONTENT_STATE.READY;
  8126. this._onContentLoaded();
  8127. return true;
  8128. } catch (error) {
  8129. this.contentState = TILE_CONTENT_STATE.FAILED;
  8130. throw error;
  8131. } finally {
  8132. requestToken.done();
  8133. }
  8134. }
  8135. unloadContent() {
  8136. if (this.content && this.content.destroy) {
  8137. this.content.destroy();
  8138. }
  8139. this.content = null;
  8140. if (this.header.content && this.header.content.destroy) {
  8141. this.header.content.destroy();
  8142. }
  8143. this.header.content = null;
  8144. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8145. return true;
  8146. }
  8147. updateVisibility(frameState, viewportIds) {
  8148. if (this._frameNumber === frameState.frameNumber) {
  8149. return;
  8150. }
  8151. const parent = this.parent;
  8152. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  8153. if (this.tileset._traverser.options.updateTransforms) {
  8154. const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;
  8155. this._updateTransform(parentTransform);
  8156. }
  8157. this._distanceToCamera = this.distanceToTile(frameState);
  8158. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  8159. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  8160. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  8161. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  8162. this._frameNumber = frameState.frameNumber;
  8163. this.viewportIds = viewportIds;
  8164. }
  8165. visibility(frameState, parentVisibilityPlaneMask) {
  8166. const {
  8167. cullingVolume
  8168. } = frameState;
  8169. const {
  8170. boundingVolume
  8171. } = this;
  8172. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  8173. }
  8174. contentVisibility() {
  8175. return true;
  8176. }
  8177. distanceToTile(frameState) {
  8178. const boundingVolume = this.boundingVolume;
  8179. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  8180. }
  8181. cameraSpaceZDepth({
  8182. camera
  8183. }) {
  8184. const boundingVolume = this.boundingVolume;
  8185. scratchVector.subVectors(boundingVolume.center, camera.position);
  8186. return camera.direction.dot(scratchVector);
  8187. }
  8188. insideViewerRequestVolume(frameState) {
  8189. const viewerRequestVolume = this._viewerRequestVolume;
  8190. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  8191. }
  8192. updateExpiration() {
  8193. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  8194. const now = Date.now();
  8195. if (Date.lessThan(this._expireDate, now)) {
  8196. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  8197. this._expiredContent = this.content;
  8198. }
  8199. }
  8200. }
  8201. get extras() {
  8202. return this.header.extras;
  8203. }
  8204. _initializeLodMetric(header) {
  8205. if ('lodMetricType' in header) {
  8206. this.lodMetricType = header.lodMetricType;
  8207. } else {
  8208. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  8209. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  8210. }
  8211. if ('lodMetricValue' in header) {
  8212. this.lodMetricValue = header.lodMetricValue;
  8213. } else {
  8214. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  8215. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  8216. }
  8217. }
  8218. _initializeTransforms(tileHeader) {
  8219. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  8220. const parent = this.parent;
  8221. const tileset = this.tileset;
  8222. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : tileset.modelMatrix.clone();
  8223. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  8224. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  8225. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  8226. }
  8227. _initializeBoundingVolumes(tileHeader) {
  8228. this._contentBoundingVolume = null;
  8229. this._viewerRequestVolume = null;
  8230. this._updateBoundingVolume(tileHeader);
  8231. }
  8232. _initializeContent(tileHeader) {
  8233. this.content = {
  8234. _tileset: this.tileset,
  8235. _tile: this
  8236. };
  8237. this.hasEmptyContent = true;
  8238. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8239. this.hasTilesetContent = false;
  8240. if (tileHeader.contentUrl) {
  8241. this.content = null;
  8242. this.hasEmptyContent = false;
  8243. }
  8244. }
  8245. _initializeRenderingState(header) {
  8246. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  8247. this._shouldRefine = false;
  8248. this._distanceToCamera = 0;
  8249. this._centerZDepth = 0;
  8250. this._screenSpaceError = 0;
  8251. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  8252. this._visible = undefined;
  8253. this._inRequestVolume = false;
  8254. this._stackLength = 0;
  8255. this._selectionDepth = 0;
  8256. this._frameNumber = 0;
  8257. this._touchedFrame = 0;
  8258. this._visitedFrame = 0;
  8259. this._selectedFrame = 0;
  8260. this._requestedFrame = 0;
  8261. this._priority = 0.0;
  8262. }
  8263. _getRefine(refine) {
  8264. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  8265. }
  8266. _isTileset() {
  8267. return this.contentUrl.indexOf('.json') !== -1;
  8268. }
  8269. _onContentLoaded() {
  8270. switch (this.content && this.content.type) {
  8271. case 'vctr':
  8272. case 'geom':
  8273. this.tileset._traverser.disableSkipLevelOfDetail = true;
  8274. break;
  8275. }
  8276. if (this._isTileset()) {
  8277. this.hasTilesetContent = true;
  8278. }
  8279. }
  8280. _updateBoundingVolume(header) {
  8281. this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume);
  8282. const content = header.content;
  8283. if (!content) {
  8284. return;
  8285. }
  8286. if (content.boundingVolume) {
  8287. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume);
  8288. }
  8289. if (header.viewerRequestVolume) {
  8290. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume);
  8291. }
  8292. }
  8293. _updateTransform(parentTransform = new Matrix4()) {
  8294. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8295. const didTransformChange = !computedTransform.equals(this.computedTransform);
  8296. if (!didTransformChange) {
  8297. return;
  8298. }
  8299. this.computedTransform = computedTransform;
  8300. this._updateBoundingVolume(this.header);
  8301. }
  8302. _getLoaderSpecificOptions(loaderId) {
  8303. switch (loaderId) {
  8304. case 'i3s':
  8305. return { ...this.tileset.options.i3s,
  8306. tile: this.header,
  8307. tileset: this.tileset.tileset,
  8308. isTileHeader: false
  8309. };
  8310. case '3d-tiles':
  8311. case 'cesium-ion':
  8312. default:
  8313. return get3dTilesOptions(this.tileset.tileset);
  8314. }
  8315. }
  8316. }
  8317. class Tileset3DTraverser extends TilesetTraverser {
  8318. compareDistanceToCamera(a, b) {
  8319. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8320. }
  8321. updateTileVisibility(tile, frameState) {
  8322. super.updateTileVisibility(tile, frameState);
  8323. if (!tile.isVisibleAndInRequestVolume) {
  8324. return;
  8325. }
  8326. const hasChildren = tile.children.length > 0;
  8327. if (tile.hasTilesetContent && hasChildren) {
  8328. const firstChild = tile.children[0];
  8329. this.updateTileVisibility(firstChild, frameState);
  8330. tile._visible = firstChild._visible;
  8331. return;
  8332. }
  8333. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8334. tile._visible = false;
  8335. return;
  8336. }
  8337. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8338. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8339. if (replace && useOptimization && hasChildren) {
  8340. if (!this.anyChildrenVisible(tile, frameState)) {
  8341. tile._visible = false;
  8342. return;
  8343. }
  8344. }
  8345. }
  8346. meetsScreenSpaceErrorEarly(tile, frameState) {
  8347. const {
  8348. parent
  8349. } = tile;
  8350. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8351. return false;
  8352. }
  8353. return !this.shouldRefine(tile, frameState, true);
  8354. }
  8355. }
  8356. class I3SPendingTilesRegister {
  8357. constructor() {
  8358. _defineProperty(this, "frameNumberMap", new Map());
  8359. }
  8360. register(viewportId, frameNumber) {
  8361. const viewportMap = this.frameNumberMap.get(viewportId) || new Map();
  8362. const oldCount = viewportMap.get(frameNumber) || 0;
  8363. viewportMap.set(frameNumber, oldCount + 1);
  8364. this.frameNumberMap.set(viewportId, viewportMap);
  8365. }
  8366. deregister(viewportId, frameNumber) {
  8367. const viewportMap = this.frameNumberMap.get(viewportId);
  8368. if (!viewportMap) {
  8369. return;
  8370. }
  8371. const oldCount = viewportMap.get(frameNumber) || 1;
  8372. viewportMap.set(frameNumber, oldCount - 1);
  8373. }
  8374. isZero(viewportId, frameNumber) {
  8375. var _this$frameNumberMap$;
  8376. const count = ((_this$frameNumberMap$ = this.frameNumberMap.get(viewportId)) === null || _this$frameNumberMap$ === void 0 ? void 0 : _this$frameNumberMap$.get(frameNumber)) || 0;
  8377. return count === 0;
  8378. }
  8379. }
  8380. const STATUS = {
  8381. REQUESTED: 'REQUESTED',
  8382. COMPLETED: 'COMPLETED',
  8383. ERROR: 'ERROR'
  8384. };
  8385. class I3STileManager {
  8386. constructor() {
  8387. _defineProperty(this, "_statusMap", void 0);
  8388. _defineProperty(this, "pendingTilesRegister", new I3SPendingTilesRegister());
  8389. this._statusMap = {};
  8390. }
  8391. add(request, key, callback, frameState) {
  8392. if (!this._statusMap[key]) {
  8393. const {
  8394. frameNumber,
  8395. viewport: {
  8396. id
  8397. }
  8398. } = frameState;
  8399. this._statusMap[key] = {
  8400. request,
  8401. callback,
  8402. key,
  8403. frameState,
  8404. status: STATUS.REQUESTED
  8405. };
  8406. this.pendingTilesRegister.register(id, frameNumber);
  8407. request().then(data => {
  8408. this._statusMap[key].status = STATUS.COMPLETED;
  8409. const {
  8410. frameNumber: actualFrameNumber,
  8411. viewport: {
  8412. id
  8413. }
  8414. } = this._statusMap[key].frameState;
  8415. this.pendingTilesRegister.deregister(id, actualFrameNumber);
  8416. this._statusMap[key].callback(data, frameState);
  8417. }).catch(error => {
  8418. this._statusMap[key].status = STATUS.ERROR;
  8419. const {
  8420. frameNumber: actualFrameNumber,
  8421. viewport: {
  8422. id
  8423. }
  8424. } = this._statusMap[key].frameState;
  8425. this.pendingTilesRegister.deregister(id, actualFrameNumber);
  8426. callback(error);
  8427. });
  8428. }
  8429. }
  8430. update(key, frameState) {
  8431. if (this._statusMap[key]) {
  8432. const {
  8433. frameNumber,
  8434. viewport: {
  8435. id
  8436. }
  8437. } = this._statusMap[key].frameState;
  8438. this.pendingTilesRegister.deregister(id, frameNumber);
  8439. const {
  8440. frameNumber: newFrameNumber,
  8441. viewport: {
  8442. id: newViewportId
  8443. }
  8444. } = frameState;
  8445. this.pendingTilesRegister.register(newViewportId, newFrameNumber);
  8446. this._statusMap[key].frameState = frameState;
  8447. }
  8448. }
  8449. find(key) {
  8450. return this._statusMap[key];
  8451. }
  8452. hasPendingTiles(viewportId, frameNumber) {
  8453. return !this.pendingTilesRegister.isZero(viewportId, frameNumber);
  8454. }
  8455. }
  8456. class I3STilesetTraverser extends TilesetTraverser {
  8457. traversalFinished(frameState) {
  8458. return !this._tileManager.hasPendingTiles(frameState.viewport.id, this._frameNumber || 0);
  8459. }
  8460. constructor(options) {
  8461. super(options);
  8462. _defineProperty(this, "_tileManager", void 0);
  8463. this._tileManager = new I3STileManager();
  8464. }
  8465. shouldRefine(tile, frameState) {
  8466. tile._lodJudge = getLodStatus(tile, frameState);
  8467. return tile._lodJudge === 'DIG';
  8468. }
  8469. updateChildTiles(tile, frameState) {
  8470. const children = tile.header.children || [];
  8471. const childTiles = tile.children;
  8472. const tileset = tile.tileset;
  8473. for (const child of children) {
  8474. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8475. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8476. if (!childTile) {
  8477. let request = () => this._loadTile(child.id, tileset);
  8478. const cachedRequest = this._tileManager.find(extendedId);
  8479. if (!cachedRequest) {
  8480. if (tileset.tileset.nodePages) {
  8481. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8482. }
  8483. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8484. } else {
  8485. this._tileManager.update(extendedId, frameState);
  8486. }
  8487. } else if (childTile) {
  8488. this.updateTile(childTile, frameState);
  8489. }
  8490. }
  8491. return false;
  8492. }
  8493. async _loadTile(nodeId, tileset) {
  8494. const {
  8495. loader
  8496. } = tileset;
  8497. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8498. const options = { ...tileset.loadOptions,
  8499. i3s: { ...tileset.loadOptions.i3s,
  8500. isTileHeader: true,
  8501. loadContent: false
  8502. }
  8503. };
  8504. return await load(nodeUrl, loader, options);
  8505. }
  8506. _onTileLoad(header, tile, extendedId) {
  8507. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8508. tile.children.push(childTile);
  8509. const frameState = this._tileManager.find(childTile.id).frameState;
  8510. this.updateTile(childTile, frameState);
  8511. if (this._frameNumber === frameState.frameNumber && (this.traversalFinished(frameState) || new Date().getTime() - this.lastUpdate > this.updateDebounceTime)) {
  8512. this.executeTraversal(childTile, frameState);
  8513. }
  8514. }
  8515. }
  8516. const DEFAULT_PROPS = {
  8517. description: '',
  8518. ellipsoid: Ellipsoid.WGS84,
  8519. modelMatrix: new Matrix4(),
  8520. throttleRequests: true,
  8521. maxRequests: 64,
  8522. maximumMemoryUsage: 32,
  8523. maximumTilesSelected: 0,
  8524. debounceTime: 0,
  8525. onTileLoad: () => {},
  8526. onTileUnload: () => {},
  8527. onTileError: () => {},
  8528. onTraversalComplete: selectedTiles => selectedTiles,
  8529. contentLoader: undefined,
  8530. viewDistanceScale: 1.0,
  8531. maximumScreenSpaceError: 8,
  8532. loadTiles: true,
  8533. updateTransforms: true,
  8534. viewportTraversersMap: null,
  8535. loadOptions: {
  8536. fetch: {}
  8537. },
  8538. attributions: [],
  8539. basePath: '',
  8540. i3s: {}
  8541. };
  8542. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8543. const TILES_IN_MEMORY = 'Tiles In Memory';
  8544. const TILES_IN_VIEW = 'Tiles In View';
  8545. const TILES_RENDERABLE = 'Tiles To Render';
  8546. const TILES_LOADED = 'Tiles Loaded';
  8547. const TILES_LOADING = 'Tiles Loading';
  8548. const TILES_UNLOADED = 'Tiles Unloaded';
  8549. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8550. const POINTS_COUNT = 'Points/Vertices';
  8551. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8552. class Tileset3D {
  8553. constructor(json, options) {
  8554. _defineProperty(this, "options", void 0);
  8555. _defineProperty(this, "loadOptions", void 0);
  8556. _defineProperty(this, "type", void 0);
  8557. _defineProperty(this, "tileset", void 0);
  8558. _defineProperty(this, "loader", void 0);
  8559. _defineProperty(this, "url", void 0);
  8560. _defineProperty(this, "basePath", void 0);
  8561. _defineProperty(this, "modelMatrix", void 0);
  8562. _defineProperty(this, "ellipsoid", void 0);
  8563. _defineProperty(this, "lodMetricType", void 0);
  8564. _defineProperty(this, "lodMetricValue", void 0);
  8565. _defineProperty(this, "refine", void 0);
  8566. _defineProperty(this, "root", void 0);
  8567. _defineProperty(this, "roots", void 0);
  8568. _defineProperty(this, "asset", void 0);
  8569. _defineProperty(this, "description", void 0);
  8570. _defineProperty(this, "properties", void 0);
  8571. _defineProperty(this, "extras", void 0);
  8572. _defineProperty(this, "attributions", void 0);
  8573. _defineProperty(this, "credits", void 0);
  8574. _defineProperty(this, "stats", void 0);
  8575. _defineProperty(this, "traverseCounter", void 0);
  8576. _defineProperty(this, "geometricError", void 0);
  8577. _defineProperty(this, "selectedTiles", void 0);
  8578. _defineProperty(this, "updatePromise", null);
  8579. _defineProperty(this, "tilesetInitializationPromise", void 0);
  8580. _defineProperty(this, "cartographicCenter", void 0);
  8581. _defineProperty(this, "cartesianCenter", void 0);
  8582. _defineProperty(this, "zoom", void 0);
  8583. _defineProperty(this, "boundingVolume", void 0);
  8584. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8585. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8586. _defineProperty(this, "_traverser", void 0);
  8587. _defineProperty(this, "_cache", void 0);
  8588. _defineProperty(this, "_requestScheduler", void 0);
  8589. _defineProperty(this, "_frameNumber", void 0);
  8590. _defineProperty(this, "_queryParamsString", void 0);
  8591. _defineProperty(this, "_queryParams", void 0);
  8592. _defineProperty(this, "_extensionsUsed", void 0);
  8593. _defineProperty(this, "_tiles", void 0);
  8594. _defineProperty(this, "_pendingCount", void 0);
  8595. _defineProperty(this, "lastUpdatedVieports", void 0);
  8596. _defineProperty(this, "_requestedTiles", void 0);
  8597. _defineProperty(this, "_emptyTiles", void 0);
  8598. _defineProperty(this, "frameStateData", void 0);
  8599. _defineProperty(this, "maximumMemoryUsage", void 0);
  8600. assert$7(json);
  8601. this.options = { ...DEFAULT_PROPS,
  8602. ...options
  8603. };
  8604. this.tileset = json;
  8605. this.loader = json.loader;
  8606. this.type = json.type;
  8607. this.url = json.url;
  8608. this.basePath = json.basePath || dirname(this.url);
  8609. this.modelMatrix = this.options.modelMatrix;
  8610. this.ellipsoid = this.options.ellipsoid;
  8611. this.lodMetricType = json.lodMetricType;
  8612. this.lodMetricValue = json.lodMetricValue;
  8613. this.refine = json.root.refine;
  8614. this.loadOptions = this.options.loadOptions || {};
  8615. this.root = null;
  8616. this.roots = {};
  8617. this.cartographicCenter = null;
  8618. this.cartesianCenter = null;
  8619. this.zoom = 1;
  8620. this.boundingVolume = null;
  8621. this.traverseCounter = 0;
  8622. this.geometricError = 0;
  8623. this._traverser = this._initializeTraverser();
  8624. this._cache = new TilesetCache();
  8625. this._requestScheduler = new RequestScheduler({
  8626. throttleRequests: this.options.throttleRequests,
  8627. maxRequests: this.options.maxRequests
  8628. });
  8629. this._frameNumber = 0;
  8630. this._pendingCount = 0;
  8631. this._tiles = {};
  8632. this.selectedTiles = [];
  8633. this._emptyTiles = [];
  8634. this._requestedTiles = [];
  8635. this.frameStateData = {};
  8636. this.lastUpdatedVieports = null;
  8637. this._queryParams = {};
  8638. this._queryParamsString = '';
  8639. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8640. this.gpuMemoryUsageInBytes = 0;
  8641. this.stats = new Stats({
  8642. id: this.url
  8643. });
  8644. this._initializeStats();
  8645. this._extensionsUsed = undefined;
  8646. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8647. this.extras = null;
  8648. this.asset = {};
  8649. this.credits = {};
  8650. this.description = this.options.description || '';
  8651. this.tilesetInitializationPromise = this._initializeTileSet(json);
  8652. }
  8653. destroy() {
  8654. this._destroy();
  8655. }
  8656. isLoaded() {
  8657. return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
  8658. }
  8659. get tiles() {
  8660. return Object.values(this._tiles);
  8661. }
  8662. get frameNumber() {
  8663. return this._frameNumber;
  8664. }
  8665. get queryParams() {
  8666. if (!this._queryParamsString) {
  8667. this._queryParamsString = getQueryParamString(this._queryParams);
  8668. }
  8669. return this._queryParamsString;
  8670. }
  8671. setProps(props) {
  8672. this.options = { ...this.options,
  8673. ...props
  8674. };
  8675. }
  8676. setOptions(options) {
  8677. this.options = { ...this.options,
  8678. ...options
  8679. };
  8680. }
  8681. getTileUrl(tilePath) {
  8682. const isDataUrl = tilePath.startsWith('data:');
  8683. if (isDataUrl) {
  8684. return tilePath;
  8685. }
  8686. return "".concat(tilePath).concat(this.queryParams);
  8687. }
  8688. hasExtension(extensionName) {
  8689. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8690. }
  8691. update(viewports = null) {
  8692. this.tilesetInitializationPromise.then(() => {
  8693. if (!viewports && this.lastUpdatedVieports) {
  8694. viewports = this.lastUpdatedVieports;
  8695. } else {
  8696. this.lastUpdatedVieports = viewports;
  8697. }
  8698. if (viewports) {
  8699. this.doUpdate(viewports);
  8700. }
  8701. });
  8702. }
  8703. async selectTiles(viewports = null) {
  8704. await this.tilesetInitializationPromise;
  8705. if (viewports) {
  8706. this.lastUpdatedVieports = viewports;
  8707. }
  8708. if (!this.updatePromise) {
  8709. this.updatePromise = new Promise(resolve => {
  8710. setTimeout(() => {
  8711. if (this.lastUpdatedVieports) {
  8712. this.doUpdate(this.lastUpdatedVieports);
  8713. }
  8714. resolve(this._frameNumber);
  8715. this.updatePromise = null;
  8716. }, this.options.debounceTime);
  8717. });
  8718. }
  8719. return this.updatePromise;
  8720. }
  8721. doUpdate(viewports) {
  8722. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8723. return;
  8724. }
  8725. if (this.traverseCounter > 0) {
  8726. return;
  8727. }
  8728. const preparedViewports = viewports instanceof Array ? viewports : [viewports];
  8729. this._cache.reset();
  8730. this._frameNumber++;
  8731. this.traverseCounter = preparedViewports.length;
  8732. const viewportsToTraverse = [];
  8733. for (const viewport of preparedViewports) {
  8734. const id = viewport.id;
  8735. if (this._needTraverse(id)) {
  8736. viewportsToTraverse.push(id);
  8737. } else {
  8738. this.traverseCounter--;
  8739. }
  8740. }
  8741. for (const viewport of preparedViewports) {
  8742. const id = viewport.id;
  8743. if (!this.roots[id]) {
  8744. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8745. }
  8746. if (!viewportsToTraverse.includes(id)) {
  8747. continue;
  8748. }
  8749. const frameState = getFrameState(viewport, this._frameNumber);
  8750. this._traverser.traverse(this.roots[id], frameState, this.options);
  8751. }
  8752. }
  8753. _needTraverse(viewportId) {
  8754. let traverserId = viewportId;
  8755. if (this.options.viewportTraversersMap) {
  8756. traverserId = this.options.viewportTraversersMap[viewportId];
  8757. }
  8758. if (traverserId !== viewportId) {
  8759. return false;
  8760. }
  8761. return true;
  8762. }
  8763. _onTraversalEnd(frameState) {
  8764. const id = frameState.viewport.id;
  8765. if (!this.frameStateData[id]) {
  8766. this.frameStateData[id] = {
  8767. selectedTiles: [],
  8768. _requestedTiles: [],
  8769. _emptyTiles: []
  8770. };
  8771. }
  8772. const currentFrameStateData = this.frameStateData[id];
  8773. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8774. const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
  8775. currentFrameStateData.selectedTiles = filteredSelectedTiles;
  8776. for (const tile of unselectedTiles) {
  8777. tile.unselect();
  8778. }
  8779. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8780. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8781. this.traverseCounter--;
  8782. if (this.traverseCounter > 0) {
  8783. return;
  8784. }
  8785. this._updateTiles();
  8786. }
  8787. _updateTiles() {
  8788. this.selectedTiles = [];
  8789. this._requestedTiles = [];
  8790. this._emptyTiles = [];
  8791. for (const frameStateKey in this.frameStateData) {
  8792. const frameStateDataValue = this.frameStateData[frameStateKey];
  8793. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8794. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8795. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8796. }
  8797. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8798. for (const tile of this.selectedTiles) {
  8799. this._tiles[tile.id] = tile;
  8800. }
  8801. this._loadTiles();
  8802. this._unloadTiles();
  8803. this._updateStats();
  8804. }
  8805. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8806. if (oldSelectedTiles.length !== selectedTiles.length) {
  8807. return true;
  8808. }
  8809. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8810. const set2 = new Set(selectedTiles.map(t => t.id));
  8811. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8812. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8813. return changed;
  8814. }
  8815. _loadTiles() {
  8816. for (const tile of this._requestedTiles) {
  8817. if (tile.contentUnloaded) {
  8818. this._loadTile(tile);
  8819. }
  8820. }
  8821. }
  8822. _unloadTiles() {
  8823. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8824. }
  8825. _updateStats() {
  8826. let tilesRenderable = 0;
  8827. let pointsRenderable = 0;
  8828. for (const tile of this.selectedTiles) {
  8829. if (tile.contentAvailable && tile.content) {
  8830. tilesRenderable++;
  8831. if (tile.content.pointCount) {
  8832. pointsRenderable += tile.content.pointCount;
  8833. } else {
  8834. pointsRenderable += tile.content.vertexCount;
  8835. }
  8836. }
  8837. }
  8838. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8839. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8840. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8841. }
  8842. async _initializeTileSet(tilesetJson) {
  8843. if (this.type === TILESET_TYPE.I3S) {
  8844. this.calculateViewPropsI3S();
  8845. tilesetJson.root = await tilesetJson.root;
  8846. }
  8847. this.root = this._initializeTileHeaders(tilesetJson, null);
  8848. if (this.type === TILESET_TYPE.TILES3D) {
  8849. this._initializeTiles3DTileset(tilesetJson);
  8850. this.calculateViewPropsTiles3D();
  8851. }
  8852. if (this.type === TILESET_TYPE.I3S) {
  8853. this._initializeI3STileset();
  8854. }
  8855. }
  8856. calculateViewPropsI3S() {
  8857. var _this$tileset$store;
  8858. const fullExtent = this.tileset.fullExtent;
  8859. if (fullExtent) {
  8860. const {
  8861. xmin,
  8862. xmax,
  8863. ymin,
  8864. ymax,
  8865. zmin,
  8866. zmax
  8867. } = fullExtent;
  8868. this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
  8869. this.cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, new Vector3());
  8870. this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
  8871. return;
  8872. }
  8873. const extent = (_this$tileset$store = this.tileset.store) === null || _this$tileset$store === void 0 ? void 0 : _this$tileset$store.extent;
  8874. if (extent) {
  8875. const [xmin, ymin, xmax, ymax] = extent;
  8876. this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
  8877. this.cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, new Vector3());
  8878. this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
  8879. return;
  8880. }
  8881. console.warn('Extent is not defined in the tileset header');
  8882. this.cartographicCenter = new Vector3();
  8883. this.zoom = 1;
  8884. return;
  8885. }
  8886. calculateViewPropsTiles3D() {
  8887. const root = this.root;
  8888. assert$7(root);
  8889. const {
  8890. center
  8891. } = root.boundingVolume;
  8892. if (!center) {
  8893. console.warn('center was not pre-calculated for the root tile');
  8894. this.cartographicCenter = new Vector3();
  8895. this.zoom = 1;
  8896. return;
  8897. }
  8898. if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
  8899. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8900. } else {
  8901. this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
  8902. }
  8903. this.cartesianCenter = center;
  8904. this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
  8905. }
  8906. _initializeStats() {
  8907. this.stats.get(TILES_TOTAL);
  8908. this.stats.get(TILES_LOADING);
  8909. this.stats.get(TILES_IN_MEMORY);
  8910. this.stats.get(TILES_IN_VIEW);
  8911. this.stats.get(TILES_RENDERABLE);
  8912. this.stats.get(TILES_LOADED);
  8913. this.stats.get(TILES_UNLOADED);
  8914. this.stats.get(TILES_LOAD_FAILED);
  8915. this.stats.get(POINTS_COUNT);
  8916. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8917. }
  8918. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8919. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader);
  8920. if (parentTileHeader) {
  8921. parentTileHeader.children.push(rootTile);
  8922. rootTile.depth = parentTileHeader.depth + 1;
  8923. }
  8924. if (this.type === TILESET_TYPE.TILES3D) {
  8925. const stack = [];
  8926. stack.push(rootTile);
  8927. while (stack.length > 0) {
  8928. const tile = stack.pop();
  8929. this.stats.get(TILES_TOTAL).incrementCount();
  8930. const children = tile.header.children || [];
  8931. for (const childHeader of children) {
  8932. const childTile = new TileHeader(this, childHeader, tile);
  8933. tile.children.push(childTile);
  8934. childTile.depth = tile.depth + 1;
  8935. stack.push(childTile);
  8936. }
  8937. }
  8938. }
  8939. return rootTile;
  8940. }
  8941. _initializeTraverser() {
  8942. let TraverserClass;
  8943. const type = this.type;
  8944. switch (type) {
  8945. case TILESET_TYPE.TILES3D:
  8946. TraverserClass = Tileset3DTraverser;
  8947. break;
  8948. case TILESET_TYPE.I3S:
  8949. TraverserClass = I3STilesetTraverser;
  8950. break;
  8951. default:
  8952. TraverserClass = TilesetTraverser;
  8953. }
  8954. return new TraverserClass({
  8955. basePath: this.basePath,
  8956. onTraversalEnd: this._onTraversalEnd.bind(this)
  8957. });
  8958. }
  8959. _destroyTileHeaders(parentTile) {
  8960. this._destroySubtree(parentTile);
  8961. }
  8962. async _loadTile(tile) {
  8963. let loaded;
  8964. try {
  8965. this._onStartTileLoading();
  8966. loaded = await tile.loadContent();
  8967. } catch (error) {
  8968. this._onTileLoadError(tile, error);
  8969. } finally {
  8970. this._onEndTileLoading();
  8971. this._onTileLoad(tile, loaded);
  8972. }
  8973. }
  8974. _onTileLoadError(tile, error) {
  8975. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8976. const message = error.message || error.toString();
  8977. const url = tile.url;
  8978. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8979. this.options.onTileError(tile, message, url);
  8980. }
  8981. _onTileLoad(tile, loaded) {
  8982. if (!loaded) {
  8983. return;
  8984. }
  8985. if (this.type === TILESET_TYPE.I3S) {
  8986. var _this$tileset, _this$tileset$nodePag;
  8987. const nodesInNodePages = ((_this$tileset = this.tileset) === null || _this$tileset === void 0 ? void 0 : (_this$tileset$nodePag = _this$tileset.nodePagesTile) === null || _this$tileset$nodePag === void 0 ? void 0 : _this$tileset$nodePag.nodesInNodePages) || 0;
  8988. this.stats.get(TILES_TOTAL).reset();
  8989. this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
  8990. }
  8991. if (tile && tile.content) {
  8992. calculateTransformProps(tile, tile.content);
  8993. }
  8994. this._addTileToCache(tile);
  8995. this.options.onTileLoad(tile);
  8996. }
  8997. _onStartTileLoading() {
  8998. this._pendingCount++;
  8999. this.stats.get(TILES_LOADING).incrementCount();
  9000. }
  9001. _onEndTileLoading() {
  9002. this._pendingCount--;
  9003. this.stats.get(TILES_LOADING).decrementCount();
  9004. }
  9005. _addTileToCache(tile) {
  9006. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  9007. }
  9008. _updateCacheStats(tile) {
  9009. this.stats.get(TILES_LOADED).incrementCount();
  9010. this.stats.get(TILES_IN_MEMORY).incrementCount();
  9011. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  9012. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  9013. }
  9014. _unloadTile(tile) {
  9015. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  9016. this.stats.get(TILES_IN_MEMORY).decrementCount();
  9017. this.stats.get(TILES_UNLOADED).incrementCount();
  9018. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  9019. this.options.onTileUnload(tile);
  9020. tile.unloadContent();
  9021. }
  9022. _destroy() {
  9023. const stack = [];
  9024. if (this.root) {
  9025. stack.push(this.root);
  9026. }
  9027. while (stack.length > 0) {
  9028. const tile = stack.pop();
  9029. for (const child of tile.children) {
  9030. stack.push(child);
  9031. }
  9032. this._destroyTile(tile);
  9033. }
  9034. this.root = null;
  9035. }
  9036. _destroySubtree(tile) {
  9037. const root = tile;
  9038. const stack = [];
  9039. stack.push(root);
  9040. while (stack.length > 0) {
  9041. tile = stack.pop();
  9042. for (const child of tile.children) {
  9043. stack.push(child);
  9044. }
  9045. if (tile !== root) {
  9046. this._destroyTile(tile);
  9047. }
  9048. }
  9049. root.children = [];
  9050. }
  9051. _destroyTile(tile) {
  9052. this._cache.unloadTile(this, tile);
  9053. this._unloadTile(tile);
  9054. tile.destroy();
  9055. }
  9056. _initializeTiles3DTileset(tilesetJson) {
  9057. this.asset = tilesetJson.asset;
  9058. if (!this.asset) {
  9059. throw new Error('Tileset must have an asset property.');
  9060. }
  9061. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  9062. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  9063. }
  9064. if ('tilesetVersion' in this.asset) {
  9065. this._queryParams.v = this.asset.tilesetVersion;
  9066. }
  9067. this.credits = {
  9068. attributions: this.options.attributions || []
  9069. };
  9070. this.description = this.options.description || '';
  9071. this.properties = tilesetJson.properties;
  9072. this.geometricError = tilesetJson.geometricError;
  9073. this._extensionsUsed = tilesetJson.extensionsUsed;
  9074. this.extras = tilesetJson.extras;
  9075. }
  9076. _initializeI3STileset() {
  9077. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  9078. this._queryParams.token = this.loadOptions.i3s.token;
  9079. }
  9080. }
  9081. }
  9082. function getQueryParamString(queryParams) {
  9083. const queryParamStrings = [];
  9084. for (const key of Object.keys(queryParams)) {
  9085. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  9086. }
  9087. switch (queryParamStrings.length) {
  9088. case 0:
  9089. return '';
  9090. case 1:
  9091. return "?".concat(queryParamStrings[0]);
  9092. default:
  9093. return "?".concat(queryParamStrings.join('&'));
  9094. }
  9095. }
  9096. const VERSION$5 = "3.2.12" ;
  9097. const TILE3D_TYPE = {
  9098. COMPOSITE: 'cmpt',
  9099. POINT_CLOUD: 'pnts',
  9100. BATCHED_3D_MODEL: 'b3dm',
  9101. INSTANCED_3D_MODEL: 'i3dm',
  9102. GEOMETRY: 'geom',
  9103. VECTOR: 'vect',
  9104. GLTF: 'glTF'
  9105. };
  9106. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  9107. assert$7(arrayBuffer instanceof ArrayBuffer);
  9108. const textDecoder = new TextDecoder('utf8');
  9109. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  9110. const string = textDecoder.decode(typedArray);
  9111. return string;
  9112. }
  9113. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  9114. const dataView = new DataView(arrayBuffer);
  9115. return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
  9116. }
  9117. const VERSION$4 = "3.2.12" ;
  9118. const DEFAULT_DRACO_OPTIONS = {
  9119. draco: {
  9120. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  9121. libraryPath: 'libs/',
  9122. extraAttributes: {},
  9123. attributeNameEntry: undefined
  9124. }
  9125. };
  9126. const DracoLoader$1 = {
  9127. name: 'Draco',
  9128. id: 'draco',
  9129. module: 'draco',
  9130. shapes: ['mesh'],
  9131. version: VERSION$4,
  9132. worker: true,
  9133. extensions: ['drc'],
  9134. mimeTypes: ['application/octet-stream'],
  9135. binary: true,
  9136. tests: ['DRACO'],
  9137. options: DEFAULT_DRACO_OPTIONS
  9138. };
  9139. function getMeshBoundingBox(attributes) {
  9140. let minX = Infinity;
  9141. let minY = Infinity;
  9142. let minZ = Infinity;
  9143. let maxX = -Infinity;
  9144. let maxY = -Infinity;
  9145. let maxZ = -Infinity;
  9146. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  9147. const len = positions && positions.length;
  9148. for (let i = 0; i < len; i += 3) {
  9149. const x = positions[i];
  9150. const y = positions[i + 1];
  9151. const z = positions[i + 2];
  9152. minX = x < minX ? x : minX;
  9153. minY = y < minY ? y : minY;
  9154. minZ = z < minZ ? z : minZ;
  9155. maxX = x > maxX ? x : maxX;
  9156. maxY = y > maxY ? y : maxY;
  9157. maxZ = z > maxZ ? z : maxZ;
  9158. }
  9159. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  9160. }
  9161. function assert$3(condition, message) {
  9162. if (!condition) {
  9163. throw new Error(message || 'loader assertion failed.');
  9164. }
  9165. }
  9166. class Schema {
  9167. constructor(fields, metadata) {
  9168. _defineProperty(this, "fields", void 0);
  9169. _defineProperty(this, "metadata", void 0);
  9170. assert$3(Array.isArray(fields));
  9171. checkNames(fields);
  9172. this.fields = fields;
  9173. this.metadata = metadata || new Map();
  9174. }
  9175. compareTo(other) {
  9176. if (this.metadata !== other.metadata) {
  9177. return false;
  9178. }
  9179. if (this.fields.length !== other.fields.length) {
  9180. return false;
  9181. }
  9182. for (let i = 0; i < this.fields.length; ++i) {
  9183. if (!this.fields[i].compareTo(other.fields[i])) {
  9184. return false;
  9185. }
  9186. }
  9187. return true;
  9188. }
  9189. select(...columnNames) {
  9190. const nameMap = Object.create(null);
  9191. for (const name of columnNames) {
  9192. nameMap[name] = true;
  9193. }
  9194. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  9195. return new Schema(selectedFields, this.metadata);
  9196. }
  9197. selectAt(...columnIndices) {
  9198. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  9199. return new Schema(selectedFields, this.metadata);
  9200. }
  9201. assign(schemaOrFields) {
  9202. let fields;
  9203. let metadata = this.metadata;
  9204. if (schemaOrFields instanceof Schema) {
  9205. const otherSchema = schemaOrFields;
  9206. fields = otherSchema.fields;
  9207. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  9208. } else {
  9209. fields = schemaOrFields;
  9210. }
  9211. const fieldMap = Object.create(null);
  9212. for (const field of this.fields) {
  9213. fieldMap[field.name] = field;
  9214. }
  9215. for (const field of fields) {
  9216. fieldMap[field.name] = field;
  9217. }
  9218. const mergedFields = Object.values(fieldMap);
  9219. return new Schema(mergedFields, metadata);
  9220. }
  9221. }
  9222. function checkNames(fields) {
  9223. const usedNames = {};
  9224. for (const field of fields) {
  9225. if (usedNames[field.name]) {
  9226. console.warn('Schema: duplicated field name', field.name, field);
  9227. }
  9228. usedNames[field.name] = true;
  9229. }
  9230. }
  9231. function mergeMaps(m1, m2) {
  9232. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  9233. }
  9234. class Field {
  9235. constructor(name, type, nullable = false, metadata = new Map()) {
  9236. _defineProperty(this, "name", void 0);
  9237. _defineProperty(this, "type", void 0);
  9238. _defineProperty(this, "nullable", void 0);
  9239. _defineProperty(this, "metadata", void 0);
  9240. this.name = name;
  9241. this.type = type;
  9242. this.nullable = nullable;
  9243. this.metadata = metadata;
  9244. }
  9245. get typeId() {
  9246. return this.type && this.type.typeId;
  9247. }
  9248. clone() {
  9249. return new Field(this.name, this.type, this.nullable, this.metadata);
  9250. }
  9251. compareTo(other) {
  9252. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  9253. }
  9254. toString() {
  9255. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  9256. }
  9257. }
  9258. let Type;
  9259. (function (Type) {
  9260. Type[Type["NONE"] = 0] = "NONE";
  9261. Type[Type["Null"] = 1] = "Null";
  9262. Type[Type["Int"] = 2] = "Int";
  9263. Type[Type["Float"] = 3] = "Float";
  9264. Type[Type["Binary"] = 4] = "Binary";
  9265. Type[Type["Utf8"] = 5] = "Utf8";
  9266. Type[Type["Bool"] = 6] = "Bool";
  9267. Type[Type["Decimal"] = 7] = "Decimal";
  9268. Type[Type["Date"] = 8] = "Date";
  9269. Type[Type["Time"] = 9] = "Time";
  9270. Type[Type["Timestamp"] = 10] = "Timestamp";
  9271. Type[Type["Interval"] = 11] = "Interval";
  9272. Type[Type["List"] = 12] = "List";
  9273. Type[Type["Struct"] = 13] = "Struct";
  9274. Type[Type["Union"] = 14] = "Union";
  9275. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  9276. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  9277. Type[Type["Map"] = 17] = "Map";
  9278. Type[Type["Dictionary"] = -1] = "Dictionary";
  9279. Type[Type["Int8"] = -2] = "Int8";
  9280. Type[Type["Int16"] = -3] = "Int16";
  9281. Type[Type["Int32"] = -4] = "Int32";
  9282. Type[Type["Int64"] = -5] = "Int64";
  9283. Type[Type["Uint8"] = -6] = "Uint8";
  9284. Type[Type["Uint16"] = -7] = "Uint16";
  9285. Type[Type["Uint32"] = -8] = "Uint32";
  9286. Type[Type["Uint64"] = -9] = "Uint64";
  9287. Type[Type["Float16"] = -10] = "Float16";
  9288. Type[Type["Float32"] = -11] = "Float32";
  9289. Type[Type["Float64"] = -12] = "Float64";
  9290. Type[Type["DateDay"] = -13] = "DateDay";
  9291. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  9292. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  9293. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  9294. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  9295. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  9296. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  9297. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  9298. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  9299. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  9300. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  9301. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  9302. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  9303. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  9304. })(Type || (Type = {}));
  9305. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  9306. class DataType {
  9307. static isNull(x) {
  9308. return x && x.typeId === Type.Null;
  9309. }
  9310. static isInt(x) {
  9311. return x && x.typeId === Type.Int;
  9312. }
  9313. static isFloat(x) {
  9314. return x && x.typeId === Type.Float;
  9315. }
  9316. static isBinary(x) {
  9317. return x && x.typeId === Type.Binary;
  9318. }
  9319. static isUtf8(x) {
  9320. return x && x.typeId === Type.Utf8;
  9321. }
  9322. static isBool(x) {
  9323. return x && x.typeId === Type.Bool;
  9324. }
  9325. static isDecimal(x) {
  9326. return x && x.typeId === Type.Decimal;
  9327. }
  9328. static isDate(x) {
  9329. return x && x.typeId === Type.Date;
  9330. }
  9331. static isTime(x) {
  9332. return x && x.typeId === Type.Time;
  9333. }
  9334. static isTimestamp(x) {
  9335. return x && x.typeId === Type.Timestamp;
  9336. }
  9337. static isInterval(x) {
  9338. return x && x.typeId === Type.Interval;
  9339. }
  9340. static isList(x) {
  9341. return x && x.typeId === Type.List;
  9342. }
  9343. static isStruct(x) {
  9344. return x && x.typeId === Type.Struct;
  9345. }
  9346. static isUnion(x) {
  9347. return x && x.typeId === Type.Union;
  9348. }
  9349. static isFixedSizeBinary(x) {
  9350. return x && x.typeId === Type.FixedSizeBinary;
  9351. }
  9352. static isFixedSizeList(x) {
  9353. return x && x.typeId === Type.FixedSizeList;
  9354. }
  9355. static isMap(x) {
  9356. return x && x.typeId === Type.Map;
  9357. }
  9358. static isDictionary(x) {
  9359. return x && x.typeId === Type.Dictionary;
  9360. }
  9361. get typeId() {
  9362. return Type.NONE;
  9363. }
  9364. compareTo(other) {
  9365. return this === other;
  9366. }
  9367. }
  9368. _Symbol$toStringTag = Symbol.toStringTag;
  9369. class Int extends DataType {
  9370. constructor(isSigned, bitWidth) {
  9371. super();
  9372. _defineProperty(this, "isSigned", void 0);
  9373. _defineProperty(this, "bitWidth", void 0);
  9374. this.isSigned = isSigned;
  9375. this.bitWidth = bitWidth;
  9376. }
  9377. get typeId() {
  9378. return Type.Int;
  9379. }
  9380. get [_Symbol$toStringTag]() {
  9381. return 'Int';
  9382. }
  9383. toString() {
  9384. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  9385. }
  9386. }
  9387. class Int8 extends Int {
  9388. constructor() {
  9389. super(true, 8);
  9390. }
  9391. }
  9392. class Int16 extends Int {
  9393. constructor() {
  9394. super(true, 16);
  9395. }
  9396. }
  9397. class Int32 extends Int {
  9398. constructor() {
  9399. super(true, 32);
  9400. }
  9401. }
  9402. class Uint8 extends Int {
  9403. constructor() {
  9404. super(false, 8);
  9405. }
  9406. }
  9407. class Uint16 extends Int {
  9408. constructor() {
  9409. super(false, 16);
  9410. }
  9411. }
  9412. class Uint32 extends Int {
  9413. constructor() {
  9414. super(false, 32);
  9415. }
  9416. }
  9417. const Precision = {
  9418. HALF: 16,
  9419. SINGLE: 32,
  9420. DOUBLE: 64
  9421. };
  9422. _Symbol$toStringTag2 = Symbol.toStringTag;
  9423. class Float extends DataType {
  9424. constructor(precision) {
  9425. super();
  9426. _defineProperty(this, "precision", void 0);
  9427. this.precision = precision;
  9428. }
  9429. get typeId() {
  9430. return Type.Float;
  9431. }
  9432. get [_Symbol$toStringTag2]() {
  9433. return 'Float';
  9434. }
  9435. toString() {
  9436. return "Float".concat(this.precision);
  9437. }
  9438. }
  9439. class Float32 extends Float {
  9440. constructor() {
  9441. super(Precision.SINGLE);
  9442. }
  9443. }
  9444. class Float64 extends Float {
  9445. constructor() {
  9446. super(Precision.DOUBLE);
  9447. }
  9448. }
  9449. _Symbol$toStringTag7 = Symbol.toStringTag;
  9450. class FixedSizeList extends DataType {
  9451. constructor(listSize, child) {
  9452. super();
  9453. _defineProperty(this, "listSize", void 0);
  9454. _defineProperty(this, "children", void 0);
  9455. this.listSize = listSize;
  9456. this.children = [child];
  9457. }
  9458. get typeId() {
  9459. return Type.FixedSizeList;
  9460. }
  9461. get valueType() {
  9462. return this.children[0].type;
  9463. }
  9464. get valueField() {
  9465. return this.children[0];
  9466. }
  9467. get [_Symbol$toStringTag7]() {
  9468. return 'FixedSizeList';
  9469. }
  9470. toString() {
  9471. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9472. }
  9473. }
  9474. function getArrowTypeFromTypedArray(array) {
  9475. switch (array.constructor) {
  9476. case Int8Array:
  9477. return new Int8();
  9478. case Uint8Array:
  9479. return new Uint8();
  9480. case Int16Array:
  9481. return new Int16();
  9482. case Uint16Array:
  9483. return new Uint16();
  9484. case Int32Array:
  9485. return new Int32();
  9486. case Uint32Array:
  9487. return new Uint32();
  9488. case Float32Array:
  9489. return new Float32();
  9490. case Float64Array:
  9491. return new Float64();
  9492. default:
  9493. throw new Error('array type not supported');
  9494. }
  9495. }
  9496. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9497. const type = getArrowTypeFromTypedArray(attribute.value);
  9498. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9499. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9500. return field;
  9501. }
  9502. function makeMeshAttributeMetadata(attribute) {
  9503. const result = new Map();
  9504. if ('byteOffset' in attribute) {
  9505. result.set('byteOffset', attribute.byteOffset.toString(10));
  9506. }
  9507. if ('byteStride' in attribute) {
  9508. result.set('byteStride', attribute.byteStride.toString(10));
  9509. }
  9510. if ('normalized' in attribute) {
  9511. result.set('normalized', attribute.normalized.toString());
  9512. }
  9513. return result;
  9514. }
  9515. function getDracoSchema(attributes, loaderData, indices) {
  9516. const metadataMap = makeMetadata(loaderData.metadata);
  9517. const fields = [];
  9518. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9519. for (const attributeName in attributes) {
  9520. const attribute = attributes[attributeName];
  9521. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9522. fields.push(field);
  9523. }
  9524. if (indices) {
  9525. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9526. fields.push(indicesField);
  9527. }
  9528. return new Schema(fields, metadataMap);
  9529. }
  9530. function transformAttributesLoaderData(loaderData) {
  9531. const result = {};
  9532. for (const key in loaderData) {
  9533. const dracoAttribute = loaderData[key];
  9534. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9535. }
  9536. return result;
  9537. }
  9538. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9539. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9540. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9541. return field;
  9542. }
  9543. function makeMetadata(metadata) {
  9544. const metadataMap = new Map();
  9545. for (const key in metadata) {
  9546. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9547. }
  9548. return metadataMap;
  9549. }
  9550. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9551. POSITION: 'POSITION',
  9552. NORMAL: 'NORMAL',
  9553. COLOR: 'COLOR_0',
  9554. TEX_COORD: 'TEXCOORD_0'
  9555. };
  9556. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9557. 1: Int8Array,
  9558. 2: Uint8Array,
  9559. 3: Int16Array,
  9560. 4: Uint16Array,
  9561. 5: Int32Array,
  9562. 6: Uint32Array,
  9563. 9: Float32Array
  9564. };
  9565. const INDEX_ITEM_SIZE = 4;
  9566. class DracoParser {
  9567. constructor(draco) {
  9568. _defineProperty(this, "draco", void 0);
  9569. _defineProperty(this, "decoder", void 0);
  9570. _defineProperty(this, "metadataQuerier", void 0);
  9571. this.draco = draco;
  9572. this.decoder = new this.draco.Decoder();
  9573. this.metadataQuerier = new this.draco.MetadataQuerier();
  9574. }
  9575. destroy() {
  9576. this.draco.destroy(this.decoder);
  9577. this.draco.destroy(this.metadataQuerier);
  9578. }
  9579. parseSync(arrayBuffer, options = {}) {
  9580. const buffer = new this.draco.DecoderBuffer();
  9581. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9582. this._disableAttributeTransforms(options);
  9583. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9584. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9585. try {
  9586. let dracoStatus;
  9587. switch (geometry_type) {
  9588. case this.draco.TRIANGULAR_MESH:
  9589. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9590. break;
  9591. case this.draco.POINT_CLOUD:
  9592. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9593. break;
  9594. default:
  9595. throw new Error('DRACO: Unknown geometry type.');
  9596. }
  9597. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9598. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9599. throw new Error(message);
  9600. }
  9601. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9602. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9603. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9604. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9605. const data = {
  9606. loader: 'draco',
  9607. loaderData,
  9608. header: {
  9609. vertexCount: dracoGeometry.num_points(),
  9610. boundingBox
  9611. },
  9612. ...geometry,
  9613. schema
  9614. };
  9615. return data;
  9616. } finally {
  9617. this.draco.destroy(buffer);
  9618. if (dracoGeometry) {
  9619. this.draco.destroy(dracoGeometry);
  9620. }
  9621. }
  9622. }
  9623. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9624. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9625. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9626. return {
  9627. geometry_type,
  9628. num_attributes: dracoGeometry.num_attributes(),
  9629. num_points: dracoGeometry.num_points(),
  9630. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9631. metadata,
  9632. attributes
  9633. };
  9634. }
  9635. _getDracoAttributes(dracoGeometry, options) {
  9636. const dracoAttributes = {};
  9637. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9638. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9639. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9640. dracoAttributes[dracoAttribute.unique_id()] = {
  9641. unique_id: dracoAttribute.unique_id(),
  9642. attribute_type: dracoAttribute.attribute_type(),
  9643. data_type: dracoAttribute.data_type(),
  9644. num_components: dracoAttribute.num_components(),
  9645. byte_offset: dracoAttribute.byte_offset(),
  9646. byte_stride: dracoAttribute.byte_stride(),
  9647. normalized: dracoAttribute.normalized(),
  9648. attribute_index: attributeId,
  9649. metadata
  9650. };
  9651. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9652. if (quantization) {
  9653. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9654. }
  9655. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9656. if (octahedron) {
  9657. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9658. }
  9659. }
  9660. return dracoAttributes;
  9661. }
  9662. _getMeshData(dracoGeometry, loaderData, options) {
  9663. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9664. const positionAttribute = attributes.POSITION;
  9665. if (!positionAttribute) {
  9666. throw new Error('DRACO: No position attribute found.');
  9667. }
  9668. if (dracoGeometry instanceof this.draco.Mesh) {
  9669. switch (options.topology) {
  9670. case 'triangle-strip':
  9671. return {
  9672. topology: 'triangle-strip',
  9673. mode: 4,
  9674. attributes,
  9675. indices: {
  9676. value: this._getTriangleStripIndices(dracoGeometry),
  9677. size: 1
  9678. }
  9679. };
  9680. case 'triangle-list':
  9681. default:
  9682. return {
  9683. topology: 'triangle-list',
  9684. mode: 5,
  9685. attributes,
  9686. indices: {
  9687. value: this._getTriangleListIndices(dracoGeometry),
  9688. size: 1
  9689. }
  9690. };
  9691. }
  9692. }
  9693. return {
  9694. topology: 'point-list',
  9695. mode: 0,
  9696. attributes
  9697. };
  9698. }
  9699. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9700. const attributes = {};
  9701. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9702. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9703. loaderAttribute.name = attributeName;
  9704. const {
  9705. value,
  9706. size
  9707. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9708. attributes[attributeName] = {
  9709. value,
  9710. size,
  9711. byteOffset: loaderAttribute.byte_offset,
  9712. byteStride: loaderAttribute.byte_stride,
  9713. normalized: loaderAttribute.normalized
  9714. };
  9715. }
  9716. return attributes;
  9717. }
  9718. _getTriangleListIndices(dracoGeometry) {
  9719. const numFaces = dracoGeometry.num_faces();
  9720. const numIndices = numFaces * 3;
  9721. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9722. const ptr = this.draco._malloc(byteLength);
  9723. try {
  9724. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9725. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9726. } finally {
  9727. this.draco._free(ptr);
  9728. }
  9729. }
  9730. _getTriangleStripIndices(dracoGeometry) {
  9731. const dracoArray = new this.draco.DracoInt32Array();
  9732. try {
  9733. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9734. return getUint32Array(dracoArray);
  9735. } finally {
  9736. this.draco.destroy(dracoArray);
  9737. }
  9738. }
  9739. _getAttributeValues(dracoGeometry, attribute) {
  9740. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9741. const numComponents = attribute.num_components;
  9742. const numPoints = dracoGeometry.num_points();
  9743. const numValues = numPoints * numComponents;
  9744. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9745. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9746. let value;
  9747. const ptr = this.draco._malloc(byteLength);
  9748. try {
  9749. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9750. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9751. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9752. } finally {
  9753. this.draco._free(ptr);
  9754. }
  9755. return {
  9756. value,
  9757. size: numComponents
  9758. };
  9759. }
  9760. _deduceAttributeName(attribute, options) {
  9761. const uniqueId = attribute.unique_id;
  9762. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9763. if (attributeUniqueId === uniqueId) {
  9764. return attributeName;
  9765. }
  9766. }
  9767. const thisAttributeType = attribute.attribute_type;
  9768. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9769. const attributeType = this.draco[dracoAttributeConstant];
  9770. if (attributeType === thisAttributeType) {
  9771. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9772. }
  9773. }
  9774. const entryName = options.attributeNameEntry || 'name';
  9775. if (attribute.metadata[entryName]) {
  9776. return attribute.metadata[entryName].string;
  9777. }
  9778. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9779. }
  9780. _getTopLevelMetadata(dracoGeometry) {
  9781. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9782. return this._getDracoMetadata(dracoMetadata);
  9783. }
  9784. _getAttributeMetadata(dracoGeometry, attributeId) {
  9785. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9786. return this._getDracoMetadata(dracoMetadata);
  9787. }
  9788. _getDracoMetadata(dracoMetadata) {
  9789. if (!dracoMetadata || !dracoMetadata.ptr) {
  9790. return {};
  9791. }
  9792. const result = {};
  9793. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9794. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9795. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9796. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9797. }
  9798. return result;
  9799. }
  9800. _getDracoMetadataField(dracoMetadata, entryName) {
  9801. const dracoArray = new this.draco.DracoInt32Array();
  9802. try {
  9803. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9804. const intArray = getInt32Array(dracoArray);
  9805. return {
  9806. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9807. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9808. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9809. intArray
  9810. };
  9811. } finally {
  9812. this.draco.destroy(dracoArray);
  9813. }
  9814. }
  9815. _disableAttributeTransforms(options) {
  9816. const {
  9817. quantizedAttributes = [],
  9818. octahedronAttributes = []
  9819. } = options;
  9820. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9821. for (const dracoAttributeName of skipAttributes) {
  9822. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9823. }
  9824. }
  9825. _getQuantizationTransform(dracoAttribute, options) {
  9826. const {
  9827. quantizedAttributes = []
  9828. } = options;
  9829. const attribute_type = dracoAttribute.attribute_type();
  9830. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9831. if (skip) {
  9832. const transform = new this.draco.AttributeQuantizationTransform();
  9833. try {
  9834. if (transform.InitFromAttribute(dracoAttribute)) {
  9835. return {
  9836. quantization_bits: transform.quantization_bits(),
  9837. range: transform.range(),
  9838. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9839. };
  9840. }
  9841. } finally {
  9842. this.draco.destroy(transform);
  9843. }
  9844. }
  9845. return null;
  9846. }
  9847. _getOctahedronTransform(dracoAttribute, options) {
  9848. const {
  9849. octahedronAttributes = []
  9850. } = options;
  9851. const attribute_type = dracoAttribute.attribute_type();
  9852. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9853. if (octahedron) {
  9854. const transform = new this.draco.AttributeQuantizationTransform();
  9855. try {
  9856. if (transform.InitFromAttribute(dracoAttribute)) {
  9857. return {
  9858. quantization_bits: transform.quantization_bits()
  9859. };
  9860. }
  9861. } finally {
  9862. this.draco.destroy(transform);
  9863. }
  9864. }
  9865. return null;
  9866. }
  9867. }
  9868. function getDracoDataType(draco, attributeType) {
  9869. switch (attributeType) {
  9870. case Float32Array:
  9871. return draco.DT_FLOAT32;
  9872. case Int8Array:
  9873. return draco.DT_INT8;
  9874. case Int16Array:
  9875. return draco.DT_INT16;
  9876. case Int32Array:
  9877. return draco.DT_INT32;
  9878. case Uint8Array:
  9879. return draco.DT_UINT8;
  9880. case Uint16Array:
  9881. return draco.DT_UINT16;
  9882. case Uint32Array:
  9883. return draco.DT_UINT32;
  9884. default:
  9885. return draco.DT_INVALID;
  9886. }
  9887. }
  9888. function getInt32Array(dracoArray) {
  9889. const numValues = dracoArray.size();
  9890. const intArray = new Int32Array(numValues);
  9891. for (let i = 0; i < numValues; i++) {
  9892. intArray[i] = dracoArray.GetValue(i);
  9893. }
  9894. return intArray;
  9895. }
  9896. function getUint32Array(dracoArray) {
  9897. const numValues = dracoArray.size();
  9898. const intArray = new Int32Array(numValues);
  9899. for (let i = 0; i < numValues; i++) {
  9900. intArray[i] = dracoArray.GetValue(i);
  9901. }
  9902. return intArray;
  9903. }
  9904. const DRACO_VERSION = '1.4.1';
  9905. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9906. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9907. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9908. let loadDecoderPromise;
  9909. async function loadDracoDecoderModule(options) {
  9910. const modules = options.modules || {};
  9911. if (modules.draco3d) {
  9912. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9913. return {
  9914. draco
  9915. };
  9916. });
  9917. } else {
  9918. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9919. }
  9920. return await loadDecoderPromise;
  9921. }
  9922. async function loadDracoDecoder(options) {
  9923. let DracoDecoderModule;
  9924. let wasmBinary;
  9925. switch (options.draco && options.draco.decoderType) {
  9926. case 'js':
  9927. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9928. break;
  9929. case 'wasm':
  9930. default:
  9931. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9932. }
  9933. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9934. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9935. }
  9936. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9937. const options = {};
  9938. if (wasmBinary) {
  9939. options.wasmBinary = wasmBinary;
  9940. }
  9941. return new Promise(resolve => {
  9942. DracoDecoderModule({ ...options,
  9943. onModuleLoaded: draco => resolve({
  9944. draco
  9945. })
  9946. });
  9947. });
  9948. }
  9949. ({
  9950. id: isBrowser$1 ? 'draco-writer' : 'draco-writer-nodejs',
  9951. name: 'Draco compressed geometry writer',
  9952. module: 'draco',
  9953. version: VERSION$4,
  9954. worker: true,
  9955. options: {
  9956. draco: {},
  9957. source: null
  9958. }
  9959. });
  9960. const DracoLoader = { ...DracoLoader$1,
  9961. parse: parse$2
  9962. };
  9963. async function parse$2(arrayBuffer, options) {
  9964. const {
  9965. draco
  9966. } = await loadDracoDecoderModule(options);
  9967. const dracoParser = new DracoParser(draco);
  9968. try {
  9969. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9970. } finally {
  9971. dracoParser.destroy();
  9972. }
  9973. }
  9974. const GL_PRIMITIVE_MODE = {
  9975. POINTS: 0x0000,
  9976. LINES: 0x0001,
  9977. LINE_LOOP: 0x0002,
  9978. LINE_STRIP: 0x0003,
  9979. TRIANGLES: 0x0004,
  9980. TRIANGLE_STRIP: 0x0005,
  9981. TRIANGLE_FAN: 0x0006
  9982. };
  9983. const GL_TYPE = {
  9984. BYTE: 5120,
  9985. UNSIGNED_BYTE: 5121,
  9986. SHORT: 5122,
  9987. UNSIGNED_SHORT: 5123,
  9988. INT: 5124,
  9989. UNSIGNED_INT: 5125,
  9990. FLOAT: 5126,
  9991. DOUBLE: 5130
  9992. };
  9993. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9994. ...GL_TYPE
  9995. };
  9996. const GL_TYPE_TO_ARRAY_TYPE = {
  9997. [GL_TYPE.DOUBLE]: Float64Array,
  9998. [GL_TYPE.FLOAT]: Float32Array,
  9999. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  10000. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  10001. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  10002. [GL_TYPE.BYTE]: Int8Array,
  10003. [GL_TYPE.SHORT]: Int16Array,
  10004. [GL_TYPE.INT]: Int32Array
  10005. };
  10006. const NAME_TO_GL_TYPE = {
  10007. DOUBLE: GL_TYPE.DOUBLE,
  10008. FLOAT: GL_TYPE.FLOAT,
  10009. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  10010. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  10011. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  10012. BYTE: GL_TYPE.BYTE,
  10013. SHORT: GL_TYPE.SHORT,
  10014. INT: GL_TYPE.INT
  10015. };
  10016. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  10017. class GLType {
  10018. static fromTypedArray(arrayOrType) {
  10019. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  10020. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  10021. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  10022. if (ArrayType === arrayOrType) {
  10023. return glType;
  10024. }
  10025. }
  10026. throw new Error(ERR_TYPE_CONVERSION);
  10027. }
  10028. static fromName(name) {
  10029. const glType = NAME_TO_GL_TYPE[name];
  10030. if (!glType) {
  10031. throw new Error(ERR_TYPE_CONVERSION);
  10032. }
  10033. return glType;
  10034. }
  10035. static getArrayType(glType) {
  10036. switch (glType) {
  10037. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  10038. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  10039. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  10040. return Uint16Array;
  10041. default:
  10042. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  10043. if (!ArrayType) {
  10044. throw new Error(ERR_TYPE_CONVERSION);
  10045. }
  10046. return ArrayType;
  10047. }
  10048. }
  10049. static getByteSize(glType) {
  10050. const ArrayType = GLType.getArrayType(glType);
  10051. return ArrayType.BYTES_PER_ELEMENT;
  10052. }
  10053. static validate(glType) {
  10054. return Boolean(GLType.getArrayType(glType));
  10055. }
  10056. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  10057. if (length === undefined) {
  10058. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  10059. }
  10060. const ArrayType = GLType.getArrayType(glType);
  10061. return new ArrayType(buffer, byteOffset, length);
  10062. }
  10063. }
  10064. function assert$2(condition, message) {
  10065. if (!condition) {
  10066. throw new Error("math.gl assertion failed. ".concat(message));
  10067. }
  10068. }
  10069. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  10070. const r5 = rgb565 >> 11 & 31;
  10071. const g6 = rgb565 >> 5 & 63;
  10072. const b5 = rgb565 & 31;
  10073. target[0] = r5 << 3;
  10074. target[1] = g6 << 2;
  10075. target[2] = b5 << 3;
  10076. return target;
  10077. }
  10078. new Vector2();
  10079. new Vector3();
  10080. new Vector2();
  10081. new Vector2();
  10082. function fromSNorm(value, rangeMaximum = 255) {
  10083. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  10084. }
  10085. function signNotZero(value) {
  10086. return value < 0.0 ? -1.0 : 1.0;
  10087. }
  10088. function octDecodeInRange(x, y, rangeMax, result) {
  10089. assert$2(result);
  10090. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  10091. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  10092. }
  10093. result.x = fromSNorm(x, rangeMax);
  10094. result.y = fromSNorm(y, rangeMax);
  10095. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  10096. if (result.z < 0.0) {
  10097. const oldVX = result.x;
  10098. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  10099. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  10100. }
  10101. return result.normalize();
  10102. }
  10103. function octDecode(x, y, result) {
  10104. return octDecodeInRange(x, y, 255, result);
  10105. }
  10106. class Tile3DFeatureTable {
  10107. constructor(featureTableJson, featureTableBinary) {
  10108. _defineProperty(this, "json", void 0);
  10109. _defineProperty(this, "buffer", void 0);
  10110. _defineProperty(this, "featuresLength", 0);
  10111. _defineProperty(this, "_cachedTypedArrays", {});
  10112. this.json = featureTableJson;
  10113. this.buffer = featureTableBinary;
  10114. }
  10115. getExtension(extensionName) {
  10116. return this.json.extensions && this.json.extensions[extensionName];
  10117. }
  10118. hasProperty(propertyName) {
  10119. return Boolean(this.json[propertyName]);
  10120. }
  10121. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  10122. const jsonValue = this.json[propertyName];
  10123. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  10124. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  10125. }
  10126. return jsonValue;
  10127. }
  10128. getPropertyArray(propertyName, componentType, componentLength) {
  10129. const jsonValue = this.json[propertyName];
  10130. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  10131. if ('componentType' in jsonValue) {
  10132. componentType = GLType.fromName(jsonValue.componentType);
  10133. }
  10134. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  10135. }
  10136. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  10137. }
  10138. getProperty(propertyName, componentType, componentLength, featureId, result) {
  10139. const jsonValue = this.json[propertyName];
  10140. if (!jsonValue) {
  10141. return jsonValue;
  10142. }
  10143. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  10144. if (componentLength === 1) {
  10145. return typedArray[featureId];
  10146. }
  10147. for (let i = 0; i < componentLength; ++i) {
  10148. result[i] = typedArray[componentLength * featureId + i];
  10149. }
  10150. return result;
  10151. }
  10152. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  10153. const cachedTypedArrays = this._cachedTypedArrays;
  10154. let typedArray = cachedTypedArrays[propertyName];
  10155. if (!typedArray) {
  10156. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  10157. cachedTypedArrays[propertyName] = typedArray;
  10158. }
  10159. return typedArray;
  10160. }
  10161. _getTypedArrayFromArray(propertyName, componentType, array) {
  10162. const cachedTypedArrays = this._cachedTypedArrays;
  10163. let typedArray = cachedTypedArrays[propertyName];
  10164. if (!typedArray) {
  10165. typedArray = GLType.createTypedArray(componentType, array);
  10166. cachedTypedArrays[propertyName] = typedArray;
  10167. }
  10168. return typedArray;
  10169. }
  10170. }
  10171. const COMPONENTS_PER_ATTRIBUTE = {
  10172. SCALAR: 1,
  10173. VEC2: 2,
  10174. VEC3: 3,
  10175. VEC4: 4,
  10176. MAT2: 4,
  10177. MAT3: 9,
  10178. MAT4: 16
  10179. };
  10180. const UNPACKER = {
  10181. SCALAR: (values, i) => values[i],
  10182. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  10183. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  10184. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  10185. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  10186. MAT3: (values, i) => [values[9 * i + 0], values[9 * i + 1], values[9 * i + 2], values[9 * i + 3], values[9 * i + 4], values[9 * i + 5], values[9 * i + 6], values[9 * i + 7], values[9 * i + 8]],
  10187. MAT4: (values, i) => [values[16 * i + 0], values[16 * i + 1], values[16 * i + 2], values[16 * i + 3], values[16 * i + 4], values[16 * i + 5], values[16 * i + 6], values[16 * i + 7], values[16 * i + 8], values[16 * i + 9], values[16 * i + 10], values[16 * i + 11], values[16 * i + 12], values[16 * i + 13], values[16 * i + 14], values[16 * i + 15]]
  10188. };
  10189. const PACKER = {
  10190. SCALAR: (x, values, i) => {
  10191. values[i] = x;
  10192. },
  10193. VEC2: (x, values, i) => {
  10194. values[2 * i + 0] = x[0];
  10195. values[2 * i + 1] = x[1];
  10196. },
  10197. VEC3: (x, values, i) => {
  10198. values[3 * i + 0] = x[0];
  10199. values[3 * i + 1] = x[1];
  10200. values[3 * i + 2] = x[2];
  10201. },
  10202. VEC4: (x, values, i) => {
  10203. values[4 * i + 0] = x[0];
  10204. values[4 * i + 1] = x[1];
  10205. values[4 * i + 2] = x[2];
  10206. values[4 * i + 3] = x[3];
  10207. },
  10208. MAT2: (x, values, i) => {
  10209. values[4 * i + 0] = x[0];
  10210. values[4 * i + 1] = x[1];
  10211. values[4 * i + 2] = x[2];
  10212. values[4 * i + 3] = x[3];
  10213. },
  10214. MAT3: (x, values, i) => {
  10215. values[9 * i + 0] = x[0];
  10216. values[9 * i + 1] = x[1];
  10217. values[9 * i + 2] = x[2];
  10218. values[9 * i + 3] = x[3];
  10219. values[9 * i + 4] = x[4];
  10220. values[9 * i + 5] = x[5];
  10221. values[9 * i + 6] = x[6];
  10222. values[9 * i + 7] = x[7];
  10223. values[9 * i + 8] = x[8];
  10224. values[9 * i + 9] = x[9];
  10225. },
  10226. MAT4: (x, values, i) => {
  10227. values[16 * i + 0] = x[0];
  10228. values[16 * i + 1] = x[1];
  10229. values[16 * i + 2] = x[2];
  10230. values[16 * i + 3] = x[3];
  10231. values[16 * i + 4] = x[4];
  10232. values[16 * i + 5] = x[5];
  10233. values[16 * i + 6] = x[6];
  10234. values[16 * i + 7] = x[7];
  10235. values[16 * i + 8] = x[8];
  10236. values[16 * i + 9] = x[9];
  10237. values[16 * i + 10] = x[10];
  10238. values[16 * i + 11] = x[11];
  10239. values[16 * i + 12] = x[12];
  10240. values[16 * i + 13] = x[13];
  10241. values[16 * i + 14] = x[14];
  10242. values[16 * i + 15] = x[15];
  10243. }
  10244. };
  10245. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  10246. const {
  10247. componentType
  10248. } = tile3DAccessor;
  10249. assert$7(tile3DAccessor.componentType);
  10250. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  10251. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  10252. const unpacker = UNPACKER[tile3DAccessor.type];
  10253. const packer = PACKER[tile3DAccessor.type];
  10254. byteOffset += tile3DAccessor.byteOffset;
  10255. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  10256. return {
  10257. values,
  10258. type,
  10259. size,
  10260. unpacker,
  10261. packer
  10262. };
  10263. }
  10264. const defined$1 = x => x !== undefined;
  10265. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  10266. if (!jsonHeader) {
  10267. return null;
  10268. }
  10269. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  10270. const legacyHierarchy = jsonHeader.HIERARCHY;
  10271. if (legacyHierarchy) {
  10272. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  10273. jsonHeader.extensions = jsonHeader.extensions || {};
  10274. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  10275. hierarchy = legacyHierarchy;
  10276. }
  10277. if (!hierarchy) {
  10278. return null;
  10279. }
  10280. return initializeHierarchyValues(hierarchy, binaryBody);
  10281. }
  10282. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  10283. let i;
  10284. let classId;
  10285. let binaryAccessor;
  10286. const instancesLength = hierarchyJson.instancesLength;
  10287. const classes = hierarchyJson.classes;
  10288. let classIds = hierarchyJson.classIds;
  10289. let parentCounts = hierarchyJson.parentCounts;
  10290. let parentIds = hierarchyJson.parentIds;
  10291. let parentIdsLength = instancesLength;
  10292. if (defined$1(classIds.byteOffset)) {
  10293. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  10294. classIds.type = AttributeType.SCALAR;
  10295. binaryAccessor = getBinaryAccessor(classIds);
  10296. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  10297. }
  10298. let parentIndexes;
  10299. if (defined$1(parentCounts)) {
  10300. if (defined$1(parentCounts.byteOffset)) {
  10301. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  10302. parentCounts.type = AttributeType.SCALAR;
  10303. binaryAccessor = getBinaryAccessor(parentCounts);
  10304. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  10305. }
  10306. parentIndexes = new Uint16Array(instancesLength);
  10307. parentIdsLength = 0;
  10308. for (i = 0; i < instancesLength; ++i) {
  10309. parentIndexes[i] = parentIdsLength;
  10310. parentIdsLength += parentCounts[i];
  10311. }
  10312. }
  10313. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  10314. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  10315. parentIds.type = AttributeType.SCALAR;
  10316. binaryAccessor = getBinaryAccessor(parentIds);
  10317. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  10318. }
  10319. const classesLength = classes.length;
  10320. for (i = 0; i < classesLength; ++i) {
  10321. const classInstancesLength = classes[i].length;
  10322. const properties = classes[i].instances;
  10323. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  10324. classes[i].instances = combine(binaryProperties, properties);
  10325. }
  10326. const classCounts = new Array(classesLength).fill(0);
  10327. const classIndexes = new Uint16Array(instancesLength);
  10328. for (i = 0; i < instancesLength; ++i) {
  10329. classId = classIds[i];
  10330. classIndexes[i] = classCounts[classId];
  10331. ++classCounts[classId];
  10332. }
  10333. const hierarchy = {
  10334. classes,
  10335. classIds,
  10336. classIndexes,
  10337. parentCounts,
  10338. parentIndexes,
  10339. parentIds
  10340. };
  10341. validateHierarchy(hierarchy);
  10342. return hierarchy;
  10343. }
  10344. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  10345. if (!hierarchy) {
  10346. return;
  10347. }
  10348. const parentCounts = hierarchy.parentCounts;
  10349. const parentIds = hierarchy.parentIds;
  10350. if (parentIds) {
  10351. return endConditionCallback(hierarchy, instanceIndex);
  10352. }
  10353. if (parentCounts > 0) {
  10354. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  10355. }
  10356. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  10357. }
  10358. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  10359. const classIds = hierarchy.classIds;
  10360. const parentCounts = hierarchy.parentCounts;
  10361. const parentIds = hierarchy.parentIds;
  10362. const parentIndexes = hierarchy.parentIndexes;
  10363. const instancesLength = classIds.length;
  10364. const visited = scratchVisited;
  10365. visited.length = Math.max(visited.length, instancesLength);
  10366. const visitedMarker = ++marker;
  10367. const stack = scratchStack;
  10368. stack.length = 0;
  10369. stack.push(instanceIndex);
  10370. while (stack.length > 0) {
  10371. instanceIndex = stack.pop();
  10372. if (visited[instanceIndex] === visitedMarker) {
  10373. continue;
  10374. }
  10375. visited[instanceIndex] = visitedMarker;
  10376. const result = endConditionCallback(hierarchy, instanceIndex);
  10377. if (defined$1(result)) {
  10378. return result;
  10379. }
  10380. const parentCount = parentCounts[instanceIndex];
  10381. const parentIndex = parentIndexes[instanceIndex];
  10382. for (let i = 0; i < parentCount; ++i) {
  10383. const parentId = parentIds[parentIndex + i];
  10384. if (parentId !== instanceIndex) {
  10385. stack.push(parentId);
  10386. }
  10387. }
  10388. }
  10389. return null;
  10390. }
  10391. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  10392. let hasParent = true;
  10393. while (hasParent) {
  10394. const result = endConditionCallback(hierarchy, instanceIndex);
  10395. if (defined$1(result)) {
  10396. return result;
  10397. }
  10398. const parentId = hierarchy.parentIds[instanceIndex];
  10399. hasParent = parentId !== instanceIndex;
  10400. instanceIndex = parentId;
  10401. }
  10402. throw new Error('traverseHierarchySingleParent');
  10403. }
  10404. function validateHierarchy(hierarchy) {
  10405. const classIds = hierarchy.classIds;
  10406. const instancesLength = classIds.length;
  10407. for (let i = 0; i < instancesLength; ++i) {
  10408. validateInstance(hierarchy, i, stack);
  10409. }
  10410. }
  10411. function validateInstance(hierarchy, instanceIndex, stack) {
  10412. const parentCounts = hierarchy.parentCounts;
  10413. const parentIds = hierarchy.parentIds;
  10414. const parentIndexes = hierarchy.parentIndexes;
  10415. const classIds = hierarchy.classIds;
  10416. const instancesLength = classIds.length;
  10417. if (!defined$1(parentIds)) {
  10418. return;
  10419. }
  10420. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  10421. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  10422. stack.push(instanceIndex);
  10423. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10424. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10425. for (let i = 0; i < parentCount; ++i) {
  10426. const parentId = parentIds[parentIndex + i];
  10427. if (parentId !== instanceIndex) {
  10428. validateInstance(hierarchy, parentId, stack);
  10429. }
  10430. }
  10431. stack.pop(instanceIndex);
  10432. }
  10433. function defined(x) {
  10434. return x !== undefined && x !== null;
  10435. }
  10436. const clone = (x, y) => x;
  10437. const IGNORED_PROPERTY_FIELDS = {
  10438. HIERARCHY: true,
  10439. extensions: true,
  10440. extras: true
  10441. };
  10442. class Tile3DBatchTableParser {
  10443. constructor(json, binary, featureCount, options = {}) {
  10444. var _this$json;
  10445. _defineProperty(this, "json", void 0);
  10446. _defineProperty(this, "binary", void 0);
  10447. _defineProperty(this, "featureCount", void 0);
  10448. _defineProperty(this, "_extensions", void 0);
  10449. _defineProperty(this, "_properties", void 0);
  10450. _defineProperty(this, "_binaryProperties", void 0);
  10451. _defineProperty(this, "_hierarchy", void 0);
  10452. assert$7(featureCount >= 0);
  10453. this.json = json || {};
  10454. this.binary = binary;
  10455. this.featureCount = featureCount;
  10456. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10457. this._properties = {};
  10458. for (const propertyName in this.json) {
  10459. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10460. this._properties[propertyName] = this.json[propertyName];
  10461. }
  10462. }
  10463. this._binaryProperties = this._initializeBinaryProperties();
  10464. if (options['3DTILES_batch_table_hierarchy']) {
  10465. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10466. }
  10467. }
  10468. getExtension(extensionName) {
  10469. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10470. }
  10471. memorySizeInBytes() {
  10472. return 0;
  10473. }
  10474. isClass(batchId, className) {
  10475. this._checkBatchId(batchId);
  10476. assert$7(typeof className === 'string', className);
  10477. if (this._hierarchy) {
  10478. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10479. const classId = hierarchy.classIds[instanceIndex];
  10480. const instanceClass = hierarchy.classes[classId];
  10481. return instanceClass.name === className;
  10482. });
  10483. return defined(result);
  10484. }
  10485. return false;
  10486. }
  10487. isExactClass(batchId, className) {
  10488. assert$7(typeof className === 'string', className);
  10489. return this.getExactClassName(batchId) === className;
  10490. }
  10491. getExactClassName(batchId) {
  10492. this._checkBatchId(batchId);
  10493. if (this._hierarchy) {
  10494. const classId = this._hierarchy.classIds[batchId];
  10495. const instanceClass = this._hierarchy.classes[classId];
  10496. return instanceClass.name;
  10497. }
  10498. return undefined;
  10499. }
  10500. hasProperty(batchId, name) {
  10501. this._checkBatchId(batchId);
  10502. assert$7(typeof name === 'string', name);
  10503. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10504. }
  10505. getPropertyNames(batchId, results) {
  10506. this._checkBatchId(batchId);
  10507. results = defined(results) ? results : [];
  10508. results.length = 0;
  10509. const propertyNames = Object.keys(this._properties);
  10510. results.push(...propertyNames);
  10511. if (this._hierarchy) {
  10512. this._getPropertyNamesInHierarchy(batchId, results);
  10513. }
  10514. return results;
  10515. }
  10516. getProperty(batchId, name) {
  10517. this._checkBatchId(batchId);
  10518. assert$7(typeof name === 'string', name);
  10519. if (this._binaryProperties) {
  10520. const binaryProperty = this._binaryProperties[name];
  10521. if (defined(binaryProperty)) {
  10522. return this._getBinaryProperty(binaryProperty, batchId);
  10523. }
  10524. }
  10525. const propertyValues = this._properties[name];
  10526. if (defined(propertyValues)) {
  10527. return clone(propertyValues[batchId]);
  10528. }
  10529. if (this._hierarchy) {
  10530. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10531. if (defined(hierarchyProperty)) {
  10532. return hierarchyProperty;
  10533. }
  10534. }
  10535. return undefined;
  10536. }
  10537. setProperty(batchId, name, value) {
  10538. const featureCount = this.featureCount;
  10539. this._checkBatchId(batchId);
  10540. assert$7(typeof name === 'string', name);
  10541. if (this._binaryProperties) {
  10542. const binaryProperty = this._binaryProperties[name];
  10543. if (binaryProperty) {
  10544. this._setBinaryProperty(binaryProperty, batchId, value);
  10545. return;
  10546. }
  10547. }
  10548. if (this._hierarchy) {
  10549. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10550. return;
  10551. }
  10552. }
  10553. let propertyValues = this._properties[name];
  10554. if (!defined(propertyValues)) {
  10555. this._properties[name] = new Array(featureCount);
  10556. propertyValues = this._properties[name];
  10557. }
  10558. propertyValues[batchId] = clone(value);
  10559. }
  10560. _checkBatchId(batchId) {
  10561. const valid = batchId >= 0 && batchId < this.featureCount;
  10562. if (!valid) {
  10563. throw new Error('batchId not in range [0, featureCount - 1].');
  10564. }
  10565. }
  10566. _getBinaryProperty(binaryProperty, index) {
  10567. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10568. }
  10569. _setBinaryProperty(binaryProperty, index, value) {
  10570. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10571. }
  10572. _initializeBinaryProperties() {
  10573. let binaryProperties = null;
  10574. for (const name in this._properties) {
  10575. const property = this._properties[name];
  10576. const binaryProperty = this._initializeBinaryProperty(name, property);
  10577. if (binaryProperty) {
  10578. binaryProperties = binaryProperties || {};
  10579. binaryProperties[name] = binaryProperty;
  10580. }
  10581. }
  10582. return binaryProperties;
  10583. }
  10584. _initializeBinaryProperty(name, property) {
  10585. if ('byteOffset' in property) {
  10586. const tile3DAccessor = property;
  10587. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10588. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10589. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10590. return {
  10591. typedArray: accessor.values,
  10592. componentCount: accessor.size,
  10593. unpack: accessor.unpacker,
  10594. pack: accessor.packer
  10595. };
  10596. }
  10597. return null;
  10598. }
  10599. _hasPropertyInHierarchy(batchId, name) {
  10600. if (!this._hierarchy) {
  10601. return false;
  10602. }
  10603. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10604. const classId = hierarchy.classIds[instanceIndex];
  10605. const instances = hierarchy.classes[classId].instances;
  10606. return defined(instances[name]);
  10607. });
  10608. return defined(result);
  10609. }
  10610. _getPropertyNamesInHierarchy(batchId, results) {
  10611. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10612. const classId = hierarchy.classIds[instanceIndex];
  10613. const instances = hierarchy.classes[classId].instances;
  10614. for (const name in instances) {
  10615. if (instances.hasOwnProperty(name)) {
  10616. if (results.indexOf(name) === -1) {
  10617. results.push(name);
  10618. }
  10619. }
  10620. }
  10621. });
  10622. }
  10623. _getHierarchyProperty(batchId, name) {
  10624. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10625. const classId = hierarchy.classIds[instanceIndex];
  10626. const instanceClass = hierarchy.classes[classId];
  10627. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10628. const propertyValues = instanceClass.instances[name];
  10629. if (defined(propertyValues)) {
  10630. if (defined(propertyValues.typedArray)) {
  10631. return this._getBinaryProperty(propertyValues, indexInClass);
  10632. }
  10633. return clone(propertyValues[indexInClass]);
  10634. }
  10635. return null;
  10636. });
  10637. }
  10638. _setHierarchyProperty(batchTable, batchId, name, value) {
  10639. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10640. const classId = hierarchy.classIds[instanceIndex];
  10641. const instanceClass = hierarchy.classes[classId];
  10642. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10643. const propertyValues = instanceClass.instances[name];
  10644. if (defined(propertyValues)) {
  10645. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10646. if (defined(propertyValues.typedArray)) {
  10647. this._setBinaryProperty(propertyValues, indexInClass, value);
  10648. } else {
  10649. propertyValues[indexInClass] = clone(value);
  10650. }
  10651. return true;
  10652. }
  10653. return false;
  10654. });
  10655. return defined(result);
  10656. }
  10657. }
  10658. const SIZEOF_UINT32$1 = 4;
  10659. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10660. const view = new DataView(arrayBuffer);
  10661. tile.magic = view.getUint32(byteOffset, true);
  10662. byteOffset += SIZEOF_UINT32$1;
  10663. tile.version = view.getUint32(byteOffset, true);
  10664. byteOffset += SIZEOF_UINT32$1;
  10665. tile.byteLength = view.getUint32(byteOffset, true);
  10666. byteOffset += SIZEOF_UINT32$1;
  10667. if (tile.version !== 1) {
  10668. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10669. }
  10670. return byteOffset;
  10671. }
  10672. const SIZEOF_UINT32 = 4;
  10673. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10674. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10675. const view = new DataView(arrayBuffer);
  10676. let batchLength;
  10677. tile.header = tile.header || {};
  10678. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10679. byteOffset += SIZEOF_UINT32;
  10680. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10681. byteOffset += SIZEOF_UINT32;
  10682. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10683. byteOffset += SIZEOF_UINT32;
  10684. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10685. byteOffset += SIZEOF_UINT32;
  10686. if (batchTableJsonByteLength >= 570425344) {
  10687. byteOffset -= SIZEOF_UINT32 * 2;
  10688. batchLength = featureTableJsonByteLength;
  10689. batchTableJsonByteLength = featureTableBinaryByteLength;
  10690. batchTableBinaryByteLength = 0;
  10691. featureTableJsonByteLength = 0;
  10692. featureTableBinaryByteLength = 0;
  10693. console.warn(DEPRECATION_WARNING);
  10694. } else if (batchTableBinaryByteLength >= 570425344) {
  10695. byteOffset -= SIZEOF_UINT32;
  10696. batchLength = batchTableJsonByteLength;
  10697. batchTableJsonByteLength = featureTableJsonByteLength;
  10698. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10699. featureTableJsonByteLength = 0;
  10700. featureTableBinaryByteLength = 0;
  10701. console.warn(DEPRECATION_WARNING);
  10702. }
  10703. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10704. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10705. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10706. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10707. tile.header.batchLength = batchLength;
  10708. return byteOffset;
  10709. }
  10710. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10711. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10712. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10713. return byteOffset;
  10714. }
  10715. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10716. const {
  10717. featureTableJsonByteLength,
  10718. featureTableBinaryByteLength,
  10719. batchLength
  10720. } = tile.header;
  10721. tile.featureTableJson = {
  10722. BATCH_LENGTH: batchLength || 0
  10723. };
  10724. if (featureTableJsonByteLength > 0) {
  10725. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10726. tile.featureTableJson = JSON.parse(featureTableString);
  10727. }
  10728. byteOffset += featureTableJsonByteLength;
  10729. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10730. byteOffset += featureTableBinaryByteLength;
  10731. return byteOffset;
  10732. }
  10733. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10734. const {
  10735. batchTableJsonByteLength,
  10736. batchTableBinaryByteLength
  10737. } = tile.header;
  10738. if (batchTableJsonByteLength > 0) {
  10739. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10740. tile.batchTableJson = JSON.parse(batchTableString);
  10741. byteOffset += batchTableJsonByteLength;
  10742. if (batchTableBinaryByteLength > 0) {
  10743. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10744. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10745. byteOffset += batchTableBinaryByteLength;
  10746. }
  10747. }
  10748. return byteOffset;
  10749. }
  10750. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10751. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10752. return null;
  10753. }
  10754. const {
  10755. batchIds,
  10756. isRGB565,
  10757. pointCount
  10758. } = tile;
  10759. if (batchIds && batchTable) {
  10760. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10761. for (let i = 0; i < pointCount; i++) {
  10762. const batchId = batchIds[i];
  10763. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10764. const color = dimensions.map(d => d * 255);
  10765. colorArray[i * 3] = color[0];
  10766. colorArray[i * 3 + 1] = color[1];
  10767. colorArray[i * 3 + 2] = color[2];
  10768. }
  10769. return {
  10770. type: GL$1.UNSIGNED_BYTE,
  10771. value: colorArray,
  10772. size: 3,
  10773. normalized: true
  10774. };
  10775. }
  10776. if (isRGB565) {
  10777. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10778. for (let i = 0; i < pointCount; i++) {
  10779. const color = decodeRGB565(colors[i]);
  10780. colorArray[i * 3] = color[0];
  10781. colorArray[i * 3 + 1] = color[1];
  10782. colorArray[i * 3 + 2] = color[2];
  10783. }
  10784. return {
  10785. type: GL$1.UNSIGNED_BYTE,
  10786. value: colorArray,
  10787. size: 3,
  10788. normalized: true
  10789. };
  10790. }
  10791. if (colors && colors.length === pointCount * 3) {
  10792. return {
  10793. type: GL$1.UNSIGNED_BYTE,
  10794. value: colors,
  10795. size: 3,
  10796. normalized: true
  10797. };
  10798. }
  10799. return {
  10800. type: GL$1.UNSIGNED_BYTE,
  10801. value: colors,
  10802. size: 4,
  10803. normalized: true
  10804. };
  10805. }
  10806. const scratchNormal = new Vector3();
  10807. function normalize3DTileNormalAttribute(tile, normals) {
  10808. if (!normals) {
  10809. return null;
  10810. }
  10811. if (tile.isOctEncoded16P) {
  10812. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10813. for (let i = 0; i < tile.pointsLength; i++) {
  10814. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10815. scratchNormal.toArray(decodedArray, i * 3);
  10816. }
  10817. return {
  10818. type: GL$1.FLOAT,
  10819. size: 2,
  10820. value: decodedArray
  10821. };
  10822. }
  10823. return {
  10824. type: GL$1.FLOAT,
  10825. size: 2,
  10826. value: normals
  10827. };
  10828. }
  10829. function normalize3DTilePositionAttribute(tile, positions, options) {
  10830. if (!tile.isQuantized) {
  10831. return positions;
  10832. }
  10833. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10834. tile.isQuantized = false;
  10835. return decodeQuantizedPositions(tile, positions);
  10836. }
  10837. return {
  10838. type: GL$1.UNSIGNED_SHORT,
  10839. value: positions,
  10840. size: 3,
  10841. normalized: true
  10842. };
  10843. }
  10844. function decodeQuantizedPositions(tile, positions) {
  10845. const scratchPosition = new Vector3();
  10846. const decodedArray = new Float32Array(tile.pointCount * 3);
  10847. for (let i = 0; i < tile.pointCount; i++) {
  10848. scratchPosition.set(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]).scale(1 / tile.quantizedRange).multiply(tile.quantizedVolumeScale).add(tile.quantizedVolumeOffset).toArray(decodedArray, i * 3);
  10849. }
  10850. return decodedArray;
  10851. }
  10852. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10853. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10854. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10855. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10856. initializeTile(tile);
  10857. const {
  10858. featureTable,
  10859. batchTable
  10860. } = parsePointCloudTables(tile);
  10861. await parseDraco(tile, featureTable, batchTable, options, context);
  10862. parsePositions(tile, featureTable, options);
  10863. parseColors(tile, featureTable, batchTable);
  10864. parseNormals(tile, featureTable);
  10865. return byteOffset;
  10866. }
  10867. function initializeTile(tile) {
  10868. tile.attributes = {
  10869. positions: null,
  10870. colors: null,
  10871. normals: null,
  10872. batchIds: null
  10873. };
  10874. tile.isQuantized = false;
  10875. tile.isTranslucent = false;
  10876. tile.isRGB565 = false;
  10877. tile.isOctEncoded16P = false;
  10878. }
  10879. function parsePointCloudTables(tile) {
  10880. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10881. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10882. if (!Number.isFinite(pointsLength)) {
  10883. throw new Error('POINTS_LENGTH must be defined');
  10884. }
  10885. featureTable.featuresLength = pointsLength;
  10886. tile.featuresLength = pointsLength;
  10887. tile.pointsLength = pointsLength;
  10888. tile.pointCount = pointsLength;
  10889. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10890. const batchTable = parseBatchIds(tile, featureTable);
  10891. return {
  10892. featureTable,
  10893. batchTable
  10894. };
  10895. }
  10896. function parsePositions(tile, featureTable, options) {
  10897. if (!tile.attributes.positions) {
  10898. if (featureTable.hasProperty('POSITION')) {
  10899. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10900. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10901. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10902. tile.isQuantized = true;
  10903. tile.quantizedRange = (1 << 16) - 1;
  10904. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10905. if (!tile.quantizedVolumeScale) {
  10906. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10907. }
  10908. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10909. if (!tile.quantizedVolumeOffset) {
  10910. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10911. }
  10912. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10913. }
  10914. }
  10915. if (!tile.attributes.positions) {
  10916. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10917. }
  10918. }
  10919. function parseColors(tile, featureTable, batchTable) {
  10920. if (!tile.attributes.colors) {
  10921. let colors = null;
  10922. if (featureTable.hasProperty('RGBA')) {
  10923. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10924. tile.isTranslucent = true;
  10925. } else if (featureTable.hasProperty('RGB')) {
  10926. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10927. } else if (featureTable.hasProperty('RGB565')) {
  10928. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10929. tile.isRGB565 = true;
  10930. }
  10931. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10932. }
  10933. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10934. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10935. }
  10936. }
  10937. function parseNormals(tile, featureTable) {
  10938. if (!tile.attributes.normals) {
  10939. let normals = null;
  10940. if (featureTable.hasProperty('NORMAL')) {
  10941. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10942. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10943. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10944. tile.isOctEncoded16P = true;
  10945. }
  10946. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10947. }
  10948. }
  10949. function parseBatchIds(tile, featureTable) {
  10950. let batchTable = null;
  10951. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10952. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10953. if (tile.batchIds) {
  10954. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10955. if (!batchFeatureLength) {
  10956. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10957. }
  10958. const {
  10959. batchTableJson,
  10960. batchTableBinary
  10961. } = tile;
  10962. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10963. }
  10964. }
  10965. return batchTable;
  10966. }
  10967. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10968. let dracoBuffer;
  10969. let dracoFeatureTableProperties;
  10970. let dracoBatchTableProperties;
  10971. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10972. if (batchTableDraco) {
  10973. dracoBatchTableProperties = batchTableDraco.properties;
  10974. }
  10975. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10976. if (featureTableDraco) {
  10977. dracoFeatureTableProperties = featureTableDraco.properties;
  10978. const dracoByteOffset = featureTableDraco.byteOffset;
  10979. const dracoByteLength = featureTableDraco.byteLength;
  10980. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10981. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10982. }
  10983. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10984. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10985. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10986. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10987. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10988. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10989. }
  10990. if (!dracoBuffer) {
  10991. return true;
  10992. }
  10993. const dracoData = {
  10994. buffer: dracoBuffer,
  10995. properties: { ...dracoFeatureTableProperties,
  10996. ...dracoBatchTableProperties
  10997. },
  10998. featureTableProperties: dracoFeatureTableProperties,
  10999. batchTableProperties: dracoBatchTableProperties,
  11000. dequantizeInShader: false
  11001. };
  11002. return await loadDraco(tile, dracoData, options, context);
  11003. }
  11004. async function loadDraco(tile, dracoData, options, context) {
  11005. const {
  11006. parse
  11007. } = context;
  11008. const dracoOptions = { ...options,
  11009. draco: { ...options.draco,
  11010. extraAttributes: dracoData.batchTableProperties || {}
  11011. }
  11012. };
  11013. delete dracoOptions['3d-tiles'];
  11014. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  11015. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  11016. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  11017. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  11018. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  11019. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  11020. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  11021. if (isQuantizedDraco) {
  11022. const quantization = data.POSITION.data.quantization;
  11023. const range = quantization.range;
  11024. tile.quantizedVolumeScale = new Vector3(range, range, range);
  11025. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  11026. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  11027. tile.isQuantizedDraco = true;
  11028. }
  11029. if (isOctEncodedDraco) {
  11030. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  11031. tile.isOctEncodedDraco = true;
  11032. }
  11033. const batchTableAttributes = {};
  11034. if (dracoData.batchTableProperties) {
  11035. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  11036. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  11037. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  11038. }
  11039. }
  11040. }
  11041. tile.attributes = {
  11042. positions: decodedPositions,
  11043. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  11044. normals: decodedNormals,
  11045. batchIds: decodedBatchIds,
  11046. ...batchTableAttributes
  11047. };
  11048. }
  11049. const VERSION$3 = "3.2.12" ;
  11050. const VERSION$2 = "3.2.12" ;
  11051. const VERSION$1 = "3.2.12" ;
  11052. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  11053. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  11054. let loadBasisTranscoderPromise;
  11055. async function loadBasisTrascoderModule(options) {
  11056. const modules = options.modules || {};
  11057. if (modules.basis) {
  11058. return modules.basis;
  11059. }
  11060. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  11061. return await loadBasisTranscoderPromise;
  11062. }
  11063. async function loadBasisTrascoder(options) {
  11064. let BASIS = null;
  11065. let wasmBinary = null;
  11066. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  11067. BASIS = BASIS || globalThis.BASIS;
  11068. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  11069. }
  11070. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  11071. const options = {};
  11072. if (wasmBinary) {
  11073. options.wasmBinary = wasmBinary;
  11074. }
  11075. return new Promise(resolve => {
  11076. BasisModule(options).then(module => {
  11077. const {
  11078. BasisFile,
  11079. initializeBasis
  11080. } = module;
  11081. initializeBasis();
  11082. resolve({
  11083. BasisFile
  11084. });
  11085. });
  11086. });
  11087. }
  11088. let loadBasisEncoderPromise;
  11089. async function loadBasisEncoderModule(options) {
  11090. const modules = options.modules || {};
  11091. if (modules.basisEncoder) {
  11092. return modules.basisEncoder;
  11093. }
  11094. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  11095. return await loadBasisEncoderPromise;
  11096. }
  11097. async function loadBasisEncoder(options) {
  11098. let BASIS_ENCODER = null;
  11099. let wasmBinary = null;
  11100. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  11101. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  11102. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  11103. }
  11104. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  11105. const options = {};
  11106. if (wasmBinary) {
  11107. options.wasmBinary = wasmBinary;
  11108. }
  11109. return new Promise(resolve => {
  11110. BasisEncoderModule(options).then(module => {
  11111. const {
  11112. BasisFile,
  11113. KTX2File,
  11114. initializeBasis,
  11115. BasisEncoder
  11116. } = module;
  11117. initializeBasis();
  11118. resolve({
  11119. BasisFile,
  11120. KTX2File,
  11121. BasisEncoder
  11122. });
  11123. });
  11124. });
  11125. }
  11126. const GL_EXTENSIONS_CONSTANTS = {
  11127. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  11128. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  11129. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  11130. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  11131. COMPRESSED_R11_EAC: 0x9270,
  11132. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  11133. COMPRESSED_RG11_EAC: 0x9272,
  11134. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  11135. COMPRESSED_RGB8_ETC2: 0x9274,
  11136. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  11137. COMPRESSED_SRGB8_ETC2: 0x9276,
  11138. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  11139. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  11140. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  11141. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  11142. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  11143. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  11144. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  11145. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  11146. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  11147. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  11148. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  11149. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  11150. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  11151. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  11152. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  11153. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  11154. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  11155. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  11156. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  11157. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  11158. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  11159. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  11160. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  11161. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  11162. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  11163. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  11164. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  11165. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  11166. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  11167. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  11168. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  11169. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  11170. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  11171. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  11172. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  11173. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  11174. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  11175. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  11176. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  11177. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  11178. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  11179. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  11180. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  11181. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  11182. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  11183. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  11184. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  11185. };
  11186. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  11187. const WEBGL_EXTENSIONS = {
  11188. WEBGL_compressed_texture_s3tc: 'dxt',
  11189. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  11190. WEBGL_compressed_texture_etc1: 'etc1',
  11191. WEBGL_compressed_texture_etc: 'etc2',
  11192. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  11193. WEBGL_compressed_texture_atc: 'atc',
  11194. WEBGL_compressed_texture_astc: 'astc',
  11195. EXT_texture_compression_rgtc: 'rgtc'
  11196. };
  11197. let formats = null;
  11198. function getSupportedGPUTextureFormats(gl) {
  11199. if (!formats) {
  11200. gl = gl || getWebGLContext() || undefined;
  11201. formats = new Set();
  11202. for (const prefix of BROWSER_PREFIXES) {
  11203. for (const extension in WEBGL_EXTENSIONS) {
  11204. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  11205. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  11206. formats.add(gpuTextureFormat);
  11207. }
  11208. }
  11209. }
  11210. }
  11211. return formats;
  11212. }
  11213. function getWebGLContext() {
  11214. try {
  11215. const canvas = document.createElement('canvas');
  11216. return canvas.getContext('webgl');
  11217. } catch (error) {
  11218. return null;
  11219. }
  11220. }
  11221. var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f||(f={}));
  11222. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  11223. function isKTX(data) {
  11224. const id = new Uint8Array(data);
  11225. const notKTX = id.byteLength < KTX2_ID.length || id[0] !== KTX2_ID[0] || id[1] !== KTX2_ID[1] || id[2] !== KTX2_ID[2] || id[3] !== KTX2_ID[3] || id[4] !== KTX2_ID[4] || id[5] !== KTX2_ID[5] || id[6] !== KTX2_ID[6] || id[7] !== KTX2_ID[7] || id[8] !== KTX2_ID[8] || id[9] !== KTX2_ID[9] || id[10] !== KTX2_ID[10] || id[11] !== KTX2_ID[11];
  11226. return !notKTX;
  11227. }
  11228. const OutputFormat = {
  11229. etc1: {
  11230. basisFormat: 0,
  11231. compressed: true,
  11232. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  11233. },
  11234. etc2: {
  11235. basisFormat: 1,
  11236. compressed: true
  11237. },
  11238. bc1: {
  11239. basisFormat: 2,
  11240. compressed: true,
  11241. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  11242. },
  11243. bc3: {
  11244. basisFormat: 3,
  11245. compressed: true,
  11246. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  11247. },
  11248. bc4: {
  11249. basisFormat: 4,
  11250. compressed: true
  11251. },
  11252. bc5: {
  11253. basisFormat: 5,
  11254. compressed: true
  11255. },
  11256. 'bc7-m6-opaque-only': {
  11257. basisFormat: 6,
  11258. compressed: true
  11259. },
  11260. 'bc7-m5': {
  11261. basisFormat: 7,
  11262. compressed: true
  11263. },
  11264. 'pvrtc1-4-rgb': {
  11265. basisFormat: 8,
  11266. compressed: true,
  11267. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  11268. },
  11269. 'pvrtc1-4-rgba': {
  11270. basisFormat: 9,
  11271. compressed: true,
  11272. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  11273. },
  11274. 'astc-4x4': {
  11275. basisFormat: 10,
  11276. compressed: true,
  11277. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  11278. },
  11279. 'atc-rgb': {
  11280. basisFormat: 11,
  11281. compressed: true
  11282. },
  11283. 'atc-rgba-interpolated-alpha': {
  11284. basisFormat: 12,
  11285. compressed: true
  11286. },
  11287. rgba32: {
  11288. basisFormat: 13,
  11289. compressed: false
  11290. },
  11291. rgb565: {
  11292. basisFormat: 14,
  11293. compressed: false
  11294. },
  11295. bgr565: {
  11296. basisFormat: 15,
  11297. compressed: false
  11298. },
  11299. rgba4444: {
  11300. basisFormat: 16,
  11301. compressed: false
  11302. }
  11303. };
  11304. async function parseBasis(data, options) {
  11305. if (options.basis.containerFormat === 'auto') {
  11306. if (isKTX(data)) {
  11307. const fileConstructors = await loadBasisEncoderModule(options);
  11308. return parseKTX2File(fileConstructors.KTX2File, data, options);
  11309. }
  11310. const {
  11311. BasisFile
  11312. } = await loadBasisTrascoderModule(options);
  11313. return parseBasisFile(BasisFile, data, options);
  11314. }
  11315. switch (options.basis.module) {
  11316. case 'encoder':
  11317. const fileConstructors = await loadBasisEncoderModule(options);
  11318. switch (options.basis.containerFormat) {
  11319. case 'ktx2':
  11320. return parseKTX2File(fileConstructors.KTX2File, data, options);
  11321. case 'basis':
  11322. default:
  11323. return parseBasisFile(fileConstructors.BasisFile, data, options);
  11324. }
  11325. case 'transcoder':
  11326. default:
  11327. const {
  11328. BasisFile
  11329. } = await loadBasisTrascoderModule(options);
  11330. return parseBasisFile(BasisFile, data, options);
  11331. }
  11332. }
  11333. function parseBasisFile(BasisFile, data, options) {
  11334. const basisFile = new BasisFile(new Uint8Array(data));
  11335. try {
  11336. if (!basisFile.startTranscoding()) {
  11337. throw new Error('Failed to start basis transcoding');
  11338. }
  11339. const imageCount = basisFile.getNumImages();
  11340. const images = [];
  11341. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  11342. const levelsCount = basisFile.getNumLevels(imageIndex);
  11343. const levels = [];
  11344. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11345. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  11346. }
  11347. images.push(levels);
  11348. }
  11349. return images;
  11350. } finally {
  11351. basisFile.close();
  11352. basisFile.delete();
  11353. }
  11354. }
  11355. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  11356. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  11357. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  11358. const hasAlpha = basisFile.getHasAlpha();
  11359. const {
  11360. compressed,
  11361. format,
  11362. basisFormat
  11363. } = getBasisOptions(options, hasAlpha);
  11364. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  11365. const decodedData = new Uint8Array(decodedSize);
  11366. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  11367. throw new Error('failed to start Basis transcoding');
  11368. }
  11369. return {
  11370. width,
  11371. height,
  11372. data: decodedData,
  11373. compressed,
  11374. format,
  11375. hasAlpha
  11376. };
  11377. }
  11378. function parseKTX2File(KTX2File, data, options) {
  11379. const ktx2File = new KTX2File(new Uint8Array(data));
  11380. try {
  11381. if (!ktx2File.startTranscoding()) {
  11382. throw new Error('failed to start KTX2 transcoding');
  11383. }
  11384. const levelsCount = ktx2File.getLevels();
  11385. const levels = [];
  11386. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11387. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  11388. break;
  11389. }
  11390. return [levels];
  11391. } finally {
  11392. ktx2File.close();
  11393. ktx2File.delete();
  11394. }
  11395. }
  11396. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  11397. const {
  11398. alphaFlag,
  11399. height,
  11400. width
  11401. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  11402. const {
  11403. compressed,
  11404. format,
  11405. basisFormat
  11406. } = getBasisOptions(options, alphaFlag);
  11407. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  11408. const decodedData = new Uint8Array(decodedSize);
  11409. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  11410. throw new Error('Failed to transcode KTX2 image');
  11411. }
  11412. return {
  11413. width,
  11414. height,
  11415. data: decodedData,
  11416. compressed,
  11417. hasAlpha: alphaFlag,
  11418. format
  11419. };
  11420. }
  11421. function getBasisOptions(options, hasAlpha) {
  11422. let format = options && options.basis && options.basis.format;
  11423. if (format === 'auto') {
  11424. format = selectSupportedBasisFormat();
  11425. }
  11426. if (typeof format === 'object') {
  11427. format = hasAlpha ? format.alpha : format.noAlpha;
  11428. }
  11429. format = format.toLowerCase();
  11430. return OutputFormat[format];
  11431. }
  11432. function selectSupportedBasisFormat() {
  11433. const supportedFormats = getSupportedGPUTextureFormats();
  11434. if (supportedFormats.has('astc')) {
  11435. return 'astc-4x4';
  11436. } else if (supportedFormats.has('dxt')) {
  11437. return {
  11438. alpha: 'bc3',
  11439. noAlpha: 'bc1'
  11440. };
  11441. } else if (supportedFormats.has('pvrtc')) {
  11442. return {
  11443. alpha: 'pvrtc1-4-rgba',
  11444. noAlpha: 'pvrtc1-4-rgb'
  11445. };
  11446. } else if (supportedFormats.has('etc1')) {
  11447. return 'etc1';
  11448. } else if (supportedFormats.has('etc2')) {
  11449. return 'etc2';
  11450. }
  11451. return 'rgb565';
  11452. }
  11453. const BasisWorkerLoader = {
  11454. name: 'Basis',
  11455. id: 'basis',
  11456. module: 'textures',
  11457. version: VERSION$2,
  11458. worker: true,
  11459. extensions: ['basis', 'ktx2'],
  11460. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11461. tests: ['sB'],
  11462. binary: true,
  11463. options: {
  11464. basis: {
  11465. format: 'auto',
  11466. libraryPath: 'libs/',
  11467. containerFormat: 'auto',
  11468. module: 'transcoder'
  11469. }
  11470. }
  11471. };
  11472. const BasisLoader = { ...BasisWorkerLoader,
  11473. parse: parseBasis
  11474. };
  11475. const VERSION = "3.2.12" ;
  11476. const {
  11477. _parseImageNode
  11478. } = globalThis;
  11479. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11480. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11481. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11482. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11483. function isImageTypeSupported(type) {
  11484. switch (type) {
  11485. case 'auto':
  11486. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11487. case 'imagebitmap':
  11488. return IMAGE_BITMAP_SUPPORTED;
  11489. case 'image':
  11490. return IMAGE_SUPPORTED;
  11491. case 'data':
  11492. return DATA_SUPPORTED;
  11493. default:
  11494. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11495. }
  11496. }
  11497. function getDefaultImageType() {
  11498. if (IMAGE_BITMAP_SUPPORTED) {
  11499. return 'imagebitmap';
  11500. }
  11501. if (IMAGE_SUPPORTED) {
  11502. return 'image';
  11503. }
  11504. if (DATA_SUPPORTED) {
  11505. return 'data';
  11506. }
  11507. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11508. }
  11509. function getImageType(image) {
  11510. const format = getImageTypeOrNull(image);
  11511. if (!format) {
  11512. throw new Error('Not an image');
  11513. }
  11514. return format;
  11515. }
  11516. function getImageData(image) {
  11517. switch (getImageType(image)) {
  11518. case 'data':
  11519. return image;
  11520. case 'image':
  11521. case 'imagebitmap':
  11522. const canvas = document.createElement('canvas');
  11523. const context = canvas.getContext('2d');
  11524. if (!context) {
  11525. throw new Error('getImageData');
  11526. }
  11527. canvas.width = image.width;
  11528. canvas.height = image.height;
  11529. context.drawImage(image, 0, 0);
  11530. return context.getImageData(0, 0, image.width, image.height);
  11531. default:
  11532. throw new Error('getImageData');
  11533. }
  11534. }
  11535. function getImageTypeOrNull(image) {
  11536. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11537. return 'imagebitmap';
  11538. }
  11539. if (typeof Image !== 'undefined' && image instanceof Image) {
  11540. return 'image';
  11541. }
  11542. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11543. return 'data';
  11544. }
  11545. return null;
  11546. }
  11547. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11548. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11549. function isSVG(url) {
  11550. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11551. }
  11552. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11553. if (isSVG(url)) {
  11554. const textDecoder = new TextDecoder();
  11555. let xmlText = textDecoder.decode(arrayBuffer);
  11556. try {
  11557. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11558. xmlText = unescape(encodeURIComponent(xmlText));
  11559. }
  11560. } catch (error) {
  11561. throw new Error(error.message);
  11562. }
  11563. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11564. return src;
  11565. }
  11566. return getBlob(arrayBuffer, url);
  11567. }
  11568. function getBlob(arrayBuffer, url) {
  11569. if (isSVG(url)) {
  11570. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11571. }
  11572. return new Blob([new Uint8Array(arrayBuffer)]);
  11573. }
  11574. async function parseToImage(arrayBuffer, options, url) {
  11575. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11576. const URL = self.URL || self.webkitURL;
  11577. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11578. try {
  11579. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11580. } finally {
  11581. if (objectUrl) {
  11582. URL.revokeObjectURL(objectUrl);
  11583. }
  11584. }
  11585. }
  11586. async function loadToImage(url, options) {
  11587. const image = new Image();
  11588. image.src = url;
  11589. if (options.image && options.image.decode && image.decode) {
  11590. await image.decode();
  11591. return image;
  11592. }
  11593. return await new Promise((resolve, reject) => {
  11594. try {
  11595. image.onload = () => resolve(image);
  11596. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11597. } catch (error) {
  11598. reject(error);
  11599. }
  11600. });
  11601. }
  11602. const EMPTY_OBJECT = {};
  11603. let imagebitmapOptionsSupported = true;
  11604. async function parseToImageBitmap(arrayBuffer, options, url) {
  11605. let blob;
  11606. if (isSVG(url)) {
  11607. const image = await parseToImage(arrayBuffer, options, url);
  11608. blob = image;
  11609. } else {
  11610. blob = getBlob(arrayBuffer, url);
  11611. }
  11612. const imagebitmapOptions = options && options.imagebitmap;
  11613. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11614. }
  11615. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11616. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11617. imagebitmapOptions = null;
  11618. }
  11619. if (imagebitmapOptions) {
  11620. try {
  11621. return await createImageBitmap(blob, imagebitmapOptions);
  11622. } catch (error) {
  11623. console.warn(error);
  11624. imagebitmapOptionsSupported = false;
  11625. }
  11626. }
  11627. return await createImageBitmap(blob);
  11628. }
  11629. function isEmptyObject(object) {
  11630. for (const key in object || EMPTY_OBJECT) {
  11631. return false;
  11632. }
  11633. return true;
  11634. }
  11635. const BIG_ENDIAN = false;
  11636. const LITTLE_ENDIAN = true;
  11637. function getBinaryImageMetadata(binaryData) {
  11638. const dataView = toDataView(binaryData);
  11639. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11640. }
  11641. function getPngMetadata(binaryData) {
  11642. const dataView = toDataView(binaryData);
  11643. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11644. if (!isPng) {
  11645. return null;
  11646. }
  11647. return {
  11648. mimeType: 'image/png',
  11649. width: dataView.getUint32(16, BIG_ENDIAN),
  11650. height: dataView.getUint32(20, BIG_ENDIAN)
  11651. };
  11652. }
  11653. function getGifMetadata(binaryData) {
  11654. const dataView = toDataView(binaryData);
  11655. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11656. if (!isGif) {
  11657. return null;
  11658. }
  11659. return {
  11660. mimeType: 'image/gif',
  11661. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11662. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11663. };
  11664. }
  11665. function getBmpMetadata(binaryData) {
  11666. const dataView = toDataView(binaryData);
  11667. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11668. if (!isBmp) {
  11669. return null;
  11670. }
  11671. return {
  11672. mimeType: 'image/bmp',
  11673. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11674. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11675. };
  11676. }
  11677. function getJpegMetadata(binaryData) {
  11678. const dataView = toDataView(binaryData);
  11679. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11680. if (!isJpeg) {
  11681. return null;
  11682. }
  11683. const {
  11684. tableMarkers,
  11685. sofMarkers
  11686. } = getJpegMarkers();
  11687. let i = 2;
  11688. while (i + 9 < dataView.byteLength) {
  11689. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11690. if (sofMarkers.has(marker)) {
  11691. return {
  11692. mimeType: 'image/jpeg',
  11693. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11694. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11695. };
  11696. }
  11697. if (!tableMarkers.has(marker)) {
  11698. return null;
  11699. }
  11700. i += 2;
  11701. i += dataView.getUint16(i, BIG_ENDIAN);
  11702. }
  11703. return null;
  11704. }
  11705. function getJpegMarkers() {
  11706. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11707. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11708. tableMarkers.add(i);
  11709. }
  11710. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11711. return {
  11712. tableMarkers,
  11713. sofMarkers
  11714. };
  11715. }
  11716. function toDataView(data) {
  11717. if (data instanceof DataView) {
  11718. return data;
  11719. }
  11720. if (ArrayBuffer.isView(data)) {
  11721. return new DataView(data.buffer);
  11722. }
  11723. if (data instanceof ArrayBuffer) {
  11724. return new DataView(data);
  11725. }
  11726. throw new Error('toDataView');
  11727. }
  11728. async function parseToNodeImage(arrayBuffer, options) {
  11729. const {
  11730. mimeType
  11731. } = getBinaryImageMetadata(arrayBuffer) || {};
  11732. const _parseImageNode = globalThis._parseImageNode;
  11733. assert$7(_parseImageNode);
  11734. return await _parseImageNode(arrayBuffer, mimeType);
  11735. }
  11736. async function parseImage(arrayBuffer, options, context) {
  11737. options = options || {};
  11738. const imageOptions = options.image || {};
  11739. const imageType = imageOptions.type || 'auto';
  11740. const {
  11741. url
  11742. } = context || {};
  11743. const loadType = getLoadableImageType(imageType);
  11744. let image;
  11745. switch (loadType) {
  11746. case 'imagebitmap':
  11747. image = await parseToImageBitmap(arrayBuffer, options, url);
  11748. break;
  11749. case 'image':
  11750. image = await parseToImage(arrayBuffer, options, url);
  11751. break;
  11752. case 'data':
  11753. image = await parseToNodeImage(arrayBuffer);
  11754. break;
  11755. default:
  11756. assert$7(false);
  11757. }
  11758. if (imageType === 'data') {
  11759. image = getImageData(image);
  11760. }
  11761. return image;
  11762. }
  11763. function getLoadableImageType(type) {
  11764. switch (type) {
  11765. case 'auto':
  11766. case 'data':
  11767. return getDefaultImageType();
  11768. default:
  11769. isImageTypeSupported(type);
  11770. return type;
  11771. }
  11772. }
  11773. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11774. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11775. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11776. image: {
  11777. type: 'auto',
  11778. decode: true
  11779. }
  11780. };
  11781. const ImageLoader = {
  11782. id: 'image',
  11783. module: 'images',
  11784. name: 'Images',
  11785. version: VERSION,
  11786. mimeTypes: MIME_TYPES,
  11787. extensions: EXTENSIONS$1,
  11788. parse: parseImage,
  11789. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11790. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11791. };
  11792. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11793. const mimeTypeSupported = {};
  11794. function _isImageFormatSupported(mimeType) {
  11795. if (mimeTypeSupported[mimeType] === undefined) {
  11796. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11797. }
  11798. return mimeTypeSupported[mimeType];
  11799. }
  11800. function checkFormatSupport(mimeType) {
  11801. switch (mimeType) {
  11802. case 'image/webp':
  11803. return checkWebPSupport();
  11804. case 'image/svg':
  11805. return isBrowser$2;
  11806. default:
  11807. if (!isBrowser$2) {
  11808. const {
  11809. _parseImageNode
  11810. } = globalThis;
  11811. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11812. }
  11813. return true;
  11814. }
  11815. }
  11816. function checkWebPSupport() {
  11817. if (!isBrowser$2) {
  11818. return false;
  11819. }
  11820. try {
  11821. const element = document.createElement('canvas');
  11822. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11823. } catch {
  11824. return false;
  11825. }
  11826. }
  11827. function assert$1(condition, message) {
  11828. if (!condition) {
  11829. throw new Error(message || 'assert failed: gltf');
  11830. }
  11831. }
  11832. function resolveUrl(url, options) {
  11833. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11834. if (absolute) {
  11835. return url;
  11836. }
  11837. const baseUrl = options.baseUri || options.uri;
  11838. if (!baseUrl) {
  11839. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11840. }
  11841. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11842. }
  11843. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11844. const bufferView = json.bufferViews[bufferViewIndex];
  11845. assert$1(bufferView);
  11846. const bufferIndex = bufferView.buffer;
  11847. const binChunk = buffers[bufferIndex];
  11848. assert$1(binChunk);
  11849. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11850. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11851. }
  11852. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11853. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11854. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11855. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11856. SCALAR: 1,
  11857. VEC2: 2,
  11858. VEC3: 3,
  11859. VEC4: 4,
  11860. MAT2: 4,
  11861. MAT3: 9,
  11862. MAT4: 16
  11863. };
  11864. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11865. 5120: 1,
  11866. 5121: 1,
  11867. 5122: 2,
  11868. 5123: 2,
  11869. 5125: 4,
  11870. 5126: 4
  11871. };
  11872. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11873. 5120: Int8Array,
  11874. 5121: Uint8Array,
  11875. 5122: Int16Array,
  11876. 5123: Uint16Array,
  11877. 5125: Uint32Array,
  11878. 5126: Float32Array
  11879. };
  11880. function getAccessorTypeFromSize(size) {
  11881. const type = TYPES[size - 1];
  11882. return type || TYPES[0];
  11883. }
  11884. function getComponentTypeFromArray(typedArray) {
  11885. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11886. if (!componentType) {
  11887. throw new Error('Illegal typed array');
  11888. }
  11889. return componentType;
  11890. }
  11891. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11892. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11893. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11894. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11895. const length = accessor.count * components;
  11896. const byteLength = accessor.count * components * bytesPerComponent;
  11897. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11898. return {
  11899. ArrayType,
  11900. length,
  11901. byteLength
  11902. };
  11903. }
  11904. const DEFAULT_GLTF_JSON = {
  11905. asset: {
  11906. version: '2.0',
  11907. generator: 'loaders.gl'
  11908. },
  11909. buffers: []
  11910. };
  11911. class GLTFScenegraph {
  11912. constructor(gltf) {
  11913. _defineProperty(this, "gltf", void 0);
  11914. _defineProperty(this, "sourceBuffers", void 0);
  11915. _defineProperty(this, "byteLength", void 0);
  11916. this.gltf = gltf || {
  11917. json: { ...DEFAULT_GLTF_JSON
  11918. },
  11919. buffers: []
  11920. };
  11921. this.sourceBuffers = [];
  11922. this.byteLength = 0;
  11923. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11924. this.byteLength = this.gltf.buffers[0].byteLength;
  11925. this.sourceBuffers = [this.gltf.buffers[0]];
  11926. }
  11927. }
  11928. get json() {
  11929. return this.gltf.json;
  11930. }
  11931. getApplicationData(key) {
  11932. const data = this.json[key];
  11933. return data;
  11934. }
  11935. getExtraData(key) {
  11936. const extras = this.json.extras || {};
  11937. return extras[key];
  11938. }
  11939. getExtension(extensionName) {
  11940. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11941. const extensions = this.json.extensions || {};
  11942. return isExtension ? extensions[extensionName] || true : null;
  11943. }
  11944. getRequiredExtension(extensionName) {
  11945. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11946. return isRequired ? this.getExtension(extensionName) : null;
  11947. }
  11948. getRequiredExtensions() {
  11949. return this.json.extensionsRequired || [];
  11950. }
  11951. getUsedExtensions() {
  11952. return this.json.extensionsUsed || [];
  11953. }
  11954. getObjectExtension(object, extensionName) {
  11955. const extensions = object.extensions || {};
  11956. return extensions[extensionName];
  11957. }
  11958. getScene(index) {
  11959. return this.getObject('scenes', index);
  11960. }
  11961. getNode(index) {
  11962. return this.getObject('nodes', index);
  11963. }
  11964. getSkin(index) {
  11965. return this.getObject('skins', index);
  11966. }
  11967. getMesh(index) {
  11968. return this.getObject('meshes', index);
  11969. }
  11970. getMaterial(index) {
  11971. return this.getObject('materials', index);
  11972. }
  11973. getAccessor(index) {
  11974. return this.getObject('accessors', index);
  11975. }
  11976. getTexture(index) {
  11977. return this.getObject('textures', index);
  11978. }
  11979. getSampler(index) {
  11980. return this.getObject('samplers', index);
  11981. }
  11982. getImage(index) {
  11983. return this.getObject('images', index);
  11984. }
  11985. getBufferView(index) {
  11986. return this.getObject('bufferViews', index);
  11987. }
  11988. getBuffer(index) {
  11989. return this.getObject('buffers', index);
  11990. }
  11991. getObject(array, index) {
  11992. if (typeof index === 'object') {
  11993. return index;
  11994. }
  11995. const object = this.json[array] && this.json[array][index];
  11996. if (!object) {
  11997. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11998. }
  11999. return object;
  12000. }
  12001. getTypedArrayForBufferView(bufferView) {
  12002. bufferView = this.getBufferView(bufferView);
  12003. const bufferIndex = bufferView.buffer;
  12004. const binChunk = this.gltf.buffers[bufferIndex];
  12005. assert$1(binChunk);
  12006. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  12007. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  12008. }
  12009. getTypedArrayForAccessor(accessor) {
  12010. accessor = this.getAccessor(accessor);
  12011. const bufferView = this.getBufferView(accessor.bufferView);
  12012. const buffer = this.getBuffer(bufferView.buffer);
  12013. const arrayBuffer = buffer.data;
  12014. const {
  12015. ArrayType,
  12016. length
  12017. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  12018. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  12019. return new ArrayType(arrayBuffer, byteOffset, length);
  12020. }
  12021. getTypedArrayForImageData(image) {
  12022. image = this.getAccessor(image);
  12023. const bufferView = this.getBufferView(image.bufferView);
  12024. const buffer = this.getBuffer(bufferView.buffer);
  12025. const arrayBuffer = buffer.data;
  12026. const byteOffset = bufferView.byteOffset || 0;
  12027. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  12028. }
  12029. addApplicationData(key, data) {
  12030. this.json[key] = data;
  12031. return this;
  12032. }
  12033. addExtraData(key, data) {
  12034. this.json.extras = this.json.extras || {};
  12035. this.json.extras[key] = data;
  12036. return this;
  12037. }
  12038. addObjectExtension(object, extensionName, data) {
  12039. object.extensions = object.extensions || {};
  12040. object.extensions[extensionName] = data;
  12041. this.registerUsedExtension(extensionName);
  12042. return this;
  12043. }
  12044. setObjectExtension(object, extensionName, data) {
  12045. const extensions = object.extensions || {};
  12046. extensions[extensionName] = data;
  12047. }
  12048. removeObjectExtension(object, extensionName) {
  12049. const extensions = object.extensions || {};
  12050. const extension = extensions[extensionName];
  12051. delete extensions[extensionName];
  12052. return extension;
  12053. }
  12054. addExtension(extensionName, extensionData = {}) {
  12055. assert$1(extensionData);
  12056. this.json.extensions = this.json.extensions || {};
  12057. this.json.extensions[extensionName] = extensionData;
  12058. this.registerUsedExtension(extensionName);
  12059. return extensionData;
  12060. }
  12061. addRequiredExtension(extensionName, extensionData = {}) {
  12062. assert$1(extensionData);
  12063. this.addExtension(extensionName, extensionData);
  12064. this.registerRequiredExtension(extensionName);
  12065. return extensionData;
  12066. }
  12067. registerUsedExtension(extensionName) {
  12068. this.json.extensionsUsed = this.json.extensionsUsed || [];
  12069. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  12070. this.json.extensionsUsed.push(extensionName);
  12071. }
  12072. }
  12073. registerRequiredExtension(extensionName) {
  12074. this.registerUsedExtension(extensionName);
  12075. this.json.extensionsRequired = this.json.extensionsRequired || [];
  12076. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  12077. this.json.extensionsRequired.push(extensionName);
  12078. }
  12079. }
  12080. removeExtension(extensionName) {
  12081. if (this.json.extensionsRequired) {
  12082. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  12083. }
  12084. if (this.json.extensionsUsed) {
  12085. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  12086. }
  12087. if (this.json.extensions) {
  12088. delete this.json.extensions[extensionName];
  12089. }
  12090. }
  12091. setDefaultScene(sceneIndex) {
  12092. this.json.scene = sceneIndex;
  12093. }
  12094. addScene(scene) {
  12095. const {
  12096. nodeIndices
  12097. } = scene;
  12098. this.json.scenes = this.json.scenes || [];
  12099. this.json.scenes.push({
  12100. nodes: nodeIndices
  12101. });
  12102. return this.json.scenes.length - 1;
  12103. }
  12104. addNode(node) {
  12105. const {
  12106. meshIndex,
  12107. matrix
  12108. } = node;
  12109. this.json.nodes = this.json.nodes || [];
  12110. const nodeData = {
  12111. mesh: meshIndex
  12112. };
  12113. if (matrix) {
  12114. nodeData.matrix = matrix;
  12115. }
  12116. this.json.nodes.push(nodeData);
  12117. return this.json.nodes.length - 1;
  12118. }
  12119. addMesh(mesh) {
  12120. const {
  12121. attributes,
  12122. indices,
  12123. material,
  12124. mode = 4
  12125. } = mesh;
  12126. const accessors = this._addAttributes(attributes);
  12127. const glTFMesh = {
  12128. primitives: [{
  12129. attributes: accessors,
  12130. mode
  12131. }]
  12132. };
  12133. if (indices) {
  12134. const indicesAccessor = this._addIndices(indices);
  12135. glTFMesh.primitives[0].indices = indicesAccessor;
  12136. }
  12137. if (Number.isFinite(material)) {
  12138. glTFMesh.primitives[0].material = material;
  12139. }
  12140. this.json.meshes = this.json.meshes || [];
  12141. this.json.meshes.push(glTFMesh);
  12142. return this.json.meshes.length - 1;
  12143. }
  12144. addPointCloud(attributes) {
  12145. const accessorIndices = this._addAttributes(attributes);
  12146. const glTFMesh = {
  12147. primitives: [{
  12148. attributes: accessorIndices,
  12149. mode: 0
  12150. }]
  12151. };
  12152. this.json.meshes = this.json.meshes || [];
  12153. this.json.meshes.push(glTFMesh);
  12154. return this.json.meshes.length - 1;
  12155. }
  12156. addImage(imageData, mimeTypeOpt) {
  12157. const metadata = getBinaryImageMetadata(imageData);
  12158. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  12159. const bufferViewIndex = this.addBufferView(imageData);
  12160. const glTFImage = {
  12161. bufferView: bufferViewIndex,
  12162. mimeType
  12163. };
  12164. this.json.images = this.json.images || [];
  12165. this.json.images.push(glTFImage);
  12166. return this.json.images.length - 1;
  12167. }
  12168. addBufferView(buffer) {
  12169. const byteLength = buffer.byteLength;
  12170. assert$1(Number.isFinite(byteLength));
  12171. this.sourceBuffers = this.sourceBuffers || [];
  12172. this.sourceBuffers.push(buffer);
  12173. const glTFBufferView = {
  12174. buffer: 0,
  12175. byteOffset: this.byteLength,
  12176. byteLength
  12177. };
  12178. this.byteLength += padToNBytes(byteLength, 4);
  12179. this.json.bufferViews = this.json.bufferViews || [];
  12180. this.json.bufferViews.push(glTFBufferView);
  12181. return this.json.bufferViews.length - 1;
  12182. }
  12183. addAccessor(bufferViewIndex, accessor) {
  12184. const glTFAccessor = {
  12185. bufferView: bufferViewIndex,
  12186. type: getAccessorTypeFromSize(accessor.size),
  12187. componentType: accessor.componentType,
  12188. count: accessor.count,
  12189. max: accessor.max,
  12190. min: accessor.min
  12191. };
  12192. this.json.accessors = this.json.accessors || [];
  12193. this.json.accessors.push(glTFAccessor);
  12194. return this.json.accessors.length - 1;
  12195. }
  12196. addBinaryBuffer(sourceBuffer, accessor = {
  12197. size: 3
  12198. }) {
  12199. const bufferViewIndex = this.addBufferView(sourceBuffer);
  12200. let minMax = {
  12201. min: accessor.min,
  12202. max: accessor.max
  12203. };
  12204. if (!minMax.min || !minMax.max) {
  12205. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  12206. }
  12207. const accessorDefaults = {
  12208. size: accessor.size,
  12209. componentType: getComponentTypeFromArray(sourceBuffer),
  12210. count: Math.round(sourceBuffer.length / accessor.size),
  12211. min: minMax.min,
  12212. max: minMax.max
  12213. };
  12214. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  12215. }
  12216. addTexture(texture) {
  12217. const {
  12218. imageIndex
  12219. } = texture;
  12220. const glTFTexture = {
  12221. source: imageIndex
  12222. };
  12223. this.json.textures = this.json.textures || [];
  12224. this.json.textures.push(glTFTexture);
  12225. return this.json.textures.length - 1;
  12226. }
  12227. addMaterial(pbrMaterialInfo) {
  12228. this.json.materials = this.json.materials || [];
  12229. this.json.materials.push(pbrMaterialInfo);
  12230. return this.json.materials.length - 1;
  12231. }
  12232. createBinaryChunk() {
  12233. var _this$json, _this$json$buffers;
  12234. this.gltf.buffers = [];
  12235. const totalByteLength = this.byteLength;
  12236. const arrayBuffer = new ArrayBuffer(totalByteLength);
  12237. const targetArray = new Uint8Array(arrayBuffer);
  12238. let dstByteOffset = 0;
  12239. for (const sourceBuffer of this.sourceBuffers || []) {
  12240. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  12241. }
  12242. if ((_this$json = this.json) !== null && _this$json !== void 0 && (_this$json$buffers = _this$json.buffers) !== null && _this$json$buffers !== void 0 && _this$json$buffers[0]) {
  12243. this.json.buffers[0].byteLength = totalByteLength;
  12244. } else {
  12245. this.json.buffers = [{
  12246. byteLength: totalByteLength
  12247. }];
  12248. }
  12249. this.gltf.binary = arrayBuffer;
  12250. this.sourceBuffers = [arrayBuffer];
  12251. }
  12252. _removeStringFromArray(array, string) {
  12253. let found = true;
  12254. while (found) {
  12255. const index = array.indexOf(string);
  12256. if (index > -1) {
  12257. array.splice(index, 1);
  12258. } else {
  12259. found = false;
  12260. }
  12261. }
  12262. }
  12263. _addAttributes(attributes = {}) {
  12264. const result = {};
  12265. for (const attributeKey in attributes) {
  12266. const attributeData = attributes[attributeKey];
  12267. const attrName = this._getGltfAttributeName(attributeKey);
  12268. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  12269. result[attrName] = accessor;
  12270. }
  12271. return result;
  12272. }
  12273. _addIndices(indices) {
  12274. return this.addBinaryBuffer(indices, {
  12275. size: 1
  12276. });
  12277. }
  12278. _getGltfAttributeName(attributeName) {
  12279. switch (attributeName.toLowerCase()) {
  12280. case 'position':
  12281. case 'positions':
  12282. case 'vertices':
  12283. return 'POSITION';
  12284. case 'normal':
  12285. case 'normals':
  12286. return 'NORMAL';
  12287. case 'color':
  12288. case 'colors':
  12289. return 'COLOR_0';
  12290. case 'texcoord':
  12291. case 'texcoords':
  12292. return 'TEXCOORD_0';
  12293. default:
  12294. return attributeName;
  12295. }
  12296. }
  12297. _getAccessorMinMax(buffer, size) {
  12298. const result = {
  12299. min: null,
  12300. max: null
  12301. };
  12302. if (buffer.length < size) {
  12303. return result;
  12304. }
  12305. result.min = [];
  12306. result.max = [];
  12307. const initValues = buffer.subarray(0, size);
  12308. for (const value of initValues) {
  12309. result.min.push(value);
  12310. result.max.push(value);
  12311. }
  12312. for (let index = size; index < buffer.length; index += size) {
  12313. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  12314. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  12315. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  12316. }
  12317. }
  12318. return result;
  12319. }
  12320. }
  12321. const wasm_base = 'B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB';
  12322. const wasm_simd = 'B9h9z9tFBBBF8dL9gBB9gLaaaaaFa9gEaaaB9gGaaB9gFaFaEQSBBFBFFGEGEGIILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBNn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBcI9z9iqlBMc/j9JSIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMkRIbaG97FaK978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAnDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAnDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBRnCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBHiCFD9tAiAPD9OD9hD9RHiDQBTFtGmEYIPLdKeOnH8ZAIAQJDBIBHpCFD9tApAPD9OD9hD9RHpAIASJDBIBHyCFD9tAyAPD9OD9hD9RHyDQBTFtGmEYIPLdKeOnH8cDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAnD9uHnDyBjGBAEAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnA8ZA8cDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNiV8ZcpMyS8cQ8df8eb8fHdApAyDQNiV8ZcpMyS8cQ8df8eb8fHiDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/xLGEaK978jUUUUBCAlHE8kUUUUBGXGXAGCI9HQBGXAFC98ZHI9FQBABRGCBRLEXAGAGDBBBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMBBAGCTJRGALCIJHLAI9JQBMMAIAF9PQFAEAFCEZHLCGWHGqCBCTAGl/8MBAEABAICGWJHIAG/8cBBGXAL9FQBAEAEDBIBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMIBMAIAEAG/8cBBSFMABAFC98ZHGT+HUUUBAGAF9PQBAEAFCEZHICEWHLJCBCAALl/8MBAEABAGCEWJHGAL/8cBBAEAIT+HUUUBAGAEAL/8cBBMAECAJ8kUUUUBM+yEGGaO97GXAF9FQBCBRGEXABCTJHEAEDBBBHICBDtHLCUU98D8cFCUU98D8cEHKD9OABDBBBHOAIDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAOAIDQBFGENVcMTtmYi8ZpyHICTD+sFD/6FHND/gFAICTD+rFCTD+sFD/6FHVD/gFD/kFD/lFHI9DB/+g6DYAVAIALD+2FHLAVCUUUU94DtHcD9OD9RD/kFHVAVD/mFAIAID/mFANALANAcD9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHLD/kFCTD+rFAVAND/mFALD/kFCggEDtD9OD9QHVAIAND/mFALD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHIDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAOAKD9OAVAIDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM94FEa8jUUUUBCAlHE8kUUUUBABAFC98ZHIT+JUUUBGXAIAF9PQBAEAFCEZHLCEWHFJCBCAAFl/8MBAEABAICEWJHBAF/8cBBAEALT+JUUUBABAEAF/8cBBMAECAJ8kUUUUBM/hEIGaF97FaL978jUUUUBCTlRGGXAF9FQBCBREEXAGABDBBBHIABCTJHLDBBBHKDQILKOSQfbPden8c8d8e8fHOCTD+sFHNCID+rFDMIBAB9DBBU8/DY9D/zI818/DYANCEDtD9QD/6FD/nFHNAIAKDQBFGENVcMTtmYi8ZpyHICTD+rFCTD+sFD/6FD/mFHKAKD/mFANAICTD+sFD/6FD/mFHVAVD/mFANAOCTD+rFCTD+sFD/6FD/mFHOAOD/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHND/mF9DBBX9LDYHID/kFCggEDtHcD9OAVAND/mFAID/kFCTD+rFD9QHVAOAND/mFAID/kFCTD+rFAKAND/mFAID/kFAcD9OD9QHNDQBFTtGEmYILPdKOenHID8dBAGDBIBDyB+t+J83EBABCNJAID8dFAGDBIBDyF+t+J83EBALAVANDQNVi8ZcMpySQ8c8dfb8e8fHND8dBAGDBIBDyG+t+J83EBABCiJAND8dFAGDBIBDyE+t+J83EBABCAJRBAECIJHEAF9JQBMMM/3FGEaF978jUUUUBCoBlREGXAGCGrAF9sHIC98ZHL9FQBCBRGABRFEXAFAFDBBBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBAFCTJRFAGCIJHGAL9JQBMMGXALAI9PQBAEAICEZHGCGWHFqCBCoBAFl/8MBAEABALCGWJHLAF/8cBBGXAG9FQBAEAEDBIBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMIBMALAEAF/8cBBMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB';
  12323. const detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]);
  12324. const wasmpack = new Uint8Array([32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167]);
  12325. const FILTERS = {
  12326. 0: '',
  12327. 1: 'meshopt_decodeFilterOct',
  12328. 2: 'meshopt_decodeFilterQuat',
  12329. 3: 'meshopt_decodeFilterExp',
  12330. NONE: '',
  12331. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  12332. QUATERNION: 'meshopt_decodeFilterQuat',
  12333. EXPONENTIAL: 'meshopt_decodeFilterExp'
  12334. };
  12335. const DECODERS = {
  12336. 0: 'meshopt_decodeVertexBuffer',
  12337. 1: 'meshopt_decodeIndexBuffer',
  12338. 2: 'meshopt_decodeIndexSequence',
  12339. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  12340. TRIANGLES: 'meshopt_decodeIndexBuffer',
  12341. INDICES: 'meshopt_decodeIndexSequence'
  12342. };
  12343. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  12344. const instance = await loadWasmInstance();
  12345. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  12346. }
  12347. let wasmPromise;
  12348. async function loadWasmInstance() {
  12349. if (!wasmPromise) {
  12350. wasmPromise = loadWasmModule();
  12351. }
  12352. return wasmPromise;
  12353. }
  12354. async function loadWasmModule() {
  12355. let wasm = wasm_base;
  12356. if (WebAssembly.validate(detector)) {
  12357. wasm = wasm_simd;
  12358. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  12359. }
  12360. const result = await WebAssembly.instantiate(unpack(wasm), {});
  12361. await result.instance.exports.__wasm_call_ctors();
  12362. return result.instance;
  12363. }
  12364. function unpack(data) {
  12365. const result = new Uint8Array(data.length);
  12366. for (let i = 0; i < data.length; ++i) {
  12367. const ch = data.charCodeAt(i);
  12368. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  12369. }
  12370. let write = 0;
  12371. for (let i = 0; i < data.length; ++i) {
  12372. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  12373. }
  12374. return result.buffer.slice(0, write);
  12375. }
  12376. function decode$5(instance, fun, target, count, size, source, filter) {
  12377. const sbrk = instance.exports.sbrk;
  12378. const count4 = count + 3 & ~3;
  12379. const tp = sbrk(count4 * size);
  12380. const sp = sbrk(source.length);
  12381. const heap = new Uint8Array(instance.exports.memory.buffer);
  12382. heap.set(source, sp);
  12383. const res = fun(tp, count, size, sp, source.length);
  12384. if (res === 0 && filter) {
  12385. filter(tp, count4, size);
  12386. }
  12387. target.set(heap.subarray(tp, tp + count * size));
  12388. sbrk(tp - sbrk(0));
  12389. if (res !== 0) {
  12390. throw new Error("Malformed buffer data: ".concat(res));
  12391. }
  12392. }
  12393. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  12394. const name$6 = EXT_MESHOPT_COMPRESSION;
  12395. async function decode$4(gltfData, options) {
  12396. var _options$gltf;
  12397. const scenegraph = new GLTFScenegraph(gltfData);
  12398. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12399. return;
  12400. }
  12401. const promises = [];
  12402. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  12403. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  12404. }
  12405. await Promise.all(promises);
  12406. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  12407. }
  12408. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  12409. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  12410. if (meshoptExtension) {
  12411. const {
  12412. byteOffset = 0,
  12413. byteLength = 0,
  12414. byteStride,
  12415. count,
  12416. mode,
  12417. filter = 'NONE',
  12418. buffer: bufferIndex
  12419. } = meshoptExtension;
  12420. const buffer = scenegraph.gltf.buffers[bufferIndex];
  12421. const source = new Uint8Array(buffer.arrayBuffer, buffer.byteOffset + byteOffset, byteLength);
  12422. const result = new Uint8Array(scenegraph.gltf.buffers[bufferView.buffer].arrayBuffer, bufferView.byteOffset, bufferView.byteLength);
  12423. await meshoptDecodeGltfBuffer(result, count, byteStride, source, mode, filter);
  12424. return result;
  12425. }
  12426. return null;
  12427. }
  12428. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12429. __proto__: null,
  12430. name: name$6,
  12431. decode: decode$4
  12432. });
  12433. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12434. const name$5 = EXT_TEXTURE_WEBP;
  12435. function preprocess$3(gltfData, options) {
  12436. const scenegraph = new GLTFScenegraph(gltfData);
  12437. if (!_isImageFormatSupported('image/webp')) {
  12438. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12439. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12440. }
  12441. return;
  12442. }
  12443. const {
  12444. json
  12445. } = scenegraph;
  12446. for (const texture of json.textures || []) {
  12447. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12448. if (extension) {
  12449. texture.source = extension.source;
  12450. }
  12451. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12452. }
  12453. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12454. }
  12455. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12456. __proto__: null,
  12457. name: name$5,
  12458. preprocess: preprocess$3
  12459. });
  12460. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12461. const name$4 = KHR_TEXTURE_BASISU;
  12462. function preprocess$2(gltfData, options) {
  12463. const scene = new GLTFScenegraph(gltfData);
  12464. const {
  12465. json
  12466. } = scene;
  12467. for (const texture of json.textures || []) {
  12468. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12469. if (extension) {
  12470. texture.source = extension.source;
  12471. }
  12472. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12473. }
  12474. scene.removeExtension(KHR_TEXTURE_BASISU);
  12475. }
  12476. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12477. __proto__: null,
  12478. name: name$4,
  12479. preprocess: preprocess$2
  12480. });
  12481. function getGLTFAccessors(attributes) {
  12482. const accessors = {};
  12483. for (const name in attributes) {
  12484. const attribute = attributes[name];
  12485. if (name !== 'indices') {
  12486. const glTFAccessor = getGLTFAccessor(attribute);
  12487. accessors[name] = glTFAccessor;
  12488. }
  12489. }
  12490. return accessors;
  12491. }
  12492. function getGLTFAccessor(attribute) {
  12493. const {
  12494. buffer,
  12495. size,
  12496. count
  12497. } = getAccessorData(attribute);
  12498. const glTFAccessor = {
  12499. value: buffer,
  12500. size,
  12501. byteOffset: 0,
  12502. count,
  12503. type: getAccessorTypeFromSize(size),
  12504. componentType: getComponentTypeFromArray(buffer)
  12505. };
  12506. return glTFAccessor;
  12507. }
  12508. function getAccessorData(attribute) {
  12509. let buffer = attribute;
  12510. let size = 1;
  12511. let count = 0;
  12512. if (attribute && attribute.value) {
  12513. buffer = attribute.value;
  12514. size = attribute.size || 1;
  12515. }
  12516. if (buffer) {
  12517. if (!ArrayBuffer.isView(buffer)) {
  12518. buffer = toTypedArray(buffer, Float32Array);
  12519. }
  12520. count = buffer.length / size;
  12521. }
  12522. return {
  12523. buffer,
  12524. size,
  12525. count
  12526. };
  12527. }
  12528. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12529. if (!array) {
  12530. return null;
  12531. }
  12532. if (Array.isArray(array)) {
  12533. return new ArrayType(array);
  12534. }
  12535. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12536. return new ArrayType(array);
  12537. }
  12538. return array;
  12539. }
  12540. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12541. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12542. function preprocess$1(gltfData, options, context) {
  12543. const scenegraph = new GLTFScenegraph(gltfData);
  12544. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12545. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12546. }
  12547. }
  12548. async function decode$3(gltfData, options, context) {
  12549. var _options$gltf;
  12550. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12551. return;
  12552. }
  12553. const scenegraph = new GLTFScenegraph(gltfData);
  12554. const promises = [];
  12555. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12556. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12557. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12558. }
  12559. }
  12560. await Promise.all(promises);
  12561. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12562. }
  12563. function encode$3(gltfData, options = {}) {
  12564. const scenegraph = new GLTFScenegraph(gltfData);
  12565. for (const mesh of scenegraph.json.meshes || []) {
  12566. compressMesh(mesh);
  12567. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12568. }
  12569. }
  12570. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12571. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12572. if (!dracoExtension) {
  12573. return;
  12574. }
  12575. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12576. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12577. const {
  12578. parse
  12579. } = context;
  12580. const dracoOptions = { ...options
  12581. };
  12582. delete dracoOptions['3d-tiles'];
  12583. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12584. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12585. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12586. if (attributeName in primitive.attributes) {
  12587. const accessorIndex = primitive.attributes[attributeName];
  12588. const accessor = scenegraph.getAccessor(accessorIndex);
  12589. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12590. decodedAttribute.min = accessor.min;
  12591. decodedAttribute.max = accessor.max;
  12592. }
  12593. }
  12594. }
  12595. primitive.attributes = decodedAttributes;
  12596. if (decodedData.indices) {
  12597. primitive.indices = getGLTFAccessor(decodedData.indices);
  12598. }
  12599. checkPrimitive(primitive);
  12600. }
  12601. function compressMesh(attributes, indices, mode = 4, options, context) {
  12602. var _context$parseSync;
  12603. if (!options.DracoWriter) {
  12604. throw new Error('options.gltf.DracoWriter not provided');
  12605. }
  12606. const compressedData = options.DracoWriter.encodeSync({
  12607. attributes
  12608. });
  12609. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12610. attributes
  12611. });
  12612. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12613. const bufferViewIndex = options.addBufferView(compressedData);
  12614. const glTFMesh = {
  12615. primitives: [{
  12616. attributes: fauxAccessors,
  12617. mode,
  12618. extensions: {
  12619. [KHR_DRACO_MESH_COMPRESSION]: {
  12620. bufferView: bufferViewIndex,
  12621. attributes: fauxAccessors
  12622. }
  12623. }
  12624. }]
  12625. };
  12626. return glTFMesh;
  12627. }
  12628. function checkPrimitive(primitive) {
  12629. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12630. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12631. }
  12632. }
  12633. function* makeMeshPrimitiveIterator(scenegraph) {
  12634. for (const mesh of scenegraph.json.meshes || []) {
  12635. for (const primitive of mesh.primitives) {
  12636. yield primitive;
  12637. }
  12638. }
  12639. }
  12640. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12641. __proto__: null,
  12642. name: name$3,
  12643. preprocess: preprocess$1,
  12644. decode: decode$3,
  12645. encode: encode$3
  12646. });
  12647. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12648. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12649. async function decode$2(gltfData) {
  12650. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12651. const {
  12652. json
  12653. } = gltfScenegraph;
  12654. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12655. if (extension) {
  12656. gltfScenegraph.json.lights = extension.lights;
  12657. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12658. }
  12659. for (const node of json.nodes || []) {
  12660. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12661. if (nodeExtension) {
  12662. node.light = nodeExtension.light;
  12663. }
  12664. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12665. }
  12666. }
  12667. async function encode$2(gltfData) {
  12668. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12669. const {
  12670. json
  12671. } = gltfScenegraph;
  12672. if (json.lights) {
  12673. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12674. assert$1(!extension.lights);
  12675. extension.lights = json.lights;
  12676. delete json.lights;
  12677. }
  12678. if (gltfScenegraph.json.lights) {
  12679. for (const light of gltfScenegraph.json.lights) {
  12680. const node = light.node;
  12681. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12682. }
  12683. delete gltfScenegraph.json.lights;
  12684. }
  12685. }
  12686. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12687. __proto__: null,
  12688. name: name$2,
  12689. decode: decode$2,
  12690. encode: encode$2
  12691. });
  12692. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12693. const name$1 = KHR_MATERIALS_UNLIT;
  12694. async function decode$1(gltfData) {
  12695. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12696. const {
  12697. json
  12698. } = gltfScenegraph;
  12699. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12700. for (const material of json.materials || []) {
  12701. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12702. if (extension) {
  12703. material.unlit = true;
  12704. }
  12705. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12706. }
  12707. }
  12708. function encode$1(gltfData) {
  12709. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12710. const {
  12711. json
  12712. } = gltfScenegraph;
  12713. if (gltfScenegraph.materials) {
  12714. for (const material of json.materials || []) {
  12715. if (material.unlit) {
  12716. delete material.unlit;
  12717. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12718. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12719. }
  12720. }
  12721. }
  12722. }
  12723. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12724. __proto__: null,
  12725. name: name$1,
  12726. decode: decode$1,
  12727. encode: encode$1
  12728. });
  12729. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12730. const name = KHR_TECHNIQUES_WEBGL;
  12731. async function decode(gltfData) {
  12732. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12733. const {
  12734. json
  12735. } = gltfScenegraph;
  12736. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12737. if (extension) {
  12738. const techniques = resolveTechniques(extension, gltfScenegraph);
  12739. for (const material of json.materials || []) {
  12740. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12741. if (materialExtension) {
  12742. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12743. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12744. }
  12745. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12746. }
  12747. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12748. }
  12749. }
  12750. async function encode(gltfData, options) {}
  12751. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12752. const {
  12753. programs = [],
  12754. shaders = [],
  12755. techniques = []
  12756. } = techniquesExtension;
  12757. const textDecoder = new TextDecoder();
  12758. shaders.forEach(shader => {
  12759. if (Number.isFinite(shader.bufferView)) {
  12760. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12761. } else {
  12762. throw new Error('KHR_techniques_webgl: no shader code');
  12763. }
  12764. });
  12765. programs.forEach(program => {
  12766. program.fragmentShader = shaders[program.fragmentShader];
  12767. program.vertexShader = shaders[program.vertexShader];
  12768. });
  12769. techniques.forEach(technique => {
  12770. technique.program = programs[technique.program];
  12771. });
  12772. return techniques;
  12773. }
  12774. function resolveValues(technique, gltfScenegraph) {
  12775. const values = Object.assign({}, technique.values);
  12776. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12777. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12778. values[uniform] = technique.uniforms[uniform].value;
  12779. }
  12780. });
  12781. Object.keys(values).forEach(uniform => {
  12782. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12783. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12784. }
  12785. });
  12786. return values;
  12787. }
  12788. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12789. __proto__: null,
  12790. name: name,
  12791. decode: decode,
  12792. encode: encode
  12793. });
  12794. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12795. function preprocessExtensions(gltf, options = {}, context) {
  12796. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12797. for (const extension of extensions) {
  12798. var _extension$preprocess;
  12799. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12800. }
  12801. }
  12802. async function decodeExtensions(gltf, options = {}, context) {
  12803. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12804. for (const extension of extensions) {
  12805. var _extension$decode;
  12806. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12807. }
  12808. }
  12809. function useExtension(extensionName, options) {
  12810. var _options$gltf;
  12811. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12812. const exclude = extensionName in excludes && !excludes[extensionName];
  12813. return !exclude;
  12814. }
  12815. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12816. function preprocess(gltfData) {
  12817. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12818. const {
  12819. json
  12820. } = gltfScenegraph;
  12821. for (const image of json.images || []) {
  12822. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12823. if (extension) {
  12824. Object.assign(image, extension);
  12825. }
  12826. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12827. }
  12828. if (json.buffers && json.buffers[0]) {
  12829. delete json.buffers[0].uri;
  12830. }
  12831. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12832. }
  12833. const GLTF_ARRAYS = {
  12834. accessors: 'accessor',
  12835. animations: 'animation',
  12836. buffers: 'buffer',
  12837. bufferViews: 'bufferView',
  12838. images: 'image',
  12839. materials: 'material',
  12840. meshes: 'mesh',
  12841. nodes: 'node',
  12842. samplers: 'sampler',
  12843. scenes: 'scene',
  12844. skins: 'skin',
  12845. textures: 'texture'
  12846. };
  12847. const GLTF_KEYS = {
  12848. accessor: 'accessors',
  12849. animations: 'animation',
  12850. buffer: 'buffers',
  12851. bufferView: 'bufferViews',
  12852. image: 'images',
  12853. material: 'materials',
  12854. mesh: 'meshes',
  12855. node: 'nodes',
  12856. sampler: 'samplers',
  12857. scene: 'scenes',
  12858. skin: 'skins',
  12859. texture: 'textures'
  12860. };
  12861. class GLTFV1Normalizer {
  12862. constructor() {
  12863. _defineProperty(this, "idToIndexMap", {
  12864. animations: {},
  12865. accessors: {},
  12866. buffers: {},
  12867. bufferViews: {},
  12868. images: {},
  12869. materials: {},
  12870. meshes: {},
  12871. nodes: {},
  12872. samplers: {},
  12873. scenes: {},
  12874. skins: {},
  12875. textures: {}
  12876. });
  12877. _defineProperty(this, "json", void 0);
  12878. }
  12879. normalize(gltf, options) {
  12880. this.json = gltf.json;
  12881. const json = gltf.json;
  12882. switch (json.asset && json.asset.version) {
  12883. case '2.0':
  12884. return;
  12885. case undefined:
  12886. case '1.0':
  12887. break;
  12888. default:
  12889. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12890. return;
  12891. }
  12892. if (!options.normalize) {
  12893. throw new Error('glTF v1 is not supported.');
  12894. }
  12895. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12896. this._addAsset(json);
  12897. this._convertTopLevelObjectsToArrays(json);
  12898. preprocess(gltf);
  12899. this._convertObjectIdsToArrayIndices(json);
  12900. this._updateObjects(json);
  12901. this._updateMaterial(json);
  12902. }
  12903. _addAsset(json) {
  12904. json.asset = json.asset || {};
  12905. json.asset.version = '2.0';
  12906. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12907. }
  12908. _convertTopLevelObjectsToArrays(json) {
  12909. for (const arrayName in GLTF_ARRAYS) {
  12910. this._convertTopLevelObjectToArray(json, arrayName);
  12911. }
  12912. }
  12913. _convertTopLevelObjectToArray(json, mapName) {
  12914. const objectMap = json[mapName];
  12915. if (!objectMap || Array.isArray(objectMap)) {
  12916. return;
  12917. }
  12918. json[mapName] = [];
  12919. for (const id in objectMap) {
  12920. const object = objectMap[id];
  12921. object.id = object.id || id;
  12922. const index = json[mapName].length;
  12923. json[mapName].push(object);
  12924. this.idToIndexMap[mapName][id] = index;
  12925. }
  12926. }
  12927. _convertObjectIdsToArrayIndices(json) {
  12928. for (const arrayName in GLTF_ARRAYS) {
  12929. this._convertIdsToIndices(json, arrayName);
  12930. }
  12931. if ('scene' in json) {
  12932. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12933. }
  12934. for (const texture of json.textures) {
  12935. this._convertTextureIds(texture);
  12936. }
  12937. for (const mesh of json.meshes) {
  12938. this._convertMeshIds(mesh);
  12939. }
  12940. for (const node of json.nodes) {
  12941. this._convertNodeIds(node);
  12942. }
  12943. for (const node of json.scenes) {
  12944. this._convertSceneIds(node);
  12945. }
  12946. }
  12947. _convertTextureIds(texture) {
  12948. if (texture.source) {
  12949. texture.source = this._convertIdToIndex(texture.source, 'image');
  12950. }
  12951. }
  12952. _convertMeshIds(mesh) {
  12953. for (const primitive of mesh.primitives) {
  12954. const {
  12955. attributes,
  12956. indices,
  12957. material
  12958. } = primitive;
  12959. for (const attributeName in attributes) {
  12960. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12961. }
  12962. if (indices) {
  12963. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12964. }
  12965. if (material) {
  12966. primitive.material = this._convertIdToIndex(material, 'material');
  12967. }
  12968. }
  12969. }
  12970. _convertNodeIds(node) {
  12971. if (node.children) {
  12972. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12973. }
  12974. if (node.meshes) {
  12975. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12976. }
  12977. }
  12978. _convertSceneIds(scene) {
  12979. if (scene.nodes) {
  12980. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12981. }
  12982. }
  12983. _convertIdsToIndices(json, topLevelArrayName) {
  12984. if (!json[topLevelArrayName]) {
  12985. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12986. json[topLevelArrayName] = [];
  12987. }
  12988. for (const object of json[topLevelArrayName]) {
  12989. for (const key in object) {
  12990. const id = object[key];
  12991. const index = this._convertIdToIndex(id, key);
  12992. object[key] = index;
  12993. }
  12994. }
  12995. }
  12996. _convertIdToIndex(id, key) {
  12997. const arrayName = GLTF_KEYS[key];
  12998. if (arrayName in this.idToIndexMap) {
  12999. const index = this.idToIndexMap[arrayName][id];
  13000. if (!Number.isFinite(index)) {
  13001. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  13002. }
  13003. return index;
  13004. }
  13005. return id;
  13006. }
  13007. _updateObjects(json) {
  13008. for (const buffer of this.json.buffers) {
  13009. delete buffer.type;
  13010. }
  13011. }
  13012. _updateMaterial(json) {
  13013. for (const material of json.materials) {
  13014. var _material$values, _material$values2, _material$values3;
  13015. material.pbrMetallicRoughness = {
  13016. baseColorFactor: [1, 1, 1, 1],
  13017. metallicFactor: 1,
  13018. roughnessFactor: 1
  13019. };
  13020. const textureId = ((_material$values = material.values) === null || _material$values === void 0 ? void 0 : _material$values.tex) || ((_material$values2 = material.values) === null || _material$values2 === void 0 ? void 0 : _material$values2.texture2d_0) || ((_material$values3 = material.values) === null || _material$values3 === void 0 ? void 0 : _material$values3.diffuseTex);
  13021. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  13022. if (textureIndex !== -1) {
  13023. material.pbrMetallicRoughness.baseColorTexture = {
  13024. index: textureIndex
  13025. };
  13026. }
  13027. }
  13028. }
  13029. }
  13030. function normalizeGLTFV1(gltf, options = {}) {
  13031. return new GLTFV1Normalizer().normalize(gltf, options);
  13032. }
  13033. const COMPONENTS = {
  13034. SCALAR: 1,
  13035. VEC2: 2,
  13036. VEC3: 3,
  13037. VEC4: 4,
  13038. MAT2: 4,
  13039. MAT3: 9,
  13040. MAT4: 16
  13041. };
  13042. const BYTES = {
  13043. 5120: 1,
  13044. 5121: 1,
  13045. 5122: 2,
  13046. 5123: 2,
  13047. 5125: 4,
  13048. 5126: 4
  13049. };
  13050. const GL_SAMPLER = {
  13051. TEXTURE_MAG_FILTER: 0x2800,
  13052. TEXTURE_MIN_FILTER: 0x2801,
  13053. TEXTURE_WRAP_S: 0x2802,
  13054. TEXTURE_WRAP_T: 0x2803,
  13055. REPEAT: 0x2901,
  13056. LINEAR: 0x2601,
  13057. NEAREST_MIPMAP_LINEAR: 0x2702
  13058. };
  13059. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  13060. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  13061. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  13062. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  13063. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  13064. };
  13065. const DEFAULT_SAMPLER = {
  13066. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  13067. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  13068. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  13069. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  13070. };
  13071. function getBytesFromComponentType(componentType) {
  13072. return BYTES[componentType];
  13073. }
  13074. function getSizeFromAccessorType(type) {
  13075. return COMPONENTS[type];
  13076. }
  13077. class GLTFPostProcessor {
  13078. constructor() {
  13079. _defineProperty(this, "baseUri", '');
  13080. _defineProperty(this, "json", {});
  13081. _defineProperty(this, "buffers", []);
  13082. _defineProperty(this, "images", []);
  13083. }
  13084. postProcess(gltf, options = {}) {
  13085. const {
  13086. json,
  13087. buffers = [],
  13088. images = [],
  13089. baseUri = ''
  13090. } = gltf;
  13091. assert$1(json);
  13092. this.baseUri = baseUri;
  13093. this.json = json;
  13094. this.buffers = buffers;
  13095. this.images = images;
  13096. this._resolveTree(this.json, options);
  13097. return this.json;
  13098. }
  13099. _resolveTree(json, options = {}) {
  13100. if (json.bufferViews) {
  13101. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  13102. }
  13103. if (json.images) {
  13104. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  13105. }
  13106. if (json.samplers) {
  13107. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  13108. }
  13109. if (json.textures) {
  13110. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  13111. }
  13112. if (json.accessors) {
  13113. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  13114. }
  13115. if (json.materials) {
  13116. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  13117. }
  13118. if (json.meshes) {
  13119. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  13120. }
  13121. if (json.nodes) {
  13122. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  13123. }
  13124. if (json.skins) {
  13125. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  13126. }
  13127. if (json.scenes) {
  13128. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  13129. }
  13130. if (json.scene !== undefined) {
  13131. json.scene = json.scenes[this.json.scene];
  13132. }
  13133. }
  13134. getScene(index) {
  13135. return this._get('scenes', index);
  13136. }
  13137. getNode(index) {
  13138. return this._get('nodes', index);
  13139. }
  13140. getSkin(index) {
  13141. return this._get('skins', index);
  13142. }
  13143. getMesh(index) {
  13144. return this._get('meshes', index);
  13145. }
  13146. getMaterial(index) {
  13147. return this._get('materials', index);
  13148. }
  13149. getAccessor(index) {
  13150. return this._get('accessors', index);
  13151. }
  13152. getCamera(index) {
  13153. return null;
  13154. }
  13155. getTexture(index) {
  13156. return this._get('textures', index);
  13157. }
  13158. getSampler(index) {
  13159. return this._get('samplers', index);
  13160. }
  13161. getImage(index) {
  13162. return this._get('images', index);
  13163. }
  13164. getBufferView(index) {
  13165. return this._get('bufferViews', index);
  13166. }
  13167. getBuffer(index) {
  13168. return this._get('buffers', index);
  13169. }
  13170. _get(array, index) {
  13171. if (typeof index === 'object') {
  13172. return index;
  13173. }
  13174. const object = this.json[array] && this.json[array][index];
  13175. if (!object) {
  13176. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  13177. }
  13178. return object;
  13179. }
  13180. _resolveScene(scene, index) {
  13181. scene.id = scene.id || "scene-".concat(index);
  13182. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  13183. return scene;
  13184. }
  13185. _resolveNode(node, index) {
  13186. node.id = node.id || "node-".concat(index);
  13187. if (node.children) {
  13188. node.children = node.children.map(child => this.getNode(child));
  13189. }
  13190. if (node.mesh !== undefined) {
  13191. node.mesh = this.getMesh(node.mesh);
  13192. } else if (node.meshes !== undefined && node.meshes.length) {
  13193. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  13194. const mesh = this.getMesh(meshIndex);
  13195. accum.id = mesh.id;
  13196. accum.primitives = accum.primitives.concat(mesh.primitives);
  13197. return accum;
  13198. }, {
  13199. primitives: []
  13200. });
  13201. }
  13202. if (node.camera !== undefined) {
  13203. node.camera = this.getCamera(node.camera);
  13204. }
  13205. if (node.skin !== undefined) {
  13206. node.skin = this.getSkin(node.skin);
  13207. }
  13208. return node;
  13209. }
  13210. _resolveSkin(skin, index) {
  13211. skin.id = skin.id || "skin-".concat(index);
  13212. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  13213. return skin;
  13214. }
  13215. _resolveMesh(mesh, index) {
  13216. mesh.id = mesh.id || "mesh-".concat(index);
  13217. if (mesh.primitives) {
  13218. mesh.primitives = mesh.primitives.map(primitive => {
  13219. primitive = { ...primitive
  13220. };
  13221. const attributes = primitive.attributes;
  13222. primitive.attributes = {};
  13223. for (const attribute in attributes) {
  13224. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  13225. }
  13226. if (primitive.indices !== undefined) {
  13227. primitive.indices = this.getAccessor(primitive.indices);
  13228. }
  13229. if (primitive.material !== undefined) {
  13230. primitive.material = this.getMaterial(primitive.material);
  13231. }
  13232. return primitive;
  13233. });
  13234. }
  13235. return mesh;
  13236. }
  13237. _resolveMaterial(material, index) {
  13238. material.id = material.id || "material-".concat(index);
  13239. if (material.normalTexture) {
  13240. material.normalTexture = { ...material.normalTexture
  13241. };
  13242. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  13243. }
  13244. if (material.occlusionTexture) {
  13245. material.occlustionTexture = { ...material.occlustionTexture
  13246. };
  13247. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  13248. }
  13249. if (material.emissiveTexture) {
  13250. material.emmisiveTexture = { ...material.emmisiveTexture
  13251. };
  13252. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  13253. }
  13254. if (!material.emissiveFactor) {
  13255. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  13256. }
  13257. if (material.pbrMetallicRoughness) {
  13258. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  13259. };
  13260. const mr = material.pbrMetallicRoughness;
  13261. if (mr.baseColorTexture) {
  13262. mr.baseColorTexture = { ...mr.baseColorTexture
  13263. };
  13264. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  13265. }
  13266. if (mr.metallicRoughnessTexture) {
  13267. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  13268. };
  13269. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  13270. }
  13271. }
  13272. return material;
  13273. }
  13274. _resolveAccessor(accessor, index) {
  13275. accessor.id = accessor.id || "accessor-".concat(index);
  13276. if (accessor.bufferView !== undefined) {
  13277. accessor.bufferView = this.getBufferView(accessor.bufferView);
  13278. }
  13279. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  13280. accessor.components = getSizeFromAccessorType(accessor.type);
  13281. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  13282. if (accessor.bufferView) {
  13283. const buffer = accessor.bufferView.buffer;
  13284. const {
  13285. ArrayType,
  13286. byteLength
  13287. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  13288. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  13289. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  13290. if (accessor.bufferView.byteStride) {
  13291. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  13292. }
  13293. accessor.value = new ArrayType(cutBuffer);
  13294. }
  13295. return accessor;
  13296. }
  13297. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  13298. const result = new Uint8Array(count * bytesPerElement);
  13299. for (let i = 0; i < count; i++) {
  13300. const elementOffset = byteOffset + i * byteStride;
  13301. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  13302. }
  13303. return result.buffer;
  13304. }
  13305. _resolveTexture(texture, index) {
  13306. texture.id = texture.id || "texture-".concat(index);
  13307. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  13308. texture.source = this.getImage(texture.source);
  13309. return texture;
  13310. }
  13311. _resolveSampler(sampler, index) {
  13312. sampler.id = sampler.id || "sampler-".concat(index);
  13313. sampler.parameters = {};
  13314. for (const key in sampler) {
  13315. const glEnum = this._enumSamplerParameter(key);
  13316. if (glEnum !== undefined) {
  13317. sampler.parameters[glEnum] = sampler[key];
  13318. }
  13319. }
  13320. return sampler;
  13321. }
  13322. _enumSamplerParameter(key) {
  13323. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  13324. }
  13325. _resolveImage(image, index) {
  13326. image.id = image.id || "image-".concat(index);
  13327. if (image.bufferView !== undefined) {
  13328. image.bufferView = this.getBufferView(image.bufferView);
  13329. }
  13330. const preloadedImage = this.images[index];
  13331. if (preloadedImage) {
  13332. image.image = preloadedImage;
  13333. }
  13334. return image;
  13335. }
  13336. _resolveBufferView(bufferView, index) {
  13337. const bufferIndex = bufferView.buffer;
  13338. const result = {
  13339. id: "bufferView-".concat(index),
  13340. ...bufferView,
  13341. buffer: this.buffers[bufferIndex]
  13342. };
  13343. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  13344. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  13345. if ('byteOffset' in bufferView) {
  13346. byteOffset += bufferView.byteOffset;
  13347. }
  13348. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  13349. return result;
  13350. }
  13351. _resolveCamera(camera, index) {
  13352. camera.id = camera.id || "camera-".concat(index);
  13353. if (camera.perspective) ;
  13354. if (camera.orthographic) ;
  13355. return camera;
  13356. }
  13357. }
  13358. function postProcessGLTF(gltf, options) {
  13359. return new GLTFPostProcessor().postProcess(gltf, options);
  13360. }
  13361. const MAGIC_glTF = 0x676c5446;
  13362. const GLB_FILE_HEADER_SIZE = 12;
  13363. const GLB_CHUNK_HEADER_SIZE = 8;
  13364. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  13365. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  13366. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  13367. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  13368. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  13369. const LE = true;
  13370. function getMagicString(dataView, byteOffset = 0) {
  13371. return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
  13372. }
  13373. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  13374. const dataView = new DataView(arrayBuffer);
  13375. const {
  13376. magic = MAGIC_glTF
  13377. } = options;
  13378. const magic1 = dataView.getUint32(byteOffset, false);
  13379. return magic1 === magic || magic1 === MAGIC_glTF;
  13380. }
  13381. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  13382. const dataView = new DataView(arrayBuffer);
  13383. const type = getMagicString(dataView, byteOffset + 0);
  13384. const version = dataView.getUint32(byteOffset + 4, LE);
  13385. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  13386. Object.assign(glb, {
  13387. header: {
  13388. byteOffset,
  13389. byteLength,
  13390. hasBinChunk: false
  13391. },
  13392. type,
  13393. version,
  13394. json: {},
  13395. binChunks: []
  13396. });
  13397. byteOffset += GLB_FILE_HEADER_SIZE;
  13398. switch (glb.version) {
  13399. case 1:
  13400. return parseGLBV1(glb, dataView, byteOffset);
  13401. case 2:
  13402. return parseGLBV2(glb, dataView, byteOffset, options = {});
  13403. default:
  13404. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  13405. }
  13406. }
  13407. function parseGLBV1(glb, dataView, byteOffset) {
  13408. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13409. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  13410. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  13411. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13412. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  13413. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  13414. byteOffset += contentLength;
  13415. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13416. return byteOffset;
  13417. }
  13418. function parseGLBV2(glb, dataView, byteOffset, options) {
  13419. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13420. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13421. return byteOffset + glb.header.byteLength;
  13422. }
  13423. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13424. while (byteOffset + 8 <= glb.header.byteLength) {
  13425. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13426. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13427. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13428. switch (chunkFormat) {
  13429. case GLB_CHUNK_TYPE_JSON:
  13430. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13431. break;
  13432. case GLB_CHUNK_TYPE_BIN:
  13433. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13434. break;
  13435. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13436. if (!options.strict) {
  13437. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13438. }
  13439. break;
  13440. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13441. if (!options.strict) {
  13442. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13443. }
  13444. break;
  13445. }
  13446. byteOffset += padToNBytes(chunkLength, 4);
  13447. }
  13448. return byteOffset;
  13449. }
  13450. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13451. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13452. const textDecoder = new TextDecoder('utf8');
  13453. const jsonText = textDecoder.decode(jsonChunk);
  13454. glb.json = JSON.parse(jsonText);
  13455. return padToNBytes(chunkLength, 4);
  13456. }
  13457. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13458. glb.header.hasBinChunk = true;
  13459. glb.binChunks.push({
  13460. byteOffset,
  13461. byteLength: chunkLength,
  13462. arrayBuffer: dataView.buffer
  13463. });
  13464. return padToNBytes(chunkLength, 4);
  13465. }
  13466. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13467. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13468. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13469. normalizeGLTFV1(gltf, {
  13470. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13471. });
  13472. preprocessExtensions(gltf, options, context);
  13473. const promises = [];
  13474. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13475. await loadBuffers(gltf, options, context);
  13476. }
  13477. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13478. const promise = loadImages(gltf, options, context);
  13479. promises.push(promise);
  13480. }
  13481. const promise = decodeExtensions(gltf, options, context);
  13482. promises.push(promise);
  13483. await Promise.all(promises);
  13484. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13485. }
  13486. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13487. if (options.uri) {
  13488. gltf.baseUri = options.uri;
  13489. }
  13490. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13491. const textDecoder = new TextDecoder();
  13492. data = textDecoder.decode(data);
  13493. }
  13494. if (typeof data === 'string') {
  13495. gltf.json = parseJSON(data);
  13496. } else if (data instanceof ArrayBuffer) {
  13497. const glb = {};
  13498. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13499. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13500. gltf._glb = glb;
  13501. gltf.json = glb.json;
  13502. } else {
  13503. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13504. }
  13505. const buffers = gltf.json.buffers || [];
  13506. gltf.buffers = new Array(buffers.length).fill(null);
  13507. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13508. const {
  13509. binChunks
  13510. } = gltf._glb;
  13511. gltf.buffers[0] = {
  13512. arrayBuffer: binChunks[0].arrayBuffer,
  13513. byteOffset: binChunks[0].byteOffset,
  13514. byteLength: binChunks[0].byteLength
  13515. };
  13516. }
  13517. const images = gltf.json.images || [];
  13518. gltf.images = new Array(images.length).fill({});
  13519. }
  13520. async function loadBuffers(gltf, options, context) {
  13521. const buffers = gltf.json.buffers || [];
  13522. for (let i = 0; i < buffers.length; ++i) {
  13523. const buffer = buffers[i];
  13524. if (buffer.uri) {
  13525. var _context$fetch, _response$arrayBuffer;
  13526. const {
  13527. fetch
  13528. } = context;
  13529. assert$1(fetch);
  13530. const uri = resolveUrl(buffer.uri, options);
  13531. const response = await (context === null || context === void 0 ? void 0 : (_context$fetch = context.fetch) === null || _context$fetch === void 0 ? void 0 : _context$fetch.call(context, uri));
  13532. const arrayBuffer = await (response === null || response === void 0 ? void 0 : (_response$arrayBuffer = response.arrayBuffer) === null || _response$arrayBuffer === void 0 ? void 0 : _response$arrayBuffer.call(response));
  13533. gltf.buffers[i] = {
  13534. arrayBuffer,
  13535. byteOffset: 0,
  13536. byteLength: arrayBuffer.byteLength
  13537. };
  13538. delete buffer.uri;
  13539. } else if (gltf.buffers[i] === null) {
  13540. gltf.buffers[i] = {
  13541. arrayBuffer: new ArrayBuffer(buffer.byteLength),
  13542. byteOffset: 0,
  13543. byteLength: buffer.byteLength
  13544. };
  13545. }
  13546. }
  13547. }
  13548. async function loadImages(gltf, options, context) {
  13549. const imageIndices = getReferencesImageIndices(gltf);
  13550. const images = gltf.json.images || [];
  13551. const promises = [];
  13552. for (const imageIndex of imageIndices) {
  13553. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13554. }
  13555. return await Promise.all(promises);
  13556. }
  13557. function getReferencesImageIndices(gltf) {
  13558. const imageIndices = new Set();
  13559. const textures = gltf.json.textures || [];
  13560. for (const texture of textures) {
  13561. if (texture.source !== undefined) {
  13562. imageIndices.add(texture.source);
  13563. }
  13564. }
  13565. return Array.from(imageIndices).sort();
  13566. }
  13567. async function loadImage(gltf, image, index, options, context) {
  13568. const {
  13569. fetch,
  13570. parse
  13571. } = context;
  13572. let arrayBuffer;
  13573. if (image.uri && !image.hasOwnProperty('bufferView')) {
  13574. const uri = resolveUrl(image.uri, options);
  13575. const response = await fetch(uri);
  13576. arrayBuffer = await response.arrayBuffer();
  13577. }
  13578. if (Number.isFinite(image.bufferView)) {
  13579. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13580. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13581. }
  13582. assert$1(arrayBuffer, 'glTF image has no data');
  13583. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13584. mimeType: image.mimeType,
  13585. basis: options.basis || {
  13586. format: selectSupportedBasisFormat()
  13587. }
  13588. }, context);
  13589. if (parsedImage && parsedImage[0]) {
  13590. parsedImage = {
  13591. compressed: true,
  13592. mipmaps: false,
  13593. width: parsedImage[0].width,
  13594. height: parsedImage[0].height,
  13595. data: parsedImage[0]
  13596. };
  13597. }
  13598. gltf.images = gltf.images || [];
  13599. gltf.images[index] = parsedImage;
  13600. }
  13601. const GLTFLoader = {
  13602. name: 'glTF',
  13603. id: 'gltf',
  13604. module: 'gltf',
  13605. version: VERSION$3,
  13606. extensions: ['gltf', 'glb'],
  13607. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13608. text: true,
  13609. binary: true,
  13610. tests: ['glTF'],
  13611. parse: parse$1,
  13612. options: {
  13613. gltf: {
  13614. normalize: true,
  13615. loadBuffers: true,
  13616. loadImages: true,
  13617. decompressMeshes: true,
  13618. postProcess: true
  13619. },
  13620. log: console
  13621. },
  13622. deprecatedOptions: {
  13623. fetchImages: 'gltf.loadImages',
  13624. createImages: 'gltf.loadImages',
  13625. decompress: 'gltf.decompressMeshes',
  13626. postProcess: 'gltf.postProcess',
  13627. gltf: {
  13628. decompress: 'gltf.decompressMeshes'
  13629. }
  13630. }
  13631. };
  13632. async function parse$1(arrayBuffer, options = {}, context) {
  13633. options = { ...GLTFLoader.options,
  13634. ...options
  13635. };
  13636. options.gltf = { ...GLTFLoader.options.gltf,
  13637. ...options.gltf
  13638. };
  13639. const {
  13640. byteOffset = 0
  13641. } = options;
  13642. const gltf = {};
  13643. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13644. }
  13645. const GLTF_FORMAT = {
  13646. URI: 0,
  13647. EMBEDDED: 1
  13648. };
  13649. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13650. tile.rotateYtoZ = true;
  13651. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13652. if (gltfByteLength === 0) {
  13653. throw new Error('glTF byte length must be greater than 0.');
  13654. }
  13655. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13656. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13657. tile.gltfByteOffset = 0;
  13658. tile.gltfByteLength = gltfByteLength;
  13659. if (byteOffset % 4 === 0) ; else {
  13660. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13661. }
  13662. return tile.byteOffset + tile.byteLength;
  13663. }
  13664. async function extractGLTF(tile, gltfFormat, options, context) {
  13665. const tile3DOptions = options['3d-tiles'] || {};
  13666. extractGLTFBufferOrURL(tile, gltfFormat);
  13667. if (tile3DOptions.loadGLTF) {
  13668. const {
  13669. parse,
  13670. fetch
  13671. } = context;
  13672. if (tile.gltfUrl) {
  13673. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13674. tile.gltfByteOffset = 0;
  13675. }
  13676. if (tile.gltfArrayBuffer) {
  13677. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13678. delete tile.gltfArrayBuffer;
  13679. delete tile.gltfByteOffset;
  13680. delete tile.gltfByteLength;
  13681. }
  13682. }
  13683. }
  13684. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13685. switch (gltfFormat) {
  13686. case GLTF_FORMAT.URI:
  13687. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13688. const textDecoder = new TextDecoder();
  13689. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13690. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13691. delete tile.gltfArrayBuffer;
  13692. delete tile.gltfByteOffset;
  13693. delete tile.gltfByteLength;
  13694. break;
  13695. case GLTF_FORMAT.EMBEDDED:
  13696. break;
  13697. default:
  13698. throw new Error('b3dm: Illegal glTF format field');
  13699. }
  13700. }
  13701. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13702. var _tile$gltf;
  13703. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13704. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13705. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13706. if (extensions && extensions.CESIUM_RTC) {
  13707. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13708. }
  13709. return byteOffset;
  13710. }
  13711. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13712. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13713. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13714. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13715. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13716. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13717. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13718. return byteOffset;
  13719. }
  13720. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13721. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13722. await extractGLTF(tile, tile.gltfFormat, options, context);
  13723. return byteOffset;
  13724. }
  13725. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13726. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13727. if (tile.version !== 1) {
  13728. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13729. }
  13730. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13731. const view = new DataView(arrayBuffer);
  13732. tile.gltfFormat = view.getUint32(byteOffset, true);
  13733. byteOffset += 4;
  13734. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13735. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13736. if (tile.featureTableJsonByteLength === 0) {
  13737. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13738. }
  13739. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13740. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13741. featureTable.featuresLength = instancesLength;
  13742. if (!Number.isFinite(instancesLength)) {
  13743. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13744. }
  13745. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13746. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13747. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13748. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13749. return byteOffset;
  13750. }
  13751. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13752. const collectionOptions = {
  13753. instances: new Array(instancesLength),
  13754. batchTable: tile._batchTable,
  13755. cull: false,
  13756. url: undefined,
  13757. gltf: undefined,
  13758. basePath: undefined,
  13759. incrementallyLoadTextures: false,
  13760. forwardAxis: [1, 0, 0]
  13761. };
  13762. const instances = collectionOptions.instances;
  13763. const instancePosition = new Vector3();
  13764. new Vector3();
  13765. new Vector3();
  13766. new Vector3();
  13767. const instanceRotation = new Matrix3();
  13768. const instanceQuaternion = new Quaternion();
  13769. const instanceScale = new Vector3();
  13770. const instanceTranslationRotationScale = {};
  13771. const instanceTransform = new Matrix4();
  13772. const scratch1 = [];
  13773. const scratch2 = [];
  13774. const scratchVector1 = new Vector3();
  13775. const scratchVector2 = new Vector3();
  13776. for (let i = 0; i < instancesLength; i++) {
  13777. let position;
  13778. if (featureTable.hasProperty('POSITION')) {
  13779. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13780. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13781. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13782. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13783. if (!quantizedVolumeOffset) {
  13784. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13785. }
  13786. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13787. if (!quantizedVolumeScale) {
  13788. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13789. }
  13790. const MAX_UNSIGNED_SHORT = 65535.0;
  13791. for (let j = 0; j < 3; j++) {
  13792. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13793. }
  13794. }
  13795. if (!position) {
  13796. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13797. }
  13798. instancePosition.copy(position);
  13799. instanceTranslationRotationScale.translation = instancePosition;
  13800. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13801. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13802. if (tile.normalUp) {
  13803. if (!tile.normalRight) {
  13804. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13805. }
  13806. tile.hasCustomOrientation = true;
  13807. } else {
  13808. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13809. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13810. if (tile.octNormalUp) {
  13811. if (!tile.octNormalRight) {
  13812. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13813. }
  13814. throw new Error('i3dm: oct-encoded orientation not implemented');
  13815. } else if (tile.eastNorthUp) {
  13816. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13817. instanceTransform.getRotationMatrix3(instanceRotation);
  13818. } else {
  13819. instanceRotation.identity();
  13820. }
  13821. }
  13822. instanceQuaternion.fromMatrix3(instanceRotation);
  13823. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13824. instanceScale.set(1.0, 1.0, 1.0);
  13825. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13826. if (Number.isFinite(scale)) {
  13827. instanceScale.multiplyByScalar(scale);
  13828. }
  13829. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13830. if (nonUniformScale) {
  13831. instanceScale.scale(nonUniformScale);
  13832. }
  13833. instanceTranslationRotationScale.scale = instanceScale;
  13834. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13835. if (batchId === undefined) {
  13836. batchId = i;
  13837. }
  13838. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13839. instanceTransform.identity();
  13840. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13841. instanceTransform.multiplyRight(rotationMatrix);
  13842. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13843. const modelMatrix = instanceTransform.clone();
  13844. instances[i] = {
  13845. modelMatrix,
  13846. batchId
  13847. };
  13848. }
  13849. tile.instances = instances;
  13850. }
  13851. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13852. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13853. const view = new DataView(arrayBuffer);
  13854. tile.tilesLength = view.getUint32(byteOffset, true);
  13855. byteOffset += 4;
  13856. tile.tiles = [];
  13857. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13858. const subtile = {};
  13859. tile.tiles.push(subtile);
  13860. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13861. }
  13862. return byteOffset;
  13863. }
  13864. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13865. tile.rotateYtoZ = true;
  13866. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13867. const {
  13868. parse
  13869. } = context;
  13870. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13871. }
  13872. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13873. tile.byteOffset = byteOffset;
  13874. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13875. switch (tile.type) {
  13876. case TILE3D_TYPE.COMPOSITE:
  13877. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13878. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13879. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13880. case TILE3D_TYPE.GLTF:
  13881. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13882. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13883. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13884. case TILE3D_TYPE.POINT_CLOUD:
  13885. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13886. default:
  13887. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13888. }
  13889. }
  13890. const SUBTREE_FILE_MAGIC = 0x74627573;
  13891. const SUBTREE_FILE_VERSION = 1;
  13892. async function parse3DTilesSubtree(data) {
  13893. const magic = new Uint32Array(data.slice(0, 4));
  13894. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13895. throw new Error('Wrong subtree file magic number');
  13896. }
  13897. const version = new Uint32Array(data.slice(4, 8));
  13898. if (version[0] !== SUBTREE_FILE_VERSION) {
  13899. throw new Error('Wrong subtree file verson, must be 1');
  13900. }
  13901. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13902. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13903. const textDecoder = new TextDecoder('utf8');
  13904. const string = textDecoder.decode(stringAttribute);
  13905. const subtree = JSON.parse(string);
  13906. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13907. let internalBinaryBuffer = new ArrayBuffer(0);
  13908. if (binaryByteLength) {
  13909. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13910. }
  13911. if ('bufferView' in subtree.tileAvailability) {
  13912. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13913. }
  13914. if ('bufferView' in subtree.contentAvailability) {
  13915. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13916. }
  13917. if ('bufferView' in subtree.childSubtreeAvailability) {
  13918. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13919. }
  13920. return subtree;
  13921. }
  13922. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13923. const bufferViewIndex = subtree[name].bufferView;
  13924. const bufferView = subtree.bufferViews[bufferViewIndex];
  13925. const buffer = subtree.buffers[bufferView.buffer];
  13926. if (buffer.uri) {
  13927. const response = await fetchFile(buffer.uri);
  13928. const data = await response.arrayBuffer();
  13929. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13930. }
  13931. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13932. }
  13933. function parseUint64Value(buffer) {
  13934. const dataView = new DataView(buffer);
  13935. const left = dataView.getUint32(0, true);
  13936. const right = dataView.getUint32(4, true);
  13937. return left + 2 ** 32 * right;
  13938. }
  13939. const Tile3DSubtreeLoader = {
  13940. id: '3d-tiles-subtree',
  13941. name: '3D Tiles Subtree',
  13942. module: '3d-tiles',
  13943. version: VERSION$5,
  13944. extensions: ['subtree'],
  13945. mimeTypes: ['application/octet-stream'],
  13946. tests: ['subtree'],
  13947. parse: parse3DTilesSubtree,
  13948. options: {}
  13949. };
  13950. const QUADTREE_DEVISION_COUNT = 4;
  13951. const OCTREE_DEVISION_COUNT = 8;
  13952. const SUBDIVISION_COUNT_MAP = {
  13953. QUADTREE: QUADTREE_DEVISION_COUNT,
  13954. OCTREE: OCTREE_DEVISION_COUNT
  13955. };
  13956. async function parseImplicitTiles(params) {
  13957. const {
  13958. options,
  13959. parentData = {
  13960. mortonIndex: 0,
  13961. x: 0,
  13962. y: 0,
  13963. z: 0
  13964. },
  13965. childIndex = 0,
  13966. globalData = {
  13967. level: 0,
  13968. mortonIndex: 0,
  13969. x: 0,
  13970. y: 0,
  13971. z: 0
  13972. }
  13973. } = params;
  13974. let {
  13975. subtree,
  13976. level = 0
  13977. } = params;
  13978. const {
  13979. subdivisionScheme,
  13980. subtreeLevels,
  13981. maximumLevel,
  13982. contentUrlTemplate,
  13983. subtreesUriTemplate,
  13984. basePath
  13985. } = options;
  13986. const tile = {
  13987. children: [],
  13988. lodMetricValue: 0,
  13989. contentUrl: ''
  13990. };
  13991. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13992. const childX = childIndex & 0b01;
  13993. const childY = childIndex >> 1 & 0b01;
  13994. const childZ = childIndex >> 2 & 0b01;
  13995. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13996. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13997. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13998. let childTileX = concatBits(parentData.x, childX);
  13999. let childTileY = concatBits(parentData.y, childY);
  14000. let childTileZ = concatBits(parentData.z, childZ);
  14001. let isChildSubtreeAvailable = false;
  14002. if (level + 1 > subtreeLevels) {
  14003. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  14004. }
  14005. const x = concatBits(globalData.x, childTileX);
  14006. const y = concatBits(globalData.y, childTileY);
  14007. const z = concatBits(globalData.z, childTileZ);
  14008. const lev = level + globalData.level;
  14009. if (isChildSubtreeAvailable) {
  14010. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  14011. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  14012. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  14013. subtree = childSubtree;
  14014. globalData.mortonIndex = childTileMortonIndex;
  14015. globalData.x = childTileX;
  14016. globalData.y = childTileY;
  14017. globalData.z = childTileZ;
  14018. globalData.level = level;
  14019. childTileMortonIndex = 0;
  14020. tileAvailabilityIndex = 0;
  14021. childTileX = 0;
  14022. childTileY = 0;
  14023. childTileZ = 0;
  14024. level = 0;
  14025. }
  14026. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  14027. if (!isTileAvailable || level > maximumLevel) {
  14028. return tile;
  14029. }
  14030. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  14031. if (isContentAvailable) {
  14032. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  14033. }
  14034. const childTileLevel = level + 1;
  14035. const pData = {
  14036. mortonIndex: childTileMortonIndex,
  14037. x: childTileX,
  14038. y: childTileY,
  14039. z: childTileZ
  14040. };
  14041. for (let index = 0; index < childrenPerTile; index++) {
  14042. const currentTile = await parseImplicitTiles({
  14043. subtree,
  14044. options,
  14045. parentData: pData,
  14046. childIndex: index,
  14047. level: childTileLevel,
  14048. globalData
  14049. });
  14050. if (currentTile.contentUrl || currentTile.children.length) {
  14051. const globalLevel = lev + 1;
  14052. const childCoordinates = {
  14053. childTileX,
  14054. childTileY,
  14055. childTileZ
  14056. };
  14057. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  14058. tile.children.push(formattedTile);
  14059. }
  14060. }
  14061. return tile;
  14062. }
  14063. function getAvailabilityResult(availabilityData, index) {
  14064. if ('constant' in availabilityData) {
  14065. return Boolean(availabilityData.constant);
  14066. }
  14067. if (availabilityData.explicitBitstream) {
  14068. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  14069. }
  14070. return false;
  14071. }
  14072. function formatTileData(tile, level, childCoordinates, options) {
  14073. const {
  14074. basePath,
  14075. refine,
  14076. getRefine,
  14077. lodMetricType,
  14078. getTileType,
  14079. rootLodMetricValue,
  14080. rootBoundingVolume
  14081. } = options;
  14082. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  14083. const lodMetricValue = rootLodMetricValue / 2 ** level;
  14084. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  14085. return {
  14086. children: tile.children,
  14087. contentUrl: tile.contentUrl,
  14088. content: {
  14089. uri
  14090. },
  14091. id: tile.contentUrl,
  14092. refine: getRefine(refine),
  14093. type: getTileType(tile),
  14094. lodMetricType,
  14095. lodMetricValue,
  14096. boundingVolume
  14097. };
  14098. }
  14099. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  14100. if (rootBoundingVolume.region) {
  14101. const {
  14102. childTileX,
  14103. childTileY,
  14104. childTileZ
  14105. } = childCoordinates;
  14106. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  14107. const boundingVolumesCount = 2 ** level;
  14108. const sizeX = (east - west) / boundingVolumesCount;
  14109. const sizeY = (north - south) / boundingVolumesCount;
  14110. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  14111. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  14112. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  14113. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  14114. return {
  14115. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  14116. };
  14117. }
  14118. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  14119. return null;
  14120. }
  14121. function concatBits(first, second) {
  14122. return parseInt(first.toString(2) + second.toString(2), 2);
  14123. }
  14124. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  14125. const mapUrl = generateMapUrl({
  14126. level,
  14127. x,
  14128. y,
  14129. z
  14130. });
  14131. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  14132. }
  14133. function generateMapUrl(items) {
  14134. const mapUrl = {};
  14135. for (const key in items) {
  14136. mapUrl["{".concat(key, "}")] = items[key];
  14137. }
  14138. return mapUrl;
  14139. }
  14140. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  14141. const byteIndex = Math.floor(availabilityIndex / 8);
  14142. const bitIndex = availabilityIndex % 8;
  14143. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  14144. return bitValue === 1;
  14145. }
  14146. function getTileType(tile) {
  14147. if (!tile.contentUrl) {
  14148. return TILE_TYPE.EMPTY;
  14149. }
  14150. const contentUrl = tile.contentUrl;
  14151. const fileExtension = contentUrl.split('.').pop();
  14152. switch (fileExtension) {
  14153. case 'pnts':
  14154. return TILE_TYPE.POINTCLOUD;
  14155. case 'i3dm':
  14156. case 'b3dm':
  14157. case 'glb':
  14158. case 'gltf':
  14159. return TILE_TYPE.SCENEGRAPH;
  14160. default:
  14161. return fileExtension;
  14162. }
  14163. }
  14164. function getRefine(refine) {
  14165. switch (refine) {
  14166. case 'REPLACE':
  14167. case 'replace':
  14168. return TILE_REFINEMENT.REPLACE;
  14169. case 'ADD':
  14170. case 'add':
  14171. return TILE_REFINEMENT.ADD;
  14172. default:
  14173. return refine;
  14174. }
  14175. }
  14176. function resolveUri(uri, basePath) {
  14177. const urlSchemeRegex = /^[a-z][0-9a-z+.-]*:/i;
  14178. if (urlSchemeRegex.test(basePath)) {
  14179. const url = new URL(uri, "".concat(basePath, "/"));
  14180. return decodeURI(url.toString());
  14181. } else if (uri.startsWith('/')) {
  14182. return uri;
  14183. }
  14184. return "".concat(basePath, "/").concat(uri);
  14185. }
  14186. function normalizeTileData(tile, options) {
  14187. if (!tile) {
  14188. return null;
  14189. }
  14190. if (tile.content) {
  14191. const contentUri = tile.content.uri || tile.content.url;
  14192. tile.contentUrl = resolveUri(contentUri, options.basePath);
  14193. }
  14194. tile.id = tile.contentUrl;
  14195. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14196. tile.lodMetricValue = tile.geometricError;
  14197. tile.transformMatrix = tile.transform;
  14198. tile.type = getTileType(tile);
  14199. tile.refine = getRefine(tile.refine);
  14200. return tile;
  14201. }
  14202. function normalizeTileHeaders(tileset) {
  14203. const basePath = tileset.basePath;
  14204. const root = normalizeTileData(tileset.root, tileset);
  14205. const stack = [];
  14206. stack.push(root);
  14207. while (stack.length > 0) {
  14208. const tile = stack.pop() || {};
  14209. const children = tile.children || [];
  14210. for (const childHeader of children) {
  14211. normalizeTileData(childHeader, {
  14212. basePath
  14213. });
  14214. stack.push(childHeader);
  14215. }
  14216. }
  14217. return root;
  14218. }
  14219. async function normalizeImplicitTileHeaders(tileset) {
  14220. if (!tileset.root) {
  14221. return null;
  14222. }
  14223. const basePath = tileset.basePath;
  14224. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  14225. const {
  14226. subdivisionScheme,
  14227. maximumLevel,
  14228. subtreeLevels,
  14229. subtrees: {
  14230. uri: subtreesUriTemplate
  14231. }
  14232. } = implicitTilingExtension;
  14233. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  14234. const rootSubtreeUrl = resolveUri(subtreeUrl, basePath);
  14235. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  14236. const contentUrlTemplate = resolveUri(tileset.root.content.uri, basePath);
  14237. const refine = tileset.root.refine;
  14238. const rootLodMetricValue = tileset.root.geometricError;
  14239. const rootBoundingVolume = tileset.root.boundingVolume;
  14240. const options = {
  14241. contentUrlTemplate,
  14242. subtreesUriTemplate,
  14243. subdivisionScheme,
  14244. subtreeLevels,
  14245. maximumLevel,
  14246. refine,
  14247. basePath,
  14248. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  14249. rootLodMetricValue,
  14250. rootBoundingVolume,
  14251. getTileType,
  14252. getRefine
  14253. };
  14254. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  14255. }
  14256. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  14257. if (!tile) {
  14258. return null;
  14259. }
  14260. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14261. tile.lodMetricValue = tile.geometricError;
  14262. tile.transformMatrix = tile.transform;
  14263. const {
  14264. children,
  14265. contentUrl
  14266. } = await parseImplicitTiles({
  14267. subtree: rootSubtree,
  14268. options
  14269. });
  14270. if (contentUrl) {
  14271. tile.contentUrl = contentUrl;
  14272. tile.content = {
  14273. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  14274. };
  14275. }
  14276. tile.refine = getRefine(tile.refine);
  14277. tile.type = getTileType(tile);
  14278. tile.children = children;
  14279. tile.id = tile.contentUrl;
  14280. return tile;
  14281. }
  14282. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  14283. const Tiles3DLoader = {
  14284. id: '3d-tiles',
  14285. name: '3D Tiles',
  14286. module: '3d-tiles',
  14287. version: VERSION$5,
  14288. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  14289. mimeTypes: ['application/octet-stream'],
  14290. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  14291. parse,
  14292. options: {
  14293. '3d-tiles': {
  14294. loadGLTF: true,
  14295. decodeQuantizedPositions: false,
  14296. isTileset: 'auto',
  14297. assetGltfUpAxis: null
  14298. }
  14299. }
  14300. };
  14301. function getBaseUri(tileset) {
  14302. return dirname(tileset.url);
  14303. }
  14304. async function parseTile(arrayBuffer, options, context) {
  14305. const tile = {
  14306. content: {
  14307. featureIds: null
  14308. }
  14309. };
  14310. const byteOffset = 0;
  14311. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  14312. return tile.content;
  14313. }
  14314. async function parseTileset(data, options, context) {
  14315. var _tilesetJson$root;
  14316. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  14317. tilesetJson.loader = options.loader || Tiles3DLoader;
  14318. tilesetJson.url = context.url;
  14319. tilesetJson.basePath = getBaseUri(tilesetJson);
  14320. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  14321. tilesetJson.type = TILESET_TYPE.TILES3D;
  14322. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14323. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  14324. return tilesetJson;
  14325. }
  14326. async function parse(data, options, context) {
  14327. const loaderOptions = options['3d-tiles'] || {};
  14328. let isTileset;
  14329. if (loaderOptions.isTileset === 'auto') {
  14330. isTileset = context.url && context.url.indexOf('.json') !== -1;
  14331. } else {
  14332. isTileset = loaderOptions.isTileset;
  14333. }
  14334. if (isTileset) {
  14335. data = await parseTileset(data, options, context);
  14336. } else {
  14337. data = await parseTile(data, options, context);
  14338. }
  14339. return data;
  14340. }
  14341. function hasImplicitTilingExtension(tilesetJson) {
  14342. var _tilesetJson$extensio, _tilesetJson$extensio2;
  14343. return (tilesetJson === null || tilesetJson === void 0 ? void 0 : (_tilesetJson$extensio = tilesetJson.extensionsRequired) === null || _tilesetJson$extensio === void 0 ? void 0 : _tilesetJson$extensio.includes(IMPLICIT_TILING_EXTENSION_NAME)) && (tilesetJson === null || tilesetJson === void 0 ? void 0 : (_tilesetJson$extensio2 = tilesetJson.extensionsUsed) === null || _tilesetJson$extensio2 === void 0 ? void 0 : _tilesetJson$extensio2.includes(IMPLICIT_TILING_EXTENSION_NAME));
  14344. }
  14345. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  14346. async function getIonTilesetMetadata(accessToken, assetId) {
  14347. if (!assetId) {
  14348. const assets = await getIonAssets(accessToken);
  14349. for (const item of assets.items) {
  14350. if (item.type === '3DTILES') {
  14351. assetId = item.id;
  14352. }
  14353. }
  14354. }
  14355. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  14356. const {
  14357. type,
  14358. url
  14359. } = ionAssetMetadata;
  14360. assert$7(type === '3DTILES' && url);
  14361. ionAssetMetadata.headers = {
  14362. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  14363. };
  14364. return ionAssetMetadata;
  14365. }
  14366. async function getIonAssets(accessToken) {
  14367. assert$7(accessToken);
  14368. const url = CESIUM_ION_URL;
  14369. const headers = {
  14370. Authorization: "Bearer ".concat(accessToken)
  14371. };
  14372. const response = await fetchFile(url, {
  14373. fetch: {
  14374. headers
  14375. }
  14376. });
  14377. if (!response.ok) {
  14378. throw new Error(response.statusText);
  14379. }
  14380. return await response.json();
  14381. }
  14382. async function getIonAssetMetadata(accessToken, assetId) {
  14383. assert$7(accessToken, assetId);
  14384. const headers = {
  14385. Authorization: "Bearer ".concat(accessToken)
  14386. };
  14387. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  14388. let response = await fetchFile("".concat(url), {
  14389. fetch: {
  14390. headers
  14391. }
  14392. });
  14393. if (!response.ok) {
  14394. throw new Error(response.statusText);
  14395. }
  14396. let metadata = await response.json();
  14397. response = await fetchFile("".concat(url, "/endpoint"), {
  14398. fetch: {
  14399. headers
  14400. }
  14401. });
  14402. if (!response.ok) {
  14403. throw new Error(response.statusText);
  14404. }
  14405. const tilesetInfo = await response.json();
  14406. metadata = { ...metadata,
  14407. ...tilesetInfo
  14408. };
  14409. return metadata;
  14410. }
  14411. async function preload(url, options = {}) {
  14412. options = options['cesium-ion'] || {};
  14413. const {
  14414. accessToken
  14415. } = options;
  14416. let assetId = options.assetId;
  14417. if (!Number.isFinite(assetId)) {
  14418. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  14419. assetId = matched && matched[1];
  14420. }
  14421. return getIonTilesetMetadata(accessToken, assetId);
  14422. }
  14423. const CesiumIonLoader = { ...Tiles3DLoader,
  14424. id: 'cesium-ion',
  14425. name: 'Cesium Ion',
  14426. preload,
  14427. parse: async (data, options, context) => {
  14428. options = { ...options
  14429. };
  14430. options['3d-tiles'] = options['cesium-ion'];
  14431. options.loader = CesiumIonLoader;
  14432. return Tiles3DLoader.parse(data, options, context);
  14433. },
  14434. options: {
  14435. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  14436. accessToken: null
  14437. }
  14438. }
  14439. };
  14440. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  14441. function generateGradientTexture(gradient) {
  14442. const size = 64;
  14443. // create canvas
  14444. const canvas = document.createElement('canvas');
  14445. canvas.width = size;
  14446. canvas.height = size;
  14447. // get context
  14448. const context = canvas.getContext('2d');
  14449. // draw gradient
  14450. context.rect(0, 0, size, size);
  14451. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14452. for (let i = 0; i < gradient.length; i++) {
  14453. const step = gradient[i];
  14454. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14455. }
  14456. context.fillStyle = ctxGradient;
  14457. context.fill();
  14458. //let texture = new THREE.Texture(canvas);
  14459. const texture = new CanvasTexture(canvas);
  14460. texture.needsUpdate = true;
  14461. texture.minFilter = LinearFilter;
  14462. texture.wrapS = RepeatWrapping;
  14463. texture.wrapT = RepeatWrapping;
  14464. texture.repeat.set(2, 2);
  14465. // textureImage = texture.image;
  14466. return texture;
  14467. }
  14468. function getCameraFrustum(camera) {
  14469. camera.updateMatrix(); // make sure camera's local matrix is updated
  14470. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14471. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14472. const frustum = new Frustum();
  14473. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14474. return frustum;
  14475. }
  14476. function loadersPlaneToMesh(plane) {
  14477. const group = new Group();
  14478. // Create a basic rectangle geometry from math.gl plane
  14479. const planeGeometry = new PlaneGeometry(10, 5);
  14480. // Align the geometry to the plane
  14481. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14482. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14483. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14484. planeGeometry.lookAt(focalPoint);
  14485. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14486. // Edges
  14487. /*
  14488. const edges = new EdgesGeometry(planeGeometry)
  14489. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14490. //plane
  14491. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14492. const mesh = new Mesh(planeGeometry, material);
  14493. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14494. group.add(arrowHelper);
  14495. group.add(mesh);
  14496. return group;
  14497. }
  14498. function loadersBoundingBoxToMesh(tile) {
  14499. // Create a basic rectangle geometry from math.gl half-axes
  14500. const { boundingVolume } = tile;
  14501. let redColor = 0;
  14502. if (tile.content) {
  14503. redColor = Math.min(tile.content.byteLength / 500000, 1.0);
  14504. }
  14505. const boxColor = new Color(redColor, 1.0, 0.0);
  14506. const boxGeometry = new BoxGeometry(1, 1, 1);
  14507. const boxTransform = new Matrix4$1();
  14508. if (boundingVolume.halfAxes) {
  14509. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  14510. }
  14511. else if (boundingVolume.radius) {
  14512. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  14513. }
  14514. boxGeometry.applyMatrix4(boxTransform);
  14515. const edges = new EdgesGeometry(boxGeometry);
  14516. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor }));
  14517. dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14518. return dispPlane;
  14519. }
  14520. function getMatrix4FromHalfAxes(halfAxes) {
  14521. const m = halfAxes;
  14522. const rotateMatrix = new Matrix4$1().fromArray([
  14523. m[0] * 2,
  14524. m[1] * 2,
  14525. m[2] * 2,
  14526. 0,
  14527. m[3] * 2,
  14528. m[4] * 2,
  14529. m[5] * 2,
  14530. 0,
  14531. m[6] * 2,
  14532. m[7] * 2,
  14533. m[8] * 2,
  14534. 0,
  14535. 0,
  14536. 0,
  14537. 0,
  14538. 1,
  14539. ]);
  14540. return rotateMatrix;
  14541. }
  14542. /*
  14543. * from https://github.com/tentone/geo-three
  14544. * Tree-shaking did not work, probably due to static class methods
  14545. */
  14546. function datumsToSpherical(latitude, longitude) {
  14547. const EARTH_RADIUS = 6378137;
  14548. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14549. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14550. const x = longitude * EARTH_ORIGIN / 180.0;
  14551. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14552. y = y * EARTH_ORIGIN / 180.0;
  14553. return new Vector2$1(x, y);
  14554. }
  14555. const Gradients = {
  14556. // From chroma spectral http://gka.github.io/chroma.js/
  14557. SPECTRAL: [
  14558. [0, new Color(0.3686, 0.3098, 0.6353)],
  14559. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14560. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14561. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14562. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14563. [0.5, new Color(1.0, 1.0, 0.749)],
  14564. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14565. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14566. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14567. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14568. [1, new Color(0.6196, 0.0039, 0.2588)],
  14569. ],
  14570. PLASMA: [
  14571. [0.0, new Color(0.241, 0.015, 0.61)],
  14572. [0.1, new Color(0.387, 0.001, 0.654)],
  14573. [0.2, new Color(0.524, 0.025, 0.653)],
  14574. [0.3, new Color(0.651, 0.125, 0.596)],
  14575. [0.4, new Color(0.752, 0.227, 0.513)],
  14576. [0.5, new Color(0.837, 0.329, 0.431)],
  14577. [0.6, new Color(0.907, 0.435, 0.353)],
  14578. [0.7, new Color(0.963, 0.554, 0.272)],
  14579. [0.8, new Color(0.992, 0.681, 0.195)],
  14580. [0.9, new Color(0.987, 0.822, 0.144)],
  14581. [1.0, new Color(0.94, 0.975, 0.131)],
  14582. ],
  14583. YELLOW_GREEN: [
  14584. [0, new Color(0.1647, 0.2824, 0.3451)],
  14585. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14586. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14587. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14588. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14589. [0.5, new Color(0.137, 0.665, 0.5614)],
  14590. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14591. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14592. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14593. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14594. [1, new Color(0.9804, 0.9804, 0.4314)],
  14595. ],
  14596. VIRIDIS: [
  14597. [0.0, new Color(0.267, 0.005, 0.329)],
  14598. [0.1, new Color(0.283, 0.141, 0.458)],
  14599. [0.2, new Color(0.254, 0.265, 0.53)],
  14600. [0.3, new Color(0.207, 0.372, 0.553)],
  14601. [0.4, new Color(0.164, 0.471, 0.558)],
  14602. [0.5, new Color(0.128, 0.567, 0.551)],
  14603. [0.6, new Color(0.135, 0.659, 0.518)],
  14604. [0.7, new Color(0.267, 0.749, 0.441)],
  14605. [0.8, new Color(0.478, 0.821, 0.318)],
  14606. [0.9, new Color(0.741, 0.873, 0.15)],
  14607. [1.0, new Color(0.993, 0.906, 0.144)],
  14608. ],
  14609. INFERNO: [
  14610. [0.0, new Color(0.077, 0.042, 0.206)],
  14611. [0.1, new Color(0.225, 0.036, 0.388)],
  14612. [0.2, new Color(0.373, 0.074, 0.432)],
  14613. [0.3, new Color(0.522, 0.128, 0.42)],
  14614. [0.4, new Color(0.665, 0.182, 0.37)],
  14615. [0.5, new Color(0.797, 0.255, 0.287)],
  14616. [0.6, new Color(0.902, 0.364, 0.184)],
  14617. [0.7, new Color(0.969, 0.516, 0.063)],
  14618. [0.8, new Color(0.988, 0.683, 0.072)],
  14619. [0.9, new Color(0.961, 0.859, 0.298)],
  14620. [1.0, new Color(0.988, 0.998, 0.645)],
  14621. ],
  14622. GRAYSCALE: [
  14623. [0, new Color(0, 0, 0)],
  14624. [1, new Color(1, 1, 1)],
  14625. ],
  14626. // 16 samples of the TURBU color scheme
  14627. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14628. // original file licensed under Apache-2.0
  14629. TURBO: [
  14630. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14631. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14632. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14633. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14634. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14635. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14636. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14637. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14638. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14639. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14640. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14641. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14642. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14643. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14644. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14645. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14646. ],
  14647. RAINBOW: [
  14648. [0, new Color(0.278, 0, 0.714)],
  14649. [1 / 6, new Color(0, 0, 1)],
  14650. [2 / 6, new Color(0, 1, 1)],
  14651. [3 / 6, new Color(0, 1, 0)],
  14652. [4 / 6, new Color(1, 1, 0)],
  14653. [5 / 6, new Color(1, 0.64, 0)],
  14654. [1, new Color(1, 0, 0)],
  14655. ],
  14656. CONTOUR: [
  14657. [0.0, new Color(0, 0, 0)],
  14658. [0.03, new Color(0, 0, 0)],
  14659. [0.04, new Color(1, 1, 1)],
  14660. [1.0, new Color(1, 1, 1)],
  14661. ],
  14662. };
  14663. const PointCloudFS = `
  14664. varying vec3 vColor;
  14665. uniform float alpha;
  14666. void main() {
  14667. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14668. discard;
  14669. } else {
  14670. gl_FragColor = vec4( vColor, alpha);
  14671. }
  14672. }
  14673. `;
  14674. const PointCloudVS = `
  14675. varying vec3 vColor;
  14676. uniform sampler2D gradient;
  14677. uniform sampler2D grayscale;
  14678. attribute float intensity;
  14679. attribute float classification;
  14680. uniform vec3 rootCenter;
  14681. uniform vec3 rootNormal;
  14682. uniform vec2 elevationRange;
  14683. uniform int coloring;
  14684. uniform bool hideGround;
  14685. uniform float maxIntensity;
  14686. uniform float intensityContrast;
  14687. uniform float pointSize;
  14688. #ifdef USE_COLOR
  14689. vec3 getRGB() {
  14690. vec3 rgb = color;
  14691. return rgb;
  14692. }
  14693. #endif
  14694. vec3 getElevation(){
  14695. vec4 world = modelMatrix * vec4( position, 1.0 );
  14696. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14697. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14698. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14699. return cElevation;
  14700. }
  14701. vec3 getIntensity(){
  14702. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14703. float intmod = pow(intensity, intensityContrast);
  14704. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14705. return cIntensity;
  14706. }
  14707. vec3 getClassification(){
  14708. float classNormalized = classification / 255.0;
  14709. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14710. return cClassification;
  14711. }
  14712. vec3 getColor(){
  14713. vec3 color;
  14714. if (hideGround && classification == 2.0) {
  14715. return vec3(0.0, 0.0, 0.0);
  14716. }
  14717. if (coloring == 1) {
  14718. color = getIntensity();
  14719. }
  14720. else if (coloring == 2) {
  14721. color = getClassification();
  14722. } else if (coloring == 3) {
  14723. color = getElevation();
  14724. }
  14725. #ifdef USE_COLOR
  14726. else if (coloring == 4) {
  14727. color = getRGB();
  14728. }
  14729. #endif
  14730. else {
  14731. color = vec3(1.0, 1.0, 1.0);
  14732. }
  14733. return color;
  14734. }
  14735. void main() {
  14736. vColor = getColor();
  14737. gl_PointSize = pointSize;
  14738. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14739. }
  14740. `;
  14741. /** Types of coloring used when viewing point cloud tiles */
  14742. var PointCloudColoring;
  14743. (function (PointCloudColoring) {
  14744. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14745. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14746. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14747. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14748. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14749. })(PointCloudColoring || (PointCloudColoring = {}));
  14750. /** Types of shading used when viewing b3dm (mesh) tiles */
  14751. var Shading;
  14752. (function (Shading) {
  14753. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14754. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14755. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14756. })(Shading || (Shading = {}));
  14757. var GeoTransform;
  14758. (function (GeoTransform) {
  14759. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14760. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14761. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14762. })(GeoTransform || (GeoTransform = {}));
  14763. const gradient = Gradients.RAINBOW;
  14764. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14765. const grayscale = Gradients.GRAYSCALE;
  14766. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14767. const defaultOptions = {
  14768. throttleRequests: true,
  14769. maxRequests: 64,
  14770. updateInterval: 0.1,
  14771. maxConcurrency: 1,
  14772. maximumScreenSpaceError: 16,
  14773. maximumMemoryUsage: 32,
  14774. viewDistanceScale: 1.0,
  14775. skipLevelOfDetail: false,
  14776. updateTransforms: true,
  14777. shading: Shading.FlatTexture,
  14778. transparent: false,
  14779. pointCloudColoring: PointCloudColoring.White,
  14780. pointSize: 1.0,
  14781. worker: true,
  14782. wireframe: false,
  14783. debug: false,
  14784. basisTranscoderPath: null,
  14785. dracoDecoderPath: null,
  14786. material: null,
  14787. computeNormals: false,
  14788. shaderCallback: null,
  14789. geoTransform: GeoTransform.Reset,
  14790. preloadTilesCount: null
  14791. };
  14792. /** 3D Tiles Loader */
  14793. class Loader3DTiles {
  14794. /**
  14795. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14796. * @public
  14797. *
  14798. * @param props - Properties for this load call {@link LoaderProps}.
  14799. * @returns An object containing the 3D Model to be added to the scene
  14800. * and a runtime engine to be updated every frame.
  14801. */
  14802. static load(props) {
  14803. return __awaiter(this, void 0, void 0, function* () {
  14804. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14805. const { url } = props;
  14806. const UPDATE_INTERVAL = options.updateInterval;
  14807. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14808. const loadersGLOptions = {};
  14809. if (options.cesiumIONToken) {
  14810. loadersGLOptions['cesium-ion'] = {
  14811. accessToken: options.cesiumIONToken,
  14812. };
  14813. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14814. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14815. }
  14816. if (props.loadingManager) {
  14817. props.loadingManager.itemStart(url);
  14818. }
  14819. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14820. const renderMap = {};
  14821. const boxMap = {};
  14822. const unloadQueue = [];
  14823. const root = new Group();
  14824. const tileBoxes = new Group();
  14825. if (!options.debug) {
  14826. tileBoxes.visible = false;
  14827. }
  14828. const pointcloudUniforms = {
  14829. pointSize: { type: 'f', value: options.pointSize },
  14830. gradient: { type: 't', value: gradientTexture },
  14831. grayscale: { type: 't', value: grayscaleTexture },
  14832. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14833. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14834. coloring: { type: 'i', value: options.pointCloudColoring },
  14835. hideGround: { type: 'b', value: true },
  14836. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14837. maxIntensity: { type: 'f', value: 1.0 },
  14838. intensityContrast: { type: 'f', value: 1.0 },
  14839. alpha: { type: 'f', value: 1.0 },
  14840. };
  14841. const pointcloudMaterial = new ShaderMaterial({
  14842. uniforms: pointcloudUniforms,
  14843. vertexShader: PointCloudVS,
  14844. fragmentShader: PointCloudFS,
  14845. transparent: options.transparent,
  14846. vertexColors: true
  14847. });
  14848. let cameraReference = null;
  14849. let rendererReference = null;
  14850. const gltfLoader = new GLTFLoader$1();
  14851. let ktx2Loader = undefined;
  14852. let dracoLoader = undefined;
  14853. if (options.basisTranscoderPath) {
  14854. ktx2Loader = new KTX2Loader();
  14855. ktx2Loader.detectSupport(props.renderer);
  14856. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14857. ktx2Loader.setWorkerLimit(1);
  14858. gltfLoader.setKTX2Loader(ktx2Loader);
  14859. }
  14860. if (options.dracoDecoderPath) {
  14861. dracoLoader = new DRACOLoader();
  14862. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14863. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14864. gltfLoader.setDRACOLoader(dracoLoader);
  14865. }
  14866. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14867. const tileOptions = {
  14868. maximumMemoryUsage: options.maximumMemoryUsage,
  14869. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14870. viewDistanceScale: options.viewDistanceScale,
  14871. skipLevelOfDetail: options.skipLevelOfDetail,
  14872. updateTransforms: options.updateTransforms,
  14873. throttleRequests: options.throttleRequests,
  14874. maxRequests: options.maxRequests,
  14875. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14876. let tileContent = null;
  14877. switch (tile.type) {
  14878. case TILE_TYPE.POINTCLOUD: {
  14879. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14880. break;
  14881. }
  14882. case TILE_TYPE.SCENEGRAPH:
  14883. case TILE_TYPE.MESH: {
  14884. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14885. break;
  14886. }
  14887. }
  14888. if (tileContent) {
  14889. tileContent.visible = false;
  14890. renderMap[tile.id] = tileContent;
  14891. root.add(renderMap[tile.id]);
  14892. if (options.debug) {
  14893. const box = loadersBoundingBoxToMesh(tile);
  14894. tileBoxes.add(box);
  14895. boxMap[tile.id] = box;
  14896. }
  14897. }
  14898. }),
  14899. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14900. if (tileset) {
  14901. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14902. detectOrientation(tile);
  14903. }
  14904. tileset._frameNumber++;
  14905. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14906. }
  14907. }),
  14908. onTileUnload: (tile) => {
  14909. unloadQueue.push(tile);
  14910. },
  14911. onTileError: (tile, message) => {
  14912. console.error('Tile error', tile.id, message);
  14913. },
  14914. };
  14915. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14916. loadImages: false,
  14917. }, '3d-tiles': {
  14918. loadGLTF: false
  14919. } }) }));
  14920. //
  14921. // transformations
  14922. const threeMat = new Matrix4$1();
  14923. const tileTrasnform = new Matrix4$1();
  14924. const rootCenter = new Vector3$1();
  14925. let orientationDetected = false;
  14926. if (tileset.root.boundingVolume) {
  14927. if (tileset.root.header.boundingVolume.region) {
  14928. // TODO: Handle region type bounding volumes
  14929. // https://github.com/visgl/loaders.gl/issues/1994
  14930. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14931. options.geoTransform = GeoTransform.WGS84Cartesian;
  14932. }
  14933. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14934. }
  14935. else {
  14936. console.warn("Bounding volume not found, no transformations applied");
  14937. }
  14938. if (options.debug) {
  14939. const box = loadersBoundingBoxToMesh(tileset.root);
  14940. tileBoxes.add(box);
  14941. boxMap[tileset.root.id] = box;
  14942. }
  14943. let disposeFlag = false;
  14944. let loadingEnded = false;
  14945. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14946. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14947. // Extra stats
  14948. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14949. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14950. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14951. let timer = 0;
  14952. let lastCameraTransform = null;
  14953. let lastCameraAspect = null;
  14954. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14955. let sseDenominator = null;
  14956. root.updateMatrixWorld(true);
  14957. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14958. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14959. detectOrientation(tileset.root);
  14960. updateResetTransform();
  14961. if (options.debug) {
  14962. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14963. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14964. }
  14965. if (options.geoTransform == GeoTransform.Mercator) {
  14966. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14967. rootCenter.set(coords.x, 0, -coords.y);
  14968. root.position.copy(rootCenter);
  14969. root.rotation.set(-Math.PI / 2, 0, 0);
  14970. root.updateMatrixWorld(true);
  14971. }
  14972. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14973. root.applyMatrix4(tileTrasnform);
  14974. root.updateMatrixWorld(true);
  14975. rootCenter.copy(root.position);
  14976. }
  14977. function detectOrientation(tile) {
  14978. if (!tile.boundingVolume.halfAxes) {
  14979. return;
  14980. }
  14981. const halfAxes = tile.boundingVolume.halfAxes;
  14982. const orientationMatrix = new Matrix4$1()
  14983. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14984. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14985. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14986. if (!rotation.equals(new Euler())) {
  14987. orientationDetected = true;
  14988. const pos = new Vector3$1(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  14989. tileTrasnform.extractRotation(orientationMatrix);
  14990. tileTrasnform.setPosition(pos);
  14991. updateResetTransform();
  14992. }
  14993. }
  14994. function updateResetTransform() {
  14995. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14996. // Reset the current model matrix and apply our own transformation
  14997. threeMat.copy(tileTrasnform).invert();
  14998. threeMat.premultiply(lastRootTransform);
  14999. threeMat.copy(lastRootTransform).multiply(new Matrix4$1().copy(tileTrasnform).invert());
  15000. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  15001. }
  15002. }
  15003. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  15004. if (disposeFlag) {
  15005. return;
  15006. }
  15007. // Assumes camera fov, near and far are not changing
  15008. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  15009. const loadersFrustum = new PerspectiveFrustum({
  15010. fov: (camera.fov / 180) * Math.PI,
  15011. aspectRatio: camera.aspect,
  15012. near: camera.near,
  15013. far: camera.far,
  15014. });
  15015. sseDenominator = loadersFrustum.sseDenominator;
  15016. lastCameraAspect = camera.aspect;
  15017. if (options.debug) {
  15018. console.log('Updated sse denonimator:', sseDenominator);
  15019. }
  15020. }
  15021. const frustum = getCameraFrustum(camera);
  15022. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  15023. const cullingVolume = new CullingVolume(planes);
  15024. const rendererSize = new Vector2$1();
  15025. renderer.getSize(rendererSize);
  15026. const frameState = {
  15027. camera: {
  15028. position: lastCameraPosition.toArray(),
  15029. },
  15030. height: rendererSize.y,
  15031. frameNumber: tileset._frameNumber,
  15032. sseDenominator: sseDenominator,
  15033. cullingVolume: cullingVolume,
  15034. viewport: {
  15035. id: 0,
  15036. },
  15037. };
  15038. tileset._cache.reset();
  15039. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  15040. for (const tile of tileset.tiles) {
  15041. if (tile.selected) {
  15042. if (!renderMap[tile.id]) {
  15043. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  15044. }
  15045. else {
  15046. // Make sure it's visible
  15047. renderMap[tile.id].visible = true;
  15048. }
  15049. }
  15050. else {
  15051. if (renderMap[tile.id]) {
  15052. renderMap[tile.id].visible = false;
  15053. }
  15054. }
  15055. }
  15056. while (unloadQueue.length > 0) {
  15057. const tile = unloadQueue.pop();
  15058. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  15059. root.remove(renderMap[tile.id]);
  15060. disposeNode(renderMap[tile.id]);
  15061. delete renderMap[tile.id];
  15062. }
  15063. if (boxMap[tile.id]) {
  15064. disposeNode(boxMap[tile.id]);
  15065. tileBoxes.remove(boxMap[tile.id]);
  15066. delete boxMap[tile.id];
  15067. }
  15068. }
  15069. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  15070. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  15071. if (props.onProgress) {
  15072. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  15073. }
  15074. if (props.loadingManager && !loadingEnded) {
  15075. if (tilesLoading == 0 &&
  15076. (options.preloadTilesCount == null ||
  15077. tilesLoaded >= options.preloadTilesCount)) {
  15078. loadingEnded = true;
  15079. props.loadingManager.itemEnd(props.url);
  15080. }
  15081. }
  15082. return frameState;
  15083. }
  15084. return {
  15085. model: root,
  15086. runtime: {
  15087. getTileset: () => {
  15088. return tileset;
  15089. },
  15090. getStats: () => {
  15091. return tileset.stats;
  15092. },
  15093. showTiles: (visible) => {
  15094. tileBoxes.visible = visible;
  15095. },
  15096. setWireframe: (wireframe) => {
  15097. options.wireframe = wireframe;
  15098. root.traverse((object) => {
  15099. if (object instanceof Mesh) {
  15100. object.material.wireframe = wireframe;
  15101. }
  15102. });
  15103. },
  15104. setDebug: (debug) => {
  15105. options.debug = debug;
  15106. tileBoxes.visible = debug;
  15107. },
  15108. setShading: (shading) => {
  15109. options.shading = shading;
  15110. },
  15111. getTileBoxes: () => {
  15112. return tileBoxes;
  15113. },
  15114. setViewDistanceScale: (scale) => {
  15115. tileset.options.viewDistanceScale = scale;
  15116. tileset._frameNumber++;
  15117. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  15118. },
  15119. setHideGround: (enabled) => {
  15120. pointcloudUniforms.hideGround.value = enabled;
  15121. },
  15122. setPointCloudColoring: (selection) => {
  15123. pointcloudUniforms.coloring.value = selection;
  15124. },
  15125. setElevationRange: (range) => {
  15126. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  15127. },
  15128. setMaxIntensity: (intensity) => {
  15129. pointcloudUniforms.maxIntensity.value = intensity;
  15130. },
  15131. setIntensityContrast: (contrast) => {
  15132. pointcloudUniforms.intensityContrast.value = contrast;
  15133. },
  15134. setPointAlpha: (alpha) => {
  15135. pointcloudUniforms.alpha.value = alpha;
  15136. },
  15137. getLatLongHeightFromPosition: (position) => {
  15138. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  15139. return {
  15140. lat: cartographicPosition[1],
  15141. long: cartographicPosition[0],
  15142. height: cartographicPosition[2],
  15143. };
  15144. },
  15145. getPositionFromLatLongHeight: (coord) => {
  15146. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  15147. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  15148. },
  15149. getCameraFrustum: (camera) => {
  15150. const frustum = getCameraFrustum(camera);
  15151. const meshes = frustum.planes
  15152. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  15153. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  15154. const model = new Group();
  15155. for (const mesh of meshes)
  15156. model.add(mesh);
  15157. return model;
  15158. },
  15159. update: function (dt, renderer, camera) {
  15160. cameraReference = camera;
  15161. rendererReference = renderer;
  15162. timer += dt;
  15163. if (tileset && timer >= UPDATE_INTERVAL) {
  15164. if (!lastRootTransform.equals(root.matrixWorld)) {
  15165. timer = 0;
  15166. lastRootTransform.copy(root.matrixWorld);
  15167. updateResetTransform();
  15168. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  15169. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  15170. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  15171. rootTransformInverse.copy(lastRootTransform).invert();
  15172. if (options.debug) {
  15173. boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  15174. boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  15175. }
  15176. }
  15177. if (lastCameraTransform == null) {
  15178. lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  15179. }
  15180. else {
  15181. const cameraChanged = !camera.matrixWorld.equals(lastCameraTransform) ||
  15182. !(camera.aspect == lastCameraAspect);
  15183. if (cameraChanged) {
  15184. timer = 0;
  15185. tileset._frameNumber++;
  15186. camera.getWorldPosition(lastCameraPosition);
  15187. lastCameraTransform.copy(camera.matrixWorld);
  15188. tilesetUpdate(tileset, renderMap, renderer, camera);
  15189. }
  15190. }
  15191. }
  15192. },
  15193. dispose: function () {
  15194. disposeFlag = true;
  15195. tileset._destroy();
  15196. while (root.children.length > 0) {
  15197. const obj = root.children[0];
  15198. disposeNode(obj);
  15199. root.remove(obj);
  15200. }
  15201. while (tileBoxes.children.length > 0) {
  15202. const obj = tileBoxes.children[0];
  15203. tileBoxes.remove(obj);
  15204. obj.geometry.dispose();
  15205. obj.material.dispose();
  15206. }
  15207. if (ktx2Loader) {
  15208. ktx2Loader.dispose();
  15209. }
  15210. if (dracoLoader) {
  15211. dracoLoader.dispose();
  15212. }
  15213. },
  15214. },
  15215. };
  15216. });
  15217. }
  15218. }
  15219. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  15220. return __awaiter(this, void 0, void 0, function* () {
  15221. return new Promise((resolve, reject) => {
  15222. var _a;
  15223. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  15224. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  15225. // The computed trasnform already contains the root's transform, so we have to invert it
  15226. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15227. if (shouldRotate) {
  15228. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  15229. }
  15230. gltfLoader.parse(tile.content.gltfArrayBuffer, tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '', (gltf) => {
  15231. const tileContent = gltf.scenes[0];
  15232. tileContent.applyMatrix4(contentTransform);
  15233. tileContent.traverse((object) => {
  15234. if (object.type == "Mesh") {
  15235. const mesh = object;
  15236. const originalMaterial = mesh.material;
  15237. const originalMap = originalMaterial.map;
  15238. if (options.material) {
  15239. mesh.material = options.material.clone();
  15240. originalMaterial.dispose();
  15241. }
  15242. else if (options.shading == Shading.FlatTexture) {
  15243. mesh.material = unlitMaterial.clone();
  15244. originalMaterial.dispose();
  15245. }
  15246. if (options.shading != Shading.ShadedNoTexture) {
  15247. if (mesh.material.type == "ShaderMaterial") {
  15248. mesh.material.uniforms.map = { value: originalMap };
  15249. }
  15250. else {
  15251. mesh.material.map = originalMap;
  15252. }
  15253. }
  15254. else {
  15255. if (originalMap) {
  15256. originalMap.dispose();
  15257. }
  15258. mesh.material.map = null;
  15259. }
  15260. if (options.shaderCallback) {
  15261. mesh.onBeforeRender = options.shaderCallback;
  15262. }
  15263. mesh.material.wireframe = options.wireframe;
  15264. if (options.computeNormals) {
  15265. mesh.geometry.computeVertexNormals();
  15266. }
  15267. }
  15268. });
  15269. resolve(tileContent);
  15270. }, (e) => {
  15271. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  15272. });
  15273. });
  15274. });
  15275. }
  15276. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  15277. const d = {
  15278. rtc_center: tile.content.rtcCenter,
  15279. points: tile.content.attributes.positions,
  15280. intensities: tile.content.attributes.intensity,
  15281. classifications: tile.content.attributes.classification,
  15282. rgb: null,
  15283. rgba: null,
  15284. };
  15285. const { colors } = tile.content.attributes;
  15286. if (colors && colors.size === 3) {
  15287. d.rgb = colors.value;
  15288. }
  15289. if (colors && colors.size === 4) {
  15290. d.rgba = colors.value;
  15291. }
  15292. const geometry = new BufferGeometry();
  15293. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  15294. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15295. if (d.rgba) {
  15296. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  15297. }
  15298. else if (d.rgb) {
  15299. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  15300. }
  15301. if (d.intensities) {
  15302. geometry.setAttribute('intensity',
  15303. // Handles both 16bit or 8bit intensity values
  15304. new BufferAttribute(d.intensities, 1, true));
  15305. }
  15306. if (d.classifications) {
  15307. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  15308. }
  15309. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  15310. if (d.rtc_center) {
  15311. const c = d.rtc_center;
  15312. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  15313. }
  15314. tileContent.applyMatrix4(contentTransform);
  15315. return tileContent;
  15316. }
  15317. function disposeMaterial(material) {
  15318. var _a, _b, _c, _d;
  15319. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  15320. (_c = (_b = material === null || material === void 0 ? void 0 : material.uniforms) === null || _b === void 0 ? void 0 : _b.map.value) === null || _c === void 0 ? void 0 : _c.dispose();
  15321. }
  15322. else if (material.map) {
  15323. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  15324. }
  15325. material.dispose();
  15326. }
  15327. function disposeNode(node) {
  15328. node.traverse((object) => {
  15329. if (object.isMesh) {
  15330. object.geometry.dispose();
  15331. if (object.material.isMaterial) {
  15332. disposeMaterial(object.material);
  15333. }
  15334. else {
  15335. // an array of materials
  15336. for (const material of object.material) {
  15337. disposeMaterial(material);
  15338. }
  15339. }
  15340. }
  15341. });
  15342. for (let i = node.children.length - 1; i >= 0; i--) {
  15343. const obj = node.children[i];
  15344. node.remove(obj);
  15345. }
  15346. }
  15347. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  15348. //# sourceMappingURL=three-loader-3dtiles.esm.js.map