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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939
  1. import { EventDispatcher, CanvasTexture, LinearFilter, RepeatWrapping, Vector2 as Vector2$1, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1/*, MeshBasicMaterial */, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from '../build/three.module.js';
  2. import { GLTFLoader as GLTFLoader$1 } from '../loaders/GLTFLoader.js';
  3. import { DRACOLoader } from '../loaders/DRACOLoader.js';
  4. import { KTX2Loader } from '../loaders/KTX2Loader.js';
  5. import MeshBasicMaterial from '../../../src/custom/materials/BasicMaterial.js' // xzw改 原先MeshBasicMaterial贴图发黑,可能和贴图有关
  6. let globalThis = window //add 有的app没有globalThis. 2023.1
  7. /*! *****************************************************************************
  8. Copyright (c) Microsoft Corporation.
  9. Permission to use, copy, modify, and/or distribute this software for any
  10. purpose with or without fee is hereby granted.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  12. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  13. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  14. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  15. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  16. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  17. PERFORMANCE OF THIS SOFTWARE.
  18. ***************************************************************************** */
  19. window.visiVertexCount = 0
  20. window.visiGeoCount = 0
  21. const maxVertexVisi = 5e6
  22. const maxTexVisi = 500
  23. function __awaiter(thisArg, _arguments, P, generator) {
  24. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  25. return new (P || (P = Promise))(function (resolve, reject) {
  26. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  27. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  28. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  29. step((generator = generator.apply(thisArg, _arguments || [])).next());
  30. });
  31. }
  32. function assert$7(condition, message) {
  33. if (!condition) {
  34. throw new Error(message || 'loader assertion failed.');
  35. }
  36. }
  37. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  38. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  39. matches$1 && parseFloat(matches$1[1]) || 0;
  40. const VERSION$8 = "3.1.4" ;
  41. function assert$6(condition, message) {
  42. if (!condition) {
  43. throw new Error(message || 'loaders.gl assertion failed.');
  44. }
  45. }
  46. const globals$1 = {
  47. self: typeof self !== 'undefined' && self,
  48. window: typeof window !== 'undefined' && window,
  49. global: typeof global !== 'undefined' && global,
  50. document: typeof document !== 'undefined' && document
  51. };
  52. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  53. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  54. const isWorker = typeof importScripts === 'function';
  55. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  56. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  57. matches && parseFloat(matches[1]) || 0;
  58. function _defineProperty(obj, key, value) {
  59. if (key in obj) {
  60. Object.defineProperty(obj, key, {
  61. value: value,
  62. enumerable: true,
  63. configurable: true,
  64. writable: true
  65. });
  66. } else {
  67. obj[key] = value;
  68. }
  69. return obj;
  70. }
  71. class WorkerJob {
  72. constructor(jobName, workerThread) {
  73. _defineProperty(this, "name", void 0);
  74. _defineProperty(this, "workerThread", void 0);
  75. _defineProperty(this, "isRunning", void 0);
  76. _defineProperty(this, "result", void 0);
  77. _defineProperty(this, "_resolve", void 0);
  78. _defineProperty(this, "_reject", void 0);
  79. this.name = jobName;
  80. this.workerThread = workerThread;
  81. this.isRunning = true;
  82. this._resolve = () => {};
  83. this._reject = () => {};
  84. this.result = new Promise((resolve, reject) => {
  85. this._resolve = resolve;
  86. this._reject = reject;
  87. });
  88. }
  89. postMessage(type, payload) {
  90. this.workerThread.postMessage({
  91. source: 'loaders.gl',
  92. type,
  93. payload
  94. });
  95. }
  96. done(value) {
  97. assert$6(this.isRunning);
  98. this.isRunning = false;
  99. this._resolve(value);
  100. }
  101. error(error) {
  102. assert$6(this.isRunning);
  103. this.isRunning = false;
  104. this._reject(error);
  105. }
  106. }
  107. const workerURLCache = new Map();
  108. function getLoadableWorkerURL(props) {
  109. assert$6(props.source && !props.url || !props.source && props.url);
  110. let workerURL = workerURLCache.get(props.source || props.url);
  111. if (!workerURL) {
  112. if (props.url) {
  113. workerURL = getLoadableWorkerURLFromURL(props.url);
  114. workerURLCache.set(props.url, workerURL);
  115. }
  116. if (props.source) {
  117. workerURL = getLoadableWorkerURLFromSource(props.source);
  118. workerURLCache.set(props.source, workerURL);
  119. }
  120. }
  121. assert$6(workerURL);
  122. return workerURL;
  123. }
  124. function getLoadableWorkerURLFromURL(url) {
  125. if (!url.startsWith('http')) {
  126. return url;
  127. }
  128. const workerSource = buildScriptSource(url);
  129. return getLoadableWorkerURLFromSource(workerSource);
  130. }
  131. function getLoadableWorkerURLFromSource(workerSource) {
  132. const blob = new Blob([workerSource], {
  133. type: 'application/javascript'
  134. });
  135. return URL.createObjectURL(blob);
  136. }
  137. function buildScriptSource(workerUrl) {
  138. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  139. }
  140. function getTransferList(object, recursive = true, transfers) {
  141. const transfersSet = transfers || new Set();
  142. if (!object) ; else if (isTransferable(object)) {
  143. transfersSet.add(object);
  144. } else if (isTransferable(object.buffer)) {
  145. transfersSet.add(object.buffer);
  146. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  147. for (const key in object) {
  148. getTransferList(object[key], recursive, transfersSet);
  149. }
  150. }
  151. return transfers === undefined ? Array.from(transfersSet) : [];
  152. }
  153. function isTransferable(object) {
  154. if (!object) {
  155. return false;
  156. }
  157. if (object instanceof ArrayBuffer) {
  158. return true;
  159. }
  160. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  161. return true;
  162. }
  163. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  164. return true;
  165. }
  166. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  167. return true;
  168. }
  169. return false;
  170. }
  171. const NOOP = () => {};
  172. class WorkerThread {
  173. static isSupported() {
  174. return typeof Worker !== 'undefined';
  175. }
  176. constructor(props) {
  177. _defineProperty(this, "name", void 0);
  178. _defineProperty(this, "source", void 0);
  179. _defineProperty(this, "url", void 0);
  180. _defineProperty(this, "terminated", false);
  181. _defineProperty(this, "worker", void 0);
  182. _defineProperty(this, "onMessage", void 0);
  183. _defineProperty(this, "onError", void 0);
  184. _defineProperty(this, "_loadableURL", '');
  185. const {
  186. name,
  187. source,
  188. url
  189. } = props;
  190. assert$6(source || url);
  191. this.name = name;
  192. this.source = source;
  193. this.url = url;
  194. this.onMessage = NOOP;
  195. this.onError = error => console.log(error);
  196. this.worker = this._createBrowserWorker();
  197. }
  198. destroy() {
  199. this.onMessage = NOOP;
  200. this.onError = NOOP;
  201. this.worker.terminate();
  202. this.terminated = true;
  203. }
  204. get isRunning() {
  205. return Boolean(this.onMessage);
  206. }
  207. postMessage(data, transferList) {
  208. transferList = transferList || getTransferList(data);
  209. this.worker.postMessage(data, transferList);
  210. }
  211. _getErrorFromErrorEvent(event) {
  212. let message = 'Failed to load ';
  213. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  214. if (event.message) {
  215. message += "".concat(event.message, " in ");
  216. }
  217. if (event.lineno) {
  218. message += ":".concat(event.lineno, ":").concat(event.colno);
  219. }
  220. return new Error(message);
  221. }
  222. _createBrowserWorker() {
  223. this._loadableURL = getLoadableWorkerURL({
  224. source: this.source,
  225. url: this.url
  226. });
  227. const worker = new Worker(this._loadableURL, {
  228. name: this.name
  229. });
  230. worker.onmessage = event => {
  231. if (!event.data) {
  232. this.onError(new Error('No data received'));
  233. } else {
  234. this.onMessage(event.data);
  235. }
  236. };
  237. worker.onerror = error => {
  238. this.onError(this._getErrorFromErrorEvent(error));
  239. this.terminated = true;
  240. };
  241. worker.onmessageerror = event => console.error(event);
  242. return worker;
  243. }
  244. }
  245. class WorkerPool {
  246. constructor(props) {
  247. _defineProperty(this, "name", 'unnamed');
  248. _defineProperty(this, "source", void 0);
  249. _defineProperty(this, "url", void 0);
  250. _defineProperty(this, "maxConcurrency", 1);
  251. _defineProperty(this, "maxMobileConcurrency", 1);
  252. _defineProperty(this, "onDebug", () => {});
  253. _defineProperty(this, "reuseWorkers", true);
  254. _defineProperty(this, "props", {});
  255. _defineProperty(this, "jobQueue", []);
  256. _defineProperty(this, "idleQueue", []);
  257. _defineProperty(this, "count", 0);
  258. _defineProperty(this, "isDestroyed", false);
  259. this.source = props.source;
  260. this.url = props.url;
  261. this.setProps(props);
  262. }
  263. destroy() {
  264. this.idleQueue.forEach(worker => worker.destroy());
  265. this.isDestroyed = true;
  266. }
  267. setProps(props) {
  268. this.props = { ...this.props,
  269. ...props
  270. };
  271. if (props.name !== undefined) {
  272. this.name = props.name;
  273. }
  274. if (props.maxConcurrency !== undefined) {
  275. this.maxConcurrency = props.maxConcurrency;
  276. }
  277. if (props.maxMobileConcurrency !== undefined) {
  278. this.maxMobileConcurrency = props.maxMobileConcurrency;
  279. }
  280. if (props.reuseWorkers !== undefined) {
  281. this.reuseWorkers = props.reuseWorkers;
  282. }
  283. if (props.onDebug !== undefined) {
  284. this.onDebug = props.onDebug;
  285. }
  286. }
  287. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  288. const startPromise = new Promise(onStart => {
  289. this.jobQueue.push({
  290. name,
  291. onMessage,
  292. onError,
  293. onStart
  294. });
  295. return this;
  296. });
  297. this._startQueuedJob();
  298. return await startPromise;
  299. }
  300. async _startQueuedJob() {
  301. if (!this.jobQueue.length) {
  302. return;
  303. }
  304. const workerThread = this._getAvailableWorker();
  305. if (!workerThread) {
  306. return;
  307. }
  308. const queuedJob = this.jobQueue.shift();
  309. if (queuedJob) {
  310. this.onDebug({
  311. message: 'Starting job',
  312. name: queuedJob.name,
  313. workerThread,
  314. backlog: this.jobQueue.length
  315. });
  316. const job = new WorkerJob(queuedJob.name, workerThread);
  317. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  318. workerThread.onError = error => queuedJob.onError(job, error);
  319. queuedJob.onStart(job);
  320. try {
  321. await job.result;
  322. } finally {
  323. this.returnWorkerToQueue(workerThread);
  324. }
  325. }
  326. }
  327. returnWorkerToQueue(worker) {
  328. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  329. if (shouldDestroyWorker) {
  330. worker.destroy();
  331. this.count--;
  332. } else {
  333. this.idleQueue.push(worker);
  334. }
  335. if (!this.isDestroyed) {
  336. this._startQueuedJob();
  337. }
  338. }
  339. _getAvailableWorker() {
  340. if (this.idleQueue.length > 0) {
  341. return this.idleQueue.shift() || null;
  342. }
  343. if (this.count < this._getMaxConcurrency()) {
  344. this.count++;
  345. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  346. return new WorkerThread({
  347. name,
  348. source: this.source,
  349. url: this.url
  350. });
  351. }
  352. return null;
  353. }
  354. _getMaxConcurrency() {
  355. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  356. }
  357. }
  358. const DEFAULT_PROPS$3 = {
  359. maxConcurrency: 3,
  360. maxMobileConcurrency: 1,
  361. onDebug: () => {},
  362. reuseWorkers: true
  363. };
  364. class WorkerFarm {
  365. static isSupported() {
  366. return WorkerThread.isSupported();
  367. }
  368. static getWorkerFarm(props = {}) {
  369. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  370. WorkerFarm._workerFarm.setProps(props);
  371. return WorkerFarm._workerFarm;
  372. }
  373. constructor(props) {
  374. _defineProperty(this, "props", void 0);
  375. _defineProperty(this, "workerPools", new Map());
  376. this.props = { ...DEFAULT_PROPS$3
  377. };
  378. this.setProps(props);
  379. this.workerPools = new Map();
  380. }
  381. destroy() {
  382. for (const workerPool of this.workerPools.values()) {
  383. workerPool.destroy();
  384. }
  385. }
  386. setProps(props) {
  387. this.props = { ...this.props,
  388. ...props
  389. };
  390. for (const workerPool of this.workerPools.values()) {
  391. workerPool.setProps(this._getWorkerPoolProps());
  392. }
  393. }
  394. getWorkerPool(options) {
  395. const {
  396. name,
  397. source,
  398. url
  399. } = options;
  400. let workerPool = this.workerPools.get(name);
  401. if (!workerPool) {
  402. workerPool = new WorkerPool({
  403. name,
  404. source,
  405. url
  406. });
  407. workerPool.setProps(this._getWorkerPoolProps());
  408. this.workerPools.set(name, workerPool);
  409. }
  410. return workerPool;
  411. }
  412. _getWorkerPoolProps() {
  413. return {
  414. maxConcurrency: this.props.maxConcurrency,
  415. maxMobileConcurrency: this.props.maxMobileConcurrency,
  416. reuseWorkers: this.props.reuseWorkers,
  417. onDebug: this.props.onDebug
  418. };
  419. }
  420. }
  421. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  422. const NPM_TAG = 'latest';
  423. function getWorkerURL(worker, options = {}) {
  424. const workerOptions = options[worker.id] || {};
  425. const workerFile = "".concat(worker.id, "-worker.js");
  426. let url = workerOptions.workerUrl;
  427. if (!url && worker.id === 'compression') {
  428. url = options.workerUrl;
  429. }
  430. if (options._workerType === 'test') {
  431. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  432. }
  433. if (!url) {
  434. let version = worker.version;
  435. if (version === 'latest') {
  436. version = NPM_TAG;
  437. }
  438. const versionTag = version ? "@".concat(version) : '';
  439. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  440. }
  441. assert$6(url);
  442. return url;
  443. }
  444. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  445. assert$6(worker, 'no worker provided');
  446. const workerVersion = worker.version;
  447. if (!coreVersion || !workerVersion) {
  448. return false;
  449. }
  450. return true;
  451. }
  452. var ChildProcessProxy = {};
  453. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  454. 'default': ChildProcessProxy
  455. }));
  456. const VERSION$7 = "3.1.4" ;
  457. const loadLibraryPromises = {};
  458. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  459. if (moduleName) {
  460. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  461. }
  462. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  463. return await loadLibraryPromises[libraryUrl];
  464. }
  465. function getLibraryUrl(library, moduleName, options) {
  466. if (library.startsWith('http')) {
  467. return library;
  468. }
  469. const modules = options.modules || {};
  470. if (modules[library]) {
  471. return modules[library];
  472. }
  473. if (!isBrowser$1) {
  474. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  475. }
  476. if (options.CDN) {
  477. assert$6(options.CDN.startsWith('http'));
  478. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  479. }
  480. if (isWorker) {
  481. return "../src/libs/".concat(library);
  482. }
  483. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  484. }
  485. async function loadLibraryFromFile(libraryUrl) {
  486. if (libraryUrl.endsWith('wasm')) {
  487. const response = await fetch(libraryUrl);
  488. return await response.arrayBuffer();
  489. }
  490. if (!isBrowser$1) {
  491. try {
  492. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  493. } catch {
  494. return null;
  495. }
  496. }
  497. if (isWorker) {
  498. return importScripts(libraryUrl);
  499. }
  500. const response = await fetch(libraryUrl);
  501. const scriptSource = await response.text();
  502. return loadLibraryFromString(scriptSource, libraryUrl);
  503. }
  504. function loadLibraryFromString(scriptSource, id) {
  505. if (!isBrowser$1) {
  506. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  507. }
  508. if (isWorker) {
  509. eval.call(global_, scriptSource);
  510. return null;
  511. }
  512. const script = document.createElement('script');
  513. script.id = id;
  514. try {
  515. script.appendChild(document.createTextNode(scriptSource));
  516. } catch (e) {
  517. script.text = scriptSource;
  518. }
  519. document.body.appendChild(script);
  520. return null;
  521. }
  522. function canParseWithWorker(loader, options) {
  523. if (!WorkerFarm.isSupported()) {
  524. return false;
  525. }
  526. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  527. }
  528. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  529. const name = loader.id;
  530. const url = getWorkerURL(loader, options);
  531. const workerFarm = WorkerFarm.getWorkerFarm(options);
  532. const workerPool = workerFarm.getWorkerPool({
  533. name,
  534. url
  535. });
  536. options = JSON.parse(JSON.stringify(options));
  537. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  538. job.postMessage('process', {
  539. input: data,
  540. options
  541. });
  542. const result = await job.result;
  543. return await result.result;
  544. }
  545. async function onMessage(parseOnMainThread, job, type, payload) {
  546. switch (type) {
  547. case 'done':
  548. job.done(payload);
  549. break;
  550. case 'error':
  551. job.error(new Error(payload.error));
  552. break;
  553. case 'process':
  554. const {
  555. id,
  556. input,
  557. options
  558. } = payload;
  559. try {
  560. const result = await parseOnMainThread(input, options);
  561. job.postMessage('done', {
  562. id,
  563. result
  564. });
  565. } catch (error) {
  566. const message = error instanceof Error ? error.message : 'unknown error';
  567. job.postMessage('error', {
  568. id,
  569. error: message
  570. });
  571. }
  572. break;
  573. default:
  574. console.warn("parse-with-worker unknown message ".concat(type));
  575. }
  576. }
  577. function getFirstCharacters$1(data, length = 5) {
  578. if (typeof data === 'string') {
  579. return data.slice(0, length);
  580. } else if (ArrayBuffer.isView(data)) {
  581. return getMagicString$3(data.buffer, data.byteOffset, length);
  582. } else if (data instanceof ArrayBuffer) {
  583. const byteOffset = 0;
  584. return getMagicString$3(data, byteOffset, length);
  585. }
  586. return '';
  587. }
  588. function getMagicString$3(arrayBuffer, byteOffset, length) {
  589. if (arrayBuffer.byteLength <= byteOffset + length) {
  590. return '';
  591. }
  592. const dataView = new DataView(arrayBuffer);
  593. let magic = '';
  594. for (let i = 0; i < length; i++) {
  595. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  596. }
  597. return magic;
  598. }
  599. function parseJSON(string) {
  600. try {
  601. return JSON.parse(string);
  602. } catch (_) {
  603. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  604. }
  605. }
  606. function isBuffer$1(value) {
  607. return value && typeof value === 'object' && value.isBuffer;
  608. }
  609. function bufferToArrayBuffer(buffer) {
  610. if (isBuffer$1(buffer)) {
  611. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  612. return typedArray.slice().buffer;
  613. }
  614. return buffer;
  615. }
  616. function toArrayBuffer(data) {
  617. if (isBuffer$1(data)) {
  618. return bufferToArrayBuffer(data);
  619. }
  620. if (data instanceof ArrayBuffer) {
  621. return data;
  622. }
  623. if (ArrayBuffer.isView(data)) {
  624. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  625. return data.buffer;
  626. }
  627. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  628. }
  629. if (typeof data === 'string') {
  630. const text = data;
  631. const uint8Array = new TextEncoder().encode(text);
  632. return uint8Array.buffer;
  633. }
  634. if (data && typeof data === 'object' && data._toArrayBuffer) {
  635. return data._toArrayBuffer();
  636. }
  637. throw new Error('toArrayBuffer');
  638. }
  639. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  640. byteLength = byteLength || arrayBuffer1.byteLength;
  641. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  642. return false;
  643. }
  644. const array1 = new Uint8Array(arrayBuffer1);
  645. const array2 = new Uint8Array(arrayBuffer2);
  646. for (let i = 0; i < array1.length; ++i) {
  647. if (array1[i] !== array2[i]) {
  648. return false;
  649. }
  650. }
  651. return true;
  652. }
  653. function concatenateArrayBuffers(...sources) {
  654. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  655. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  656. const result = new Uint8Array(byteLength);
  657. let offset = 0;
  658. for (const sourceArray of sourceArrays) {
  659. result.set(sourceArray, offset);
  660. offset += sourceArray.byteLength;
  661. }
  662. return result.buffer;
  663. }
  664. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  665. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  666. const arrayCopy = new Uint8Array(subArray);
  667. return arrayCopy.buffer;
  668. }
  669. function padToNBytes(byteLength, padding) {
  670. assert$7(byteLength >= 0);
  671. assert$7(padding > 0);
  672. return byteLength + (padding - 1) & ~(padding - 1);
  673. }
  674. function copyToArray(source, target, targetOffset) {
  675. let sourceArray;
  676. if (source instanceof ArrayBuffer) {
  677. sourceArray = new Uint8Array(source);
  678. } else {
  679. const srcByteOffset = source.byteOffset;
  680. const srcByteLength = source.byteLength;
  681. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  682. }
  683. target.set(sourceArray, targetOffset);
  684. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  685. }
  686. async function concatenateArrayBuffersAsync(asyncIterator) {
  687. const arrayBuffers = [];
  688. for await (const chunk of asyncIterator) {
  689. arrayBuffers.push(chunk);
  690. }
  691. return concatenateArrayBuffers(...arrayBuffers);
  692. }
  693. function getHiResTimestamp$1() {
  694. let timestamp;
  695. if (typeof window !== 'undefined' && window.performance) {
  696. timestamp = window.performance.now();
  697. } else if (typeof process !== 'undefined' && process.hrtime) {
  698. const timeParts = process.hrtime();
  699. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  700. } else {
  701. timestamp = Date.now();
  702. }
  703. return timestamp;
  704. }
  705. class Stat {
  706. constructor(name, type) {
  707. _defineProperty(this, "name", void 0);
  708. _defineProperty(this, "type", void 0);
  709. _defineProperty(this, "sampleSize", 1);
  710. _defineProperty(this, "time", void 0);
  711. _defineProperty(this, "count", void 0);
  712. _defineProperty(this, "samples", void 0);
  713. _defineProperty(this, "lastTiming", void 0);
  714. _defineProperty(this, "lastSampleTime", void 0);
  715. _defineProperty(this, "lastSampleCount", void 0);
  716. _defineProperty(this, "_count", 0);
  717. _defineProperty(this, "_time", 0);
  718. _defineProperty(this, "_samples", 0);
  719. _defineProperty(this, "_startTime", 0);
  720. _defineProperty(this, "_timerPending", false);
  721. this.name = name;
  722. this.type = type;
  723. this.reset();
  724. }
  725. setSampleSize(samples) {
  726. this.sampleSize = samples;
  727. return this;
  728. }
  729. incrementCount() {
  730. this.addCount(1);
  731. return this;
  732. }
  733. decrementCount() {
  734. this.subtractCount(1);
  735. return this;
  736. }
  737. addCount(value) {
  738. this._count += value;
  739. this._samples++;
  740. this._checkSampling();
  741. return this;
  742. }
  743. subtractCount(value) {
  744. this._count -= value;
  745. this._samples++;
  746. this._checkSampling();
  747. return this;
  748. }
  749. addTime(time) {
  750. this._time += time;
  751. this.lastTiming = time;
  752. this._samples++;
  753. this._checkSampling();
  754. return this;
  755. }
  756. timeStart() {
  757. this._startTime = getHiResTimestamp$1();
  758. this._timerPending = true;
  759. return this;
  760. }
  761. timeEnd() {
  762. if (!this._timerPending) {
  763. return this;
  764. }
  765. this.addTime(getHiResTimestamp$1() - this._startTime);
  766. this._timerPending = false;
  767. this._checkSampling();
  768. return this;
  769. }
  770. getSampleAverageCount() {
  771. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  772. }
  773. getSampleAverageTime() {
  774. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  775. }
  776. getSampleHz() {
  777. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  778. }
  779. getAverageCount() {
  780. return this.samples > 0 ? this.count / this.samples : 0;
  781. }
  782. getAverageTime() {
  783. return this.samples > 0 ? this.time / this.samples : 0;
  784. }
  785. getHz() {
  786. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  787. }
  788. reset() {
  789. this.time = 0;
  790. this.count = 0;
  791. this.samples = 0;
  792. this.lastTiming = 0;
  793. this.lastSampleTime = 0;
  794. this.lastSampleCount = 0;
  795. this._count = 0;
  796. this._time = 0;
  797. this._samples = 0;
  798. this._startTime = 0;
  799. this._timerPending = false;
  800. return this;
  801. }
  802. _checkSampling() {
  803. if (this._samples === this.sampleSize) {
  804. this.lastSampleTime = this._time;
  805. this.lastSampleCount = this._count;
  806. this.count += this._count;
  807. this.time += this._time;
  808. this.samples += this._samples;
  809. this._time = 0;
  810. this._count = 0;
  811. this._samples = 0;
  812. }
  813. }
  814. }
  815. class Stats {
  816. constructor(options) {
  817. _defineProperty(this, "id", void 0);
  818. _defineProperty(this, "stats", {});
  819. this.id = options.id;
  820. this.stats = {};
  821. this._initializeStats(options.stats);
  822. Object.seal(this);
  823. }
  824. get(name) {
  825. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  826. return this._getOrCreate({
  827. name,
  828. type
  829. });
  830. }
  831. get size() {
  832. return Object.keys(this.stats).length;
  833. }
  834. reset() {
  835. for (const key in this.stats) {
  836. this.stats[key].reset();
  837. }
  838. return this;
  839. }
  840. forEach(fn) {
  841. for (const key in this.stats) {
  842. fn(this.stats[key]);
  843. }
  844. }
  845. getTable() {
  846. const table = {};
  847. this.forEach(stat => {
  848. table[stat.name] = {
  849. time: stat.time || 0,
  850. count: stat.count || 0,
  851. average: stat.getAverageTime() || 0,
  852. hz: stat.getHz() || 0
  853. };
  854. });
  855. return table;
  856. }
  857. _initializeStats() {
  858. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  859. stats.forEach(stat => this._getOrCreate(stat));
  860. }
  861. _getOrCreate(stat) {
  862. if (!stat || !stat.name) {
  863. return null;
  864. }
  865. const {
  866. name,
  867. type
  868. } = stat;
  869. if (!this.stats[name]) {
  870. if (stat instanceof Stat) {
  871. this.stats[name] = stat;
  872. } else {
  873. this.stats[name] = new Stat(name, type);
  874. }
  875. }
  876. return this.stats[name];
  877. }
  878. }
  879. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  880. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  881. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  882. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  883. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  884. const DEFAULT_PROPS$2 = {
  885. id: 'request-scheduler',
  886. throttleRequests: true,
  887. maxRequests: 6
  888. };
  889. class RequestScheduler {
  890. constructor(props = {}) {
  891. _defineProperty(this, "props", void 0);
  892. _defineProperty(this, "stats", void 0);
  893. _defineProperty(this, "activeRequestCount", 0);
  894. _defineProperty(this, "requestQueue", []);
  895. _defineProperty(this, "requestMap", new Map());
  896. _defineProperty(this, "deferredUpdate", null);
  897. this.props = { ...DEFAULT_PROPS$2,
  898. ...props
  899. };
  900. this.stats = new Stats({
  901. id: this.props.id
  902. });
  903. this.stats.get(STAT_QUEUED_REQUESTS);
  904. this.stats.get(STAT_ACTIVE_REQUESTS);
  905. this.stats.get(STAT_CANCELLED_REQUESTS);
  906. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  907. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  908. }
  909. scheduleRequest(handle, getPriority = () => 0) {
  910. if (!this.props.throttleRequests) {
  911. return Promise.resolve({
  912. done: () => {}
  913. });
  914. }
  915. if (this.requestMap.has(handle)) {
  916. return this.requestMap.get(handle);
  917. }
  918. const request = {
  919. handle,
  920. priority: 0,
  921. getPriority
  922. };
  923. const promise = new Promise(resolve => {
  924. request.resolve = resolve;
  925. return request;
  926. });
  927. this.requestQueue.push(request);
  928. this.requestMap.set(handle, promise);
  929. this._issueNewRequests();
  930. return promise;
  931. }
  932. _issueRequest(request) {
  933. const {
  934. handle,
  935. resolve
  936. } = request;
  937. let isDone = false;
  938. const done = () => {
  939. if (!isDone) {
  940. isDone = true;
  941. this.requestMap.delete(handle);
  942. this.activeRequestCount--;
  943. this._issueNewRequests();
  944. }
  945. };
  946. this.activeRequestCount++;
  947. return resolve ? resolve({
  948. done
  949. }) : Promise.resolve({
  950. done
  951. });
  952. }
  953. _issueNewRequests() {
  954. if (!this.deferredUpdate) {
  955. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  956. }
  957. }
  958. _issueNewRequestsAsync() {
  959. this.deferredUpdate = null;
  960. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  961. if (freeSlots === 0) {
  962. return;
  963. }
  964. this._updateAllRequests();
  965. for (let i = 0; i < freeSlots; ++i) {
  966. const request = this.requestQueue.shift();
  967. if (request) {
  968. this._issueRequest(request);
  969. }
  970. }
  971. }
  972. _updateAllRequests() {
  973. const requestQueue = this.requestQueue;
  974. for (let i = 0; i < requestQueue.length; ++i) {
  975. const request = requestQueue[i];
  976. if (!this._updateRequest(request)) {
  977. requestQueue.splice(i, 1);
  978. this.requestMap.delete(request.handle);
  979. i--;
  980. }
  981. }
  982. requestQueue.sort((a, b) => a.priority - b.priority);
  983. }
  984. _updateRequest(request) {
  985. request.priority = request.getPriority(request.handle);
  986. if (request.priority < 0) {
  987. request.resolve(null);
  988. return false;
  989. }
  990. return true;
  991. }
  992. }
  993. let pathPrefix = '';
  994. const fileAliases = {};
  995. function resolvePath(filename) {
  996. for (const alias in fileAliases) {
  997. if (filename.startsWith(alias)) {
  998. const replacement = fileAliases[alias];
  999. filename = filename.replace(alias, replacement);
  1000. }
  1001. }
  1002. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1003. filename = "".concat(pathPrefix).concat(filename);
  1004. }
  1005. return filename;
  1006. }
  1007. function filename(url) {
  1008. const slashIndex = url && url.lastIndexOf('/');
  1009. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1010. }
  1011. function dirname(url) {
  1012. const slashIndex = url && url.lastIndexOf('/');
  1013. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1014. }
  1015. const isBoolean = x => typeof x === 'boolean';
  1016. const isFunction = x => typeof x === 'function';
  1017. const isObject = x => x !== null && typeof x === 'object';
  1018. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1019. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1020. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1021. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1022. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1023. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1024. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1025. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1026. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1027. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1028. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1029. function parseMIMEType(mimeString) {
  1030. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1031. if (matches) {
  1032. return matches[1];
  1033. }
  1034. return mimeString;
  1035. }
  1036. function parseMIMETypeFromURL(url) {
  1037. const matches = DATA_URL_PATTERN.exec(url);
  1038. if (matches) {
  1039. return matches[1];
  1040. }
  1041. return '';
  1042. }
  1043. const QUERY_STRING_PATTERN = /\?.*/;
  1044. function getResourceUrlAndType(resource) {
  1045. if (isResponse(resource)) {
  1046. const url = stripQueryString(resource.url || '');
  1047. const contentTypeHeader = resource.headers.get('content-type') || '';
  1048. return {
  1049. url,
  1050. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1051. };
  1052. }
  1053. if (isBlob(resource)) {
  1054. return {
  1055. url: stripQueryString(resource.name || ''),
  1056. type: resource.type || ''
  1057. };
  1058. }
  1059. if (typeof resource === 'string') {
  1060. return {
  1061. url: stripQueryString(resource),
  1062. type: parseMIMETypeFromURL(resource)
  1063. };
  1064. }
  1065. return {
  1066. url: '',
  1067. type: ''
  1068. };
  1069. }
  1070. function getResourceContentLength(resource) {
  1071. if (isResponse(resource)) {
  1072. return resource.headers['content-length'] || -1;
  1073. }
  1074. if (isBlob(resource)) {
  1075. return resource.size;
  1076. }
  1077. if (typeof resource === 'string') {
  1078. return resource.length;
  1079. }
  1080. if (resource instanceof ArrayBuffer) {
  1081. return resource.byteLength;
  1082. }
  1083. if (ArrayBuffer.isView(resource)) {
  1084. return resource.byteLength;
  1085. }
  1086. return -1;
  1087. }
  1088. function stripQueryString(url) {
  1089. return url.replace(QUERY_STRING_PATTERN, '');
  1090. }
  1091. async function makeResponse(resource) {
  1092. if (isResponse(resource)) {
  1093. return resource;
  1094. }
  1095. const headers = {};
  1096. const contentLength = getResourceContentLength(resource);
  1097. if (contentLength >= 0) {
  1098. headers['content-length'] = String(contentLength);
  1099. }
  1100. const {
  1101. url,
  1102. type
  1103. } = getResourceUrlAndType(resource);
  1104. if (type) {
  1105. headers['content-type'] = type;
  1106. }
  1107. const initialDataUrl = await getInitialDataUrl(resource);
  1108. if (initialDataUrl) {
  1109. headers['x-first-bytes'] = initialDataUrl;
  1110. }
  1111. if (typeof resource === 'string') {
  1112. resource = new TextEncoder().encode(resource);
  1113. }
  1114. const response = new Response(resource, {
  1115. headers
  1116. });
  1117. Object.defineProperty(response, 'url', {
  1118. value: url
  1119. });
  1120. return response;
  1121. }
  1122. async function checkResponse(response) {
  1123. if (!response.ok) {
  1124. const message = await getResponseError(response);
  1125. throw new Error(message);
  1126. }
  1127. }
  1128. async function getResponseError(response) {
  1129. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1130. try {
  1131. const contentType = response.headers.get('Content-Type');
  1132. let text = response.statusText;
  1133. if (contentType.includes('application/json')) {
  1134. text += " ".concat(await response.text());
  1135. }
  1136. message += text;
  1137. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1138. } catch (error) {}
  1139. return message;
  1140. }
  1141. async function getInitialDataUrl(resource) {
  1142. const INITIAL_DATA_LENGTH = 5;
  1143. if (typeof resource === 'string') {
  1144. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1145. }
  1146. if (resource instanceof Blob) {
  1147. const blobSlice = resource.slice(0, 5);
  1148. return await new Promise(resolve => {
  1149. const reader = new FileReader();
  1150. reader.onload = event => {
  1151. var _event$target;
  1152. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1153. };
  1154. reader.readAsDataURL(blobSlice);
  1155. });
  1156. }
  1157. if (resource instanceof ArrayBuffer) {
  1158. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1159. const base64 = arrayBufferToBase64(slice);
  1160. return "data:base64,".concat(base64);
  1161. }
  1162. return null;
  1163. }
  1164. function arrayBufferToBase64(buffer) {
  1165. let binary = '';
  1166. const bytes = new Uint8Array(buffer);
  1167. for (let i = 0; i < bytes.byteLength; i++) {
  1168. binary += String.fromCharCode(bytes[i]);
  1169. }
  1170. return btoa(binary);
  1171. }
  1172. async function fetchFile(url, options) {
  1173. if (typeof url === 'string') {
  1174. url = resolvePath(url);
  1175. let fetchOptions = options;
  1176. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1177. fetchOptions = options.fetch;
  1178. }
  1179. return await fetch(url, fetchOptions);
  1180. }
  1181. return await makeResponse(url);
  1182. }
  1183. function isElectron(mockUserAgent) {
  1184. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1185. return true;
  1186. }
  1187. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1188. return true;
  1189. }
  1190. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1191. const userAgent = mockUserAgent || realUserAgent;
  1192. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1193. return true;
  1194. }
  1195. return false;
  1196. }
  1197. function isBrowser() {
  1198. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1199. return !isNode || isElectron();
  1200. }
  1201. const globals = {
  1202. self: typeof self !== 'undefined' && self,
  1203. window: typeof window !== 'undefined' && window,
  1204. global: typeof global !== 'undefined' && global,
  1205. document: typeof document !== 'undefined' && document,
  1206. process: typeof process === 'object' && process
  1207. };
  1208. const window_ = globals.window || globals.self || globals.global;
  1209. const process_ = globals.process || {};
  1210. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1211. isBrowser();
  1212. function getStorage(type) {
  1213. try {
  1214. const storage = window[type];
  1215. const x = '__storage_test__';
  1216. storage.setItem(x, x);
  1217. storage.removeItem(x);
  1218. return storage;
  1219. } catch (e) {
  1220. return null;
  1221. }
  1222. }
  1223. class LocalStorage {
  1224. constructor(id) {
  1225. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1226. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1227. _defineProperty(this, "storage", void 0);
  1228. _defineProperty(this, "id", void 0);
  1229. _defineProperty(this, "config", {});
  1230. this.storage = getStorage(type);
  1231. this.id = id;
  1232. this.config = {};
  1233. Object.assign(this.config, defaultSettings);
  1234. this._loadConfiguration();
  1235. }
  1236. getConfiguration() {
  1237. return this.config;
  1238. }
  1239. setConfiguration(configuration) {
  1240. this.config = {};
  1241. return this.updateConfiguration(configuration);
  1242. }
  1243. updateConfiguration(configuration) {
  1244. Object.assign(this.config, configuration);
  1245. if (this.storage) {
  1246. const serialized = JSON.stringify(this.config);
  1247. this.storage.setItem(this.id, serialized);
  1248. }
  1249. return this;
  1250. }
  1251. _loadConfiguration() {
  1252. let configuration = {};
  1253. if (this.storage) {
  1254. const serializedConfiguration = this.storage.getItem(this.id);
  1255. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1256. }
  1257. Object.assign(this.config, configuration);
  1258. return this;
  1259. }
  1260. }
  1261. function formatTime(ms) {
  1262. let formatted;
  1263. if (ms < 10) {
  1264. formatted = "".concat(ms.toFixed(2), "ms");
  1265. } else if (ms < 100) {
  1266. formatted = "".concat(ms.toFixed(1), "ms");
  1267. } else if (ms < 1000) {
  1268. formatted = "".concat(ms.toFixed(0), "ms");
  1269. } else {
  1270. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1271. }
  1272. return formatted;
  1273. }
  1274. function leftPad(string) {
  1275. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1276. const padLength = Math.max(length - string.length, 0);
  1277. return "".concat(' '.repeat(padLength)).concat(string);
  1278. }
  1279. function formatImage(image, message, scale) {
  1280. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1281. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1282. if (image.width > maxWidth) {
  1283. scale = Math.min(scale, maxWidth / image.width);
  1284. }
  1285. const width = image.width * scale;
  1286. const height = image.height * scale;
  1287. 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('');
  1288. return ["".concat(message, " %c+"), style];
  1289. }
  1290. let COLOR;
  1291. (function (COLOR) {
  1292. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1293. COLOR[COLOR["RED"] = 31] = "RED";
  1294. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1295. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1296. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1297. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1298. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1299. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1300. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1301. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1302. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1303. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1304. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1305. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1306. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1307. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1308. })(COLOR || (COLOR = {}));
  1309. function getColor(color) {
  1310. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1311. }
  1312. function addColor(string, color, background) {
  1313. if (!isBrowser && typeof string === 'string') {
  1314. if (color) {
  1315. color = getColor(color);
  1316. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1317. }
  1318. if (background) {
  1319. color = getColor(background);
  1320. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1321. }
  1322. }
  1323. return string;
  1324. }
  1325. function autobind(obj) {
  1326. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1327. const proto = Object.getPrototypeOf(obj);
  1328. const propNames = Object.getOwnPropertyNames(proto);
  1329. for (const key of propNames) {
  1330. if (typeof obj[key] === 'function') {
  1331. if (!predefined.find(name => key === name)) {
  1332. obj[key] = obj[key].bind(obj);
  1333. }
  1334. }
  1335. }
  1336. }
  1337. function assert$5(condition, message) {
  1338. if (!condition) {
  1339. throw new Error(message || 'Assertion failed');
  1340. }
  1341. }
  1342. function getHiResTimestamp() {
  1343. let timestamp;
  1344. if (isBrowser && 'performance' in window_) {
  1345. var _window$performance, _window$performance$n;
  1346. 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);
  1347. } else if ('hrtime' in process_) {
  1348. var _process$hrtime;
  1349. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1350. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1351. } else {
  1352. timestamp = Date.now();
  1353. }
  1354. return timestamp;
  1355. }
  1356. const originalConsole = {
  1357. debug: isBrowser ? console.debug || console.log : console.log,
  1358. log: console.log,
  1359. info: console.info,
  1360. warn: console.warn,
  1361. error: console.error
  1362. };
  1363. const DEFAULT_SETTINGS = {
  1364. enabled: true,
  1365. level: 0
  1366. };
  1367. function noop$1() {}
  1368. const cache = {};
  1369. const ONCE = {
  1370. once: true
  1371. };
  1372. class Log {
  1373. constructor() {
  1374. let {
  1375. id
  1376. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1377. id: ''
  1378. };
  1379. _defineProperty(this, "id", void 0);
  1380. _defineProperty(this, "VERSION", VERSION$6);
  1381. _defineProperty(this, "_startTs", getHiResTimestamp());
  1382. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1383. _defineProperty(this, "_storage", void 0);
  1384. _defineProperty(this, "userData", {});
  1385. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1386. this.id = id;
  1387. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1388. this.userData = {};
  1389. this.timeStamp("".concat(this.id, " started"));
  1390. autobind(this);
  1391. Object.seal(this);
  1392. }
  1393. set level(newLevel) {
  1394. this.setLevel(newLevel);
  1395. }
  1396. get level() {
  1397. return this.getLevel();
  1398. }
  1399. isEnabled() {
  1400. return this._storage.config.enabled;
  1401. }
  1402. getLevel() {
  1403. return this._storage.config.level;
  1404. }
  1405. getTotal() {
  1406. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1407. }
  1408. getDelta() {
  1409. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1410. }
  1411. set priority(newPriority) {
  1412. this.level = newPriority;
  1413. }
  1414. get priority() {
  1415. return this.level;
  1416. }
  1417. getPriority() {
  1418. return this.level;
  1419. }
  1420. enable() {
  1421. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1422. this._storage.updateConfiguration({
  1423. enabled
  1424. });
  1425. return this;
  1426. }
  1427. setLevel(level) {
  1428. this._storage.updateConfiguration({
  1429. level
  1430. });
  1431. return this;
  1432. }
  1433. get(setting) {
  1434. return this._storage.config[setting];
  1435. }
  1436. set(setting, value) {
  1437. this._storage.updateConfiguration({
  1438. [setting]: value
  1439. });
  1440. }
  1441. settings() {
  1442. if (console.table) {
  1443. console.table(this._storage.config);
  1444. } else {
  1445. console.log(this._storage.config);
  1446. }
  1447. }
  1448. assert(condition, message) {
  1449. assert$5(condition, message);
  1450. }
  1451. warn(message) {
  1452. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1453. }
  1454. error(message) {
  1455. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1456. }
  1457. deprecated(oldUsage, newUsage) {
  1458. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1459. }
  1460. removed(oldUsage, newUsage) {
  1461. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1462. }
  1463. probe(logLevel, message) {
  1464. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1465. time: true,
  1466. once: true
  1467. });
  1468. }
  1469. log(logLevel, message) {
  1470. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1471. }
  1472. info(logLevel, message) {
  1473. return this._getLogFunction(logLevel, message, console.info, arguments);
  1474. }
  1475. once(logLevel, message) {
  1476. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1477. args[_key - 2] = arguments[_key];
  1478. }
  1479. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1480. }
  1481. table(logLevel, table, columns) {
  1482. if (table) {
  1483. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1484. tag: getTableHeader(table)
  1485. });
  1486. }
  1487. return noop$1;
  1488. }
  1489. image(_ref) {
  1490. let {
  1491. logLevel,
  1492. priority,
  1493. image,
  1494. message = '',
  1495. scale = 1
  1496. } = _ref;
  1497. if (!this._shouldLog(logLevel || priority)) {
  1498. return noop$1;
  1499. }
  1500. return isBrowser ? logImageInBrowser({
  1501. image,
  1502. message,
  1503. scale
  1504. }) : logImageInNode({
  1505. image,
  1506. message,
  1507. scale
  1508. });
  1509. }
  1510. time(logLevel, message) {
  1511. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1512. }
  1513. timeEnd(logLevel, message) {
  1514. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1515. }
  1516. timeStamp(logLevel, message) {
  1517. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1518. }
  1519. group(logLevel, message) {
  1520. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1521. collapsed: false
  1522. };
  1523. const options = normalizeArguments({
  1524. logLevel,
  1525. message,
  1526. opts
  1527. });
  1528. const {
  1529. collapsed
  1530. } = opts;
  1531. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1532. return this._getLogFunction(options);
  1533. }
  1534. groupCollapsed(logLevel, message) {
  1535. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1536. return this.group(logLevel, message, Object.assign({}, opts, {
  1537. collapsed: true
  1538. }));
  1539. }
  1540. groupEnd(logLevel) {
  1541. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1542. }
  1543. withGroup(logLevel, message, func) {
  1544. this.group(logLevel, message)();
  1545. try {
  1546. func();
  1547. } finally {
  1548. this.groupEnd(logLevel)();
  1549. }
  1550. }
  1551. trace() {
  1552. if (console.trace) {
  1553. console.trace();
  1554. }
  1555. }
  1556. _shouldLog(logLevel) {
  1557. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1558. }
  1559. _getLogFunction(logLevel, message, method, args, opts) {
  1560. if (this._shouldLog(logLevel)) {
  1561. opts = normalizeArguments({
  1562. logLevel,
  1563. message,
  1564. args,
  1565. opts
  1566. });
  1567. method = method || opts.method;
  1568. assert$5(method);
  1569. opts.total = this.getTotal();
  1570. opts.delta = this.getDelta();
  1571. this._deltaTs = getHiResTimestamp();
  1572. const tag = opts.tag || opts.message;
  1573. if (opts.once) {
  1574. if (!cache[tag]) {
  1575. cache[tag] = getHiResTimestamp();
  1576. } else {
  1577. return noop$1;
  1578. }
  1579. }
  1580. message = decorateMessage(this.id, opts.message, opts);
  1581. return method.bind(console, message, ...opts.args);
  1582. }
  1583. return noop$1;
  1584. }
  1585. }
  1586. _defineProperty(Log, "VERSION", VERSION$6);
  1587. function normalizeLogLevel(logLevel) {
  1588. if (!logLevel) {
  1589. return 0;
  1590. }
  1591. let resolvedLevel;
  1592. switch (typeof logLevel) {
  1593. case 'number':
  1594. resolvedLevel = logLevel;
  1595. break;
  1596. case 'object':
  1597. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1598. break;
  1599. default:
  1600. return 0;
  1601. }
  1602. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1603. return resolvedLevel;
  1604. }
  1605. function normalizeArguments(opts) {
  1606. const {
  1607. logLevel,
  1608. message
  1609. } = opts;
  1610. opts.logLevel = normalizeLogLevel(logLevel);
  1611. const args = opts.args ? Array.from(opts.args) : [];
  1612. while (args.length && args.shift() !== message) {}
  1613. switch (typeof logLevel) {
  1614. case 'string':
  1615. case 'function':
  1616. if (message !== undefined) {
  1617. args.unshift(message);
  1618. }
  1619. opts.message = logLevel;
  1620. break;
  1621. case 'object':
  1622. Object.assign(opts, logLevel);
  1623. break;
  1624. }
  1625. if (typeof opts.message === 'function') {
  1626. opts.message = opts.message();
  1627. }
  1628. const messageType = typeof opts.message;
  1629. assert$5(messageType === 'string' || messageType === 'object');
  1630. return Object.assign(opts, {
  1631. args
  1632. }, opts.opts);
  1633. }
  1634. function decorateMessage(id, message, opts) {
  1635. if (typeof message === 'string') {
  1636. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1637. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1638. message = addColor(message, opts.color, opts.background);
  1639. }
  1640. return message;
  1641. }
  1642. function logImageInNode(_ref2) {
  1643. let {
  1644. image,
  1645. message = '',
  1646. scale = 1
  1647. } = _ref2;
  1648. let asciify = null;
  1649. try {
  1650. asciify = module.require('asciify-image');
  1651. } catch (error) {}
  1652. if (asciify) {
  1653. return () => asciify(image, {
  1654. fit: 'box',
  1655. width: "".concat(Math.round(80 * scale), "%")
  1656. }).then(data => console.log(data));
  1657. }
  1658. return noop$1;
  1659. }
  1660. function logImageInBrowser(_ref3) {
  1661. let {
  1662. image,
  1663. message = '',
  1664. scale = 1
  1665. } = _ref3;
  1666. if (typeof image === 'string') {
  1667. const img = new Image();
  1668. img.onload = () => {
  1669. const args = formatImage(img, message, scale);
  1670. console.log(...args);
  1671. };
  1672. img.src = image;
  1673. return noop$1;
  1674. }
  1675. const element = image.nodeName || '';
  1676. if (element.toLowerCase() === 'img') {
  1677. console.log(...formatImage(image, message, scale));
  1678. return noop$1;
  1679. }
  1680. if (element.toLowerCase() === 'canvas') {
  1681. const img = new Image();
  1682. img.onload = () => console.log(...formatImage(img, message, scale));
  1683. img.src = image.toDataURL();
  1684. return noop$1;
  1685. }
  1686. return noop$1;
  1687. }
  1688. function getTableHeader(table) {
  1689. for (const key in table) {
  1690. for (const title in table[key]) {
  1691. return title || 'untitled';
  1692. }
  1693. }
  1694. return 'empty';
  1695. }
  1696. const probeLog = new Log({
  1697. id: 'loaders.gl'
  1698. });
  1699. class NullLog {
  1700. log() {
  1701. return () => {};
  1702. }
  1703. info() {
  1704. return () => {};
  1705. }
  1706. warn() {
  1707. return () => {};
  1708. }
  1709. error() {
  1710. return () => {};
  1711. }
  1712. }
  1713. class ConsoleLog {
  1714. constructor() {
  1715. _defineProperty(this, "console", void 0);
  1716. this.console = console;
  1717. }
  1718. log(...args) {
  1719. return this.console.log.bind(this.console, ...args);
  1720. }
  1721. info(...args) {
  1722. return this.console.info.bind(this.console, ...args);
  1723. }
  1724. warn(...args) {
  1725. return this.console.warn.bind(this.console, ...args);
  1726. }
  1727. error(...args) {
  1728. return this.console.error.bind(this.console, ...args);
  1729. }
  1730. }
  1731. const DEFAULT_LOADER_OPTIONS = {
  1732. fetch: null,
  1733. mimeType: undefined,
  1734. nothrow: false,
  1735. log: new ConsoleLog(),
  1736. CDN: 'https://unpkg.com/@loaders.gl',
  1737. worker: true,
  1738. maxConcurrency: 3,
  1739. maxMobileConcurrency: 1,
  1740. reuseWorkers: true,
  1741. _workerType: '',
  1742. limit: 0,
  1743. _limitMB: 0,
  1744. batchSize: 'auto',
  1745. batchDebounceMs: 0,
  1746. metadata: false,
  1747. transforms: []
  1748. };
  1749. const REMOVED_LOADER_OPTIONS = {
  1750. throws: 'nothrow',
  1751. dataType: '(no longer used)',
  1752. uri: 'baseUri',
  1753. method: 'fetch.method',
  1754. headers: 'fetch.headers',
  1755. body: 'fetch.body',
  1756. mode: 'fetch.mode',
  1757. credentials: 'fetch.credentials',
  1758. cache: 'fetch.cache',
  1759. redirect: 'fetch.redirect',
  1760. referrer: 'fetch.referrer',
  1761. referrerPolicy: 'fetch.referrerPolicy',
  1762. integrity: 'fetch.integrity',
  1763. keepalive: 'fetch.keepalive',
  1764. signal: 'fetch.signal'
  1765. };
  1766. function getGlobalLoaderState() {
  1767. globalThis.loaders = globalThis.loaders || {};
  1768. const {
  1769. loaders
  1770. } = globalThis;
  1771. loaders._state = loaders._state || {};
  1772. return loaders._state;
  1773. }
  1774. const getGlobalLoaderOptions = () => {
  1775. const state = getGlobalLoaderState();
  1776. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1777. };
  1778. return state.globalOptions;
  1779. };
  1780. function normalizeOptions(options, loader, loaders, url) {
  1781. loaders = loaders || [];
  1782. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1783. validateOptions(options, loaders);
  1784. return normalizeOptionsInternal(loader, options, url);
  1785. }
  1786. function getFetchFunction(options, context) {
  1787. const globalOptions = getGlobalLoaderOptions();
  1788. const fetchOptions = options || globalOptions;
  1789. if (typeof fetchOptions.fetch === 'function') {
  1790. return fetchOptions.fetch;
  1791. }
  1792. if (isObject(fetchOptions.fetch)) {
  1793. return url => fetchFile(url, fetchOptions);
  1794. }
  1795. if (context !== null && context !== void 0 && context.fetch) {
  1796. return context === null || context === void 0 ? void 0 : context.fetch;
  1797. }
  1798. return fetchFile;
  1799. }
  1800. function validateOptions(options, loaders) {
  1801. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1802. for (const loader of loaders) {
  1803. const idOptions = options && options[loader.id] || {};
  1804. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1805. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1806. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1807. }
  1808. }
  1809. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1810. const loaderName = id || 'Top level';
  1811. const prefix = id ? "".concat(id, ".") : '';
  1812. for (const key in options) {
  1813. const isSubOptions = !id && isObject(options[key]);
  1814. const isBaseUriOption = key === 'baseUri' && !id;
  1815. const isWorkerUrlOption = key === 'workerUrl' && id;
  1816. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1817. if (key in deprecatedOptions) {
  1818. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1819. } else if (!isSubOptions) {
  1820. const suggestion = findSimilarOption(key, loaders);
  1821. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1822. }
  1823. }
  1824. }
  1825. }
  1826. function findSimilarOption(optionKey, loaders) {
  1827. const lowerCaseOptionKey = optionKey.toLowerCase();
  1828. let bestSuggestion = '';
  1829. for (const loader of loaders) {
  1830. for (const key in loader.options) {
  1831. if (optionKey === key) {
  1832. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1833. }
  1834. const lowerCaseKey = key.toLowerCase();
  1835. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1836. if (isPartialMatch) {
  1837. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1838. }
  1839. }
  1840. }
  1841. return bestSuggestion;
  1842. }
  1843. function normalizeOptionsInternal(loader, options, url) {
  1844. const loaderDefaultOptions = loader.options || {};
  1845. const mergedOptions = { ...loaderDefaultOptions
  1846. };
  1847. addUrlOptions(mergedOptions, url);
  1848. if (mergedOptions.log === null) {
  1849. mergedOptions.log = new NullLog();
  1850. }
  1851. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1852. mergeNestedFields(mergedOptions, options);
  1853. return mergedOptions;
  1854. }
  1855. function mergeNestedFields(mergedOptions, options) {
  1856. for (const key in options) {
  1857. if (key in options) {
  1858. const value = options[key];
  1859. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1860. mergedOptions[key] = { ...mergedOptions[key],
  1861. ...options[key]
  1862. };
  1863. } else {
  1864. mergedOptions[key] = options[key];
  1865. }
  1866. }
  1867. }
  1868. }
  1869. function addUrlOptions(options, url) {
  1870. if (url && !('baseUri' in options)) {
  1871. options.baseUri = url;
  1872. }
  1873. }
  1874. function isLoaderObject(loader) {
  1875. var _loader;
  1876. if (!loader) {
  1877. return false;
  1878. }
  1879. if (Array.isArray(loader)) {
  1880. loader = loader[0];
  1881. }
  1882. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1883. return hasExtensions;
  1884. }
  1885. function normalizeLoader(loader) {
  1886. var _loader2, _loader3;
  1887. assert$7(loader, 'null loader');
  1888. assert$7(isLoaderObject(loader), 'invalid loader');
  1889. let options;
  1890. if (Array.isArray(loader)) {
  1891. options = loader[1];
  1892. loader = loader[0];
  1893. loader = { ...loader,
  1894. options: { ...loader.options,
  1895. ...options
  1896. }
  1897. };
  1898. }
  1899. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1900. loader.text = true;
  1901. }
  1902. if (!loader.text) {
  1903. loader.binary = true;
  1904. }
  1905. return loader;
  1906. }
  1907. const getGlobalLoaderRegistry = () => {
  1908. const state = getGlobalLoaderState();
  1909. state.loaderRegistry = state.loaderRegistry || [];
  1910. return state.loaderRegistry;
  1911. };
  1912. function getRegisteredLoaders() {
  1913. return getGlobalLoaderRegistry();
  1914. }
  1915. const EXT_PATTERN = /\.([^.]+)$/;
  1916. async function selectLoader(data, loaders = [], options, context) {
  1917. if (!validHTTPResponse(data)) {
  1918. return null;
  1919. }
  1920. let loader = selectLoaderSync(data, loaders, { ...options,
  1921. nothrow: true
  1922. }, context);
  1923. if (loader) {
  1924. return loader;
  1925. }
  1926. if (isBlob(data)) {
  1927. data = await data.slice(0, 10).arrayBuffer();
  1928. loader = selectLoaderSync(data, loaders, options, context);
  1929. }
  1930. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1931. throw new Error(getNoValidLoaderMessage(data));
  1932. }
  1933. return loader;
  1934. }
  1935. function selectLoaderSync(data, loaders = [], options, context) {
  1936. if (!validHTTPResponse(data)) {
  1937. return null;
  1938. }
  1939. if (loaders && !Array.isArray(loaders)) {
  1940. return normalizeLoader(loaders);
  1941. }
  1942. let candidateLoaders = [];
  1943. if (loaders) {
  1944. candidateLoaders = candidateLoaders.concat(loaders);
  1945. }
  1946. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1947. candidateLoaders.push(...getRegisteredLoaders());
  1948. }
  1949. normalizeLoaders(candidateLoaders);
  1950. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1951. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1952. throw new Error(getNoValidLoaderMessage(data));
  1953. }
  1954. return loader;
  1955. }
  1956. function selectLoaderInternal(data, loaders, options, context) {
  1957. const {
  1958. url,
  1959. type
  1960. } = getResourceUrlAndType(data);
  1961. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1962. let loader = null;
  1963. if (options !== null && options !== void 0 && options.mimeType) {
  1964. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  1965. }
  1966. loader = loader || findLoaderByUrl(loaders, testUrl);
  1967. loader = loader || findLoaderByMIMEType(loaders, type);
  1968. loader = loader || findLoaderByInitialBytes(loaders, data);
  1969. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  1970. return loader;
  1971. }
  1972. function validHTTPResponse(data) {
  1973. if (data instanceof Response) {
  1974. if (data.status === 204) {
  1975. return false;
  1976. }
  1977. }
  1978. return true;
  1979. }
  1980. function getNoValidLoaderMessage(data) {
  1981. const {
  1982. url,
  1983. type
  1984. } = getResourceUrlAndType(data);
  1985. let message = 'No valid loader found (';
  1986. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  1987. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  1988. const firstCharacters = data ? getFirstCharacters(data) : '';
  1989. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  1990. message += ')';
  1991. return message;
  1992. }
  1993. function normalizeLoaders(loaders) {
  1994. for (const loader of loaders) {
  1995. normalizeLoader(loader);
  1996. }
  1997. }
  1998. function findLoaderByUrl(loaders, url) {
  1999. const match = url && EXT_PATTERN.exec(url);
  2000. const extension = match && match[1];
  2001. return extension ? findLoaderByExtension(loaders, extension) : null;
  2002. }
  2003. function findLoaderByExtension(loaders, extension) {
  2004. extension = extension.toLowerCase();
  2005. for (const loader of loaders) {
  2006. for (const loaderExtension of loader.extensions) {
  2007. if (loaderExtension.toLowerCase() === extension) {
  2008. return loader;
  2009. }
  2010. }
  2011. }
  2012. return null;
  2013. }
  2014. function findLoaderByMIMEType(loaders, mimeType) {
  2015. for (const loader of loaders) {
  2016. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2017. return loader;
  2018. }
  2019. if (mimeType === "application/x.".concat(loader.id)) {
  2020. return loader;
  2021. }
  2022. }
  2023. return null;
  2024. }
  2025. function findLoaderByInitialBytes(loaders, data) {
  2026. if (!data) {
  2027. return null;
  2028. }
  2029. for (const loader of loaders) {
  2030. if (typeof data === 'string') {
  2031. if (testDataAgainstText(data, loader)) {
  2032. return loader;
  2033. }
  2034. } else if (ArrayBuffer.isView(data)) {
  2035. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2036. return loader;
  2037. }
  2038. } else if (data instanceof ArrayBuffer) {
  2039. const byteOffset = 0;
  2040. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2041. return loader;
  2042. }
  2043. }
  2044. }
  2045. return null;
  2046. }
  2047. function testDataAgainstText(data, loader) {
  2048. if (loader.testText) {
  2049. return loader.testText(data);
  2050. }
  2051. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2052. return tests.some(test => data.startsWith(test));
  2053. }
  2054. function testDataAgainstBinary(data, byteOffset, loader) {
  2055. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2056. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2057. }
  2058. function testBinary(data, byteOffset, loader, test) {
  2059. if (test instanceof ArrayBuffer) {
  2060. return compareArrayBuffers(test, data, test.byteLength);
  2061. }
  2062. switch (typeof test) {
  2063. case 'function':
  2064. return test(data, loader);
  2065. case 'string':
  2066. const magic = getMagicString$2(data, byteOffset, test.length);
  2067. return test === magic;
  2068. default:
  2069. return false;
  2070. }
  2071. }
  2072. function getFirstCharacters(data, length = 5) {
  2073. if (typeof data === 'string') {
  2074. return data.slice(0, length);
  2075. } else if (ArrayBuffer.isView(data)) {
  2076. return getMagicString$2(data.buffer, data.byteOffset, length);
  2077. } else if (data instanceof ArrayBuffer) {
  2078. const byteOffset = 0;
  2079. return getMagicString$2(data, byteOffset, length);
  2080. }
  2081. return '';
  2082. }
  2083. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2084. if (arrayBuffer.byteLength < byteOffset + length) {
  2085. return '';
  2086. }
  2087. const dataView = new DataView(arrayBuffer);
  2088. let magic = '';
  2089. for (let i = 0; i < length; i++) {
  2090. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2091. }
  2092. return magic;
  2093. }
  2094. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2095. function* makeStringIterator(string, options) {
  2096. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2097. let offset = 0;
  2098. const textEncoder = new TextEncoder();
  2099. while (offset < string.length) {
  2100. const chunkLength = Math.min(string.length - offset, chunkSize);
  2101. const chunk = string.slice(offset, offset + chunkLength);
  2102. offset += chunkLength;
  2103. yield textEncoder.encode(chunk);
  2104. }
  2105. }
  2106. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2107. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2108. const {
  2109. chunkSize = DEFAULT_CHUNK_SIZE$1
  2110. } = options;
  2111. let byteOffset = 0;
  2112. while (byteOffset < arrayBuffer.byteLength) {
  2113. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2114. const chunk = new ArrayBuffer(chunkByteLength);
  2115. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2116. const chunkArray = new Uint8Array(chunk);
  2117. chunkArray.set(sourceArray);
  2118. byteOffset += chunkByteLength;
  2119. yield chunk;
  2120. }
  2121. }
  2122. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2123. async function* makeBlobIterator(blob, options) {
  2124. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2125. let offset = 0;
  2126. while (offset < blob.size) {
  2127. const end = offset + chunkSize;
  2128. const chunk = await blob.slice(offset, end).arrayBuffer();
  2129. offset = end;
  2130. yield chunk;
  2131. }
  2132. }
  2133. function makeStreamIterator(stream, options) {
  2134. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2135. }
  2136. async function* makeBrowserStreamIterator(stream, options) {
  2137. const reader = stream.getReader();
  2138. let nextBatchPromise;
  2139. try {
  2140. while (true) {
  2141. const currentBatchPromise = nextBatchPromise || reader.read();
  2142. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2143. nextBatchPromise = reader.read();
  2144. }
  2145. const {
  2146. done,
  2147. value
  2148. } = await currentBatchPromise;
  2149. if (done) {
  2150. return;
  2151. }
  2152. yield toArrayBuffer(value);
  2153. }
  2154. } catch (error) {
  2155. reader.releaseLock();
  2156. }
  2157. }
  2158. async function* makeNodeStreamIterator(stream, options) {
  2159. for await (const chunk of stream) {
  2160. yield toArrayBuffer(chunk);
  2161. }
  2162. }
  2163. function makeIterator(data, options) {
  2164. if (typeof data === 'string') {
  2165. return makeStringIterator(data, options);
  2166. }
  2167. if (data instanceof ArrayBuffer) {
  2168. return makeArrayBufferIterator(data, options);
  2169. }
  2170. if (isBlob(data)) {
  2171. return makeBlobIterator(data, options);
  2172. }
  2173. if (isReadableStream(data)) {
  2174. return makeStreamIterator(data, options);
  2175. }
  2176. if (isResponse(data)) {
  2177. const response = data;
  2178. return makeStreamIterator(response.body, options);
  2179. }
  2180. throw new Error('makeIterator');
  2181. }
  2182. const ERR_DATA = 'Cannot convert supplied data type';
  2183. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2184. if (loader.text && typeof data === 'string') {
  2185. return data;
  2186. }
  2187. if (isBuffer(data)) {
  2188. data = data.buffer;
  2189. }
  2190. if (data instanceof ArrayBuffer) {
  2191. const arrayBuffer = data;
  2192. if (loader.text && !loader.binary) {
  2193. const textDecoder = new TextDecoder('utf8');
  2194. return textDecoder.decode(arrayBuffer);
  2195. }
  2196. return arrayBuffer;
  2197. }
  2198. if (ArrayBuffer.isView(data)) {
  2199. if (loader.text && !loader.binary) {
  2200. const textDecoder = new TextDecoder('utf8');
  2201. return textDecoder.decode(data);
  2202. }
  2203. let arrayBuffer = data.buffer;
  2204. const byteLength = data.byteLength || data.length;
  2205. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2206. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2207. }
  2208. return arrayBuffer;
  2209. }
  2210. throw new Error(ERR_DATA);
  2211. }
  2212. async function getArrayBufferOrStringFromData(data, loader, options) {
  2213. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2214. if (typeof data === 'string' || isArrayBuffer) {
  2215. return getArrayBufferOrStringFromDataSync(data, loader);
  2216. }
  2217. if (isBlob(data)) {
  2218. data = await makeResponse(data);
  2219. }
  2220. if (isResponse(data)) {
  2221. const response = data;
  2222. await checkResponse(response);
  2223. return loader.binary ? await response.arrayBuffer() : await response.text();
  2224. }
  2225. if (isReadableStream(data)) {
  2226. data = makeIterator(data, options);
  2227. }
  2228. if (isIterable(data) || isAsyncIterable(data)) {
  2229. return concatenateArrayBuffersAsync(data);
  2230. }
  2231. throw new Error(ERR_DATA);
  2232. }
  2233. function getLoaderContext(context, options, previousContext = null) {
  2234. if (previousContext) {
  2235. return previousContext;
  2236. }
  2237. const resolvedContext = {
  2238. fetch: getFetchFunction(options, context),
  2239. ...context
  2240. };
  2241. if (!Array.isArray(resolvedContext.loaders)) {
  2242. resolvedContext.loaders = null;
  2243. }
  2244. return resolvedContext;
  2245. }
  2246. function getLoadersFromContext(loaders, context) {
  2247. if (!context && loaders && !Array.isArray(loaders)) {
  2248. return loaders;
  2249. }
  2250. let candidateLoaders;
  2251. if (loaders) {
  2252. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2253. }
  2254. if (context && context.loaders) {
  2255. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2256. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2257. }
  2258. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2259. }
  2260. async function parse$3(data, loaders, options, context) {
  2261. assert$6(!context || typeof context === 'object');
  2262. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2263. context = undefined;
  2264. options = loaders;
  2265. loaders = undefined;
  2266. }
  2267. data = await data;
  2268. options = options || {};
  2269. const {
  2270. url
  2271. } = getResourceUrlAndType(data);
  2272. const typedLoaders = loaders;
  2273. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2274. const loader = await selectLoader(data, candidateLoaders, options);
  2275. if (!loader) {
  2276. return null;
  2277. }
  2278. options = normalizeOptions(options, loader, candidateLoaders, url);
  2279. context = getLoaderContext({
  2280. url,
  2281. parse: parse$3,
  2282. loaders: candidateLoaders
  2283. }, options, context);
  2284. return await parseWithLoader(loader, data, options, context);
  2285. }
  2286. async function parseWithLoader(loader, data, options, context) {
  2287. validateWorkerVersion(loader);
  2288. data = await getArrayBufferOrStringFromData(data, loader, options);
  2289. if (loader.parseTextSync && typeof data === 'string') {
  2290. options.dataType = 'text';
  2291. return loader.parseTextSync(data, options, context, loader);
  2292. }
  2293. if (canParseWithWorker(loader, options)) {
  2294. return await parseWithWorker(loader, data, options, context, parse$3);
  2295. }
  2296. if (loader.parseText && typeof data === 'string') {
  2297. return await loader.parseText(data, options, context, loader);
  2298. }
  2299. if (loader.parse) {
  2300. return await loader.parse(data, options, context, loader);
  2301. }
  2302. assert$6(!loader.parseSync);
  2303. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2304. }
  2305. async function load(url, loaders, options, context) {
  2306. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2307. options = loaders;
  2308. loaders = undefined;
  2309. }
  2310. const fetch = getFetchFunction(options);
  2311. let data = url;
  2312. if (typeof url === 'string') {
  2313. data = await fetch(url);
  2314. }
  2315. if (isBlob(url)) {
  2316. data = await fetch(url);
  2317. }
  2318. return await parse$3(data, loaders, options);
  2319. }
  2320. function assert$4(condition, message) {
  2321. if (!condition) {
  2322. throw new Error("math.gl assertion ".concat(message));
  2323. }
  2324. }
  2325. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2326. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2327. const config = {};
  2328. config.EPSILON = 1e-12;
  2329. config.debug = false;
  2330. config.precision = 4;
  2331. config.printTypes = false;
  2332. config.printDegrees = false;
  2333. config.printRowMajor = true;
  2334. function round(value) {
  2335. return Math.round(value / config.EPSILON) * config.EPSILON;
  2336. }
  2337. function formatValue(value, {
  2338. precision = config.precision || 4
  2339. } = {}) {
  2340. value = round(value);
  2341. return "".concat(parseFloat(value.toPrecision(precision)));
  2342. }
  2343. function isArray(value) {
  2344. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2345. }
  2346. function duplicateArray(array) {
  2347. return array.clone ? array.clone() : new Array(array.length);
  2348. }
  2349. function map$1(value, func, result) {
  2350. if (isArray(value)) {
  2351. result = result || duplicateArray(value);
  2352. for (let i = 0; i < result.length && i < value.length; ++i) {
  2353. result[i] = func(value[i], i, result);
  2354. }
  2355. return result;
  2356. }
  2357. return func(value);
  2358. }
  2359. function toRadians(degrees) {
  2360. return radians(degrees);
  2361. }
  2362. function toDegrees(radians) {
  2363. return degrees(radians);
  2364. }
  2365. function radians(degrees, result) {
  2366. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2367. }
  2368. function degrees(radians, result) {
  2369. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2370. }
  2371. function clamp(value, min, max) {
  2372. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2373. }
  2374. function equals(a, b, epsilon) {
  2375. const oldEpsilon = config.EPSILON;
  2376. if (epsilon) {
  2377. config.EPSILON = epsilon;
  2378. }
  2379. try {
  2380. if (a === b) {
  2381. return true;
  2382. }
  2383. if (isArray(a) && isArray(b)) {
  2384. if (a.length !== b.length) {
  2385. return false;
  2386. }
  2387. for (let i = 0; i < a.length; ++i) {
  2388. if (!equals(a[i], b[i])) {
  2389. return false;
  2390. }
  2391. }
  2392. return true;
  2393. }
  2394. if (a && a.equals) {
  2395. return a.equals(b);
  2396. }
  2397. if (b && b.equals) {
  2398. return b.equals(a);
  2399. }
  2400. if (Number.isFinite(a) && Number.isFinite(b)) {
  2401. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2402. }
  2403. return false;
  2404. } finally {
  2405. config.EPSILON = oldEpsilon;
  2406. }
  2407. }
  2408. function _extendableBuiltin(cls) {
  2409. function ExtendableBuiltin() {
  2410. var instance = Reflect.construct(cls, Array.from(arguments));
  2411. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2412. return instance;
  2413. }
  2414. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2415. constructor: {
  2416. value: cls,
  2417. enumerable: false,
  2418. writable: true,
  2419. configurable: true
  2420. }
  2421. });
  2422. if (Object.setPrototypeOf) {
  2423. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2424. } else {
  2425. ExtendableBuiltin.__proto__ = cls;
  2426. }
  2427. return ExtendableBuiltin;
  2428. }
  2429. class MathArray extends _extendableBuiltin(Array) {
  2430. get ELEMENTS() {
  2431. assert$4(false);
  2432. return 0;
  2433. }
  2434. clone() {
  2435. return new this.constructor().copy(this);
  2436. }
  2437. from(arrayOrObject) {
  2438. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2439. }
  2440. fromArray(array, offset = 0) {
  2441. for (let i = 0; i < this.ELEMENTS; ++i) {
  2442. this[i] = array[i + offset];
  2443. }
  2444. return this.check();
  2445. }
  2446. to(arrayOrObject) {
  2447. if (arrayOrObject === this) {
  2448. return this;
  2449. }
  2450. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2451. }
  2452. toTarget(target) {
  2453. return target ? this.to(target) : this;
  2454. }
  2455. toArray(array = [], offset = 0) {
  2456. for (let i = 0; i < this.ELEMENTS; ++i) {
  2457. array[offset + i] = this[i];
  2458. }
  2459. return array;
  2460. }
  2461. toFloat32Array() {
  2462. return new Float32Array(this);
  2463. }
  2464. toString() {
  2465. return this.formatString(config);
  2466. }
  2467. formatString(opts) {
  2468. let string = '';
  2469. for (let i = 0; i < this.ELEMENTS; ++i) {
  2470. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2471. }
  2472. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2473. }
  2474. equals(array) {
  2475. if (!array || this.length !== array.length) {
  2476. return false;
  2477. }
  2478. for (let i = 0; i < this.ELEMENTS; ++i) {
  2479. if (!equals(this[i], array[i])) {
  2480. return false;
  2481. }
  2482. }
  2483. return true;
  2484. }
  2485. exactEquals(array) {
  2486. if (!array || this.length !== array.length) {
  2487. return false;
  2488. }
  2489. for (let i = 0; i < this.ELEMENTS; ++i) {
  2490. if (this[i] !== array[i]) {
  2491. return false;
  2492. }
  2493. }
  2494. return true;
  2495. }
  2496. negate() {
  2497. for (let i = 0; i < this.ELEMENTS; ++i) {
  2498. this[i] = -this[i];
  2499. }
  2500. return this.check();
  2501. }
  2502. lerp(a, b, t) {
  2503. if (t === undefined) {
  2504. t = b;
  2505. b = a;
  2506. a = this;
  2507. }
  2508. for (let i = 0; i < this.ELEMENTS; ++i) {
  2509. const ai = a[i];
  2510. this[i] = ai + t * (b[i] - ai);
  2511. }
  2512. return this.check();
  2513. }
  2514. min(vector) {
  2515. for (let i = 0; i < this.ELEMENTS; ++i) {
  2516. this[i] = Math.min(vector[i], this[i]);
  2517. }
  2518. return this.check();
  2519. }
  2520. max(vector) {
  2521. for (let i = 0; i < this.ELEMENTS; ++i) {
  2522. this[i] = Math.max(vector[i], this[i]);
  2523. }
  2524. return this.check();
  2525. }
  2526. clamp(minVector, maxVector) {
  2527. for (let i = 0; i < this.ELEMENTS; ++i) {
  2528. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2529. }
  2530. return this.check();
  2531. }
  2532. add(...vectors) {
  2533. for (const vector of vectors) {
  2534. for (let i = 0; i < this.ELEMENTS; ++i) {
  2535. this[i] += vector[i];
  2536. }
  2537. }
  2538. return this.check();
  2539. }
  2540. subtract(...vectors) {
  2541. for (const vector of vectors) {
  2542. for (let i = 0; i < this.ELEMENTS; ++i) {
  2543. this[i] -= vector[i];
  2544. }
  2545. }
  2546. return this.check();
  2547. }
  2548. scale(scale) {
  2549. if (Array.isArray(scale)) {
  2550. return this.multiply(scale);
  2551. }
  2552. for (let i = 0; i < this.ELEMENTS; ++i) {
  2553. this[i] *= scale;
  2554. }
  2555. return this.check();
  2556. }
  2557. sub(a) {
  2558. return this.subtract(a);
  2559. }
  2560. setScalar(a) {
  2561. for (let i = 0; i < this.ELEMENTS; ++i) {
  2562. this[i] = a;
  2563. }
  2564. return this.check();
  2565. }
  2566. addScalar(a) {
  2567. for (let i = 0; i < this.ELEMENTS; ++i) {
  2568. this[i] += a;
  2569. }
  2570. return this.check();
  2571. }
  2572. subScalar(a) {
  2573. return this.addScalar(-a);
  2574. }
  2575. multiplyScalar(scalar) {
  2576. for (let i = 0; i < this.ELEMENTS; ++i) {
  2577. this[i] *= scalar;
  2578. }
  2579. return this.check();
  2580. }
  2581. divideScalar(a) {
  2582. return this.scale(1 / a);
  2583. }
  2584. clampScalar(min, max) {
  2585. for (let i = 0; i < this.ELEMENTS; ++i) {
  2586. this[i] = Math.min(Math.max(this[i], min), max);
  2587. }
  2588. return this.check();
  2589. }
  2590. multiplyByScalar(scalar) {
  2591. return this.scale(scalar);
  2592. }
  2593. get elements() {
  2594. return this;
  2595. }
  2596. check() {
  2597. if (config.debug && !this.validate()) {
  2598. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2599. }
  2600. return this;
  2601. }
  2602. validate() {
  2603. let valid = this.length === this.ELEMENTS;
  2604. for (let i = 0; i < this.ELEMENTS; ++i) {
  2605. valid = valid && Number.isFinite(this[i]);
  2606. }
  2607. return valid;
  2608. }
  2609. }
  2610. function validateVector(v, length) {
  2611. if (v.length !== length) {
  2612. return false;
  2613. }
  2614. for (let i = 0; i < v.length; ++i) {
  2615. if (!Number.isFinite(v[i])) {
  2616. return false;
  2617. }
  2618. }
  2619. return true;
  2620. }
  2621. function checkNumber(value) {
  2622. if (!Number.isFinite(value)) {
  2623. throw new Error("Invalid number ".concat(value));
  2624. }
  2625. return value;
  2626. }
  2627. function checkVector(v, length, callerName = '') {
  2628. if (config.debug && !validateVector(v, length)) {
  2629. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2630. }
  2631. return v;
  2632. }
  2633. const map = {};
  2634. function deprecated(method, version) {
  2635. if (!map[method]) {
  2636. map[method] = true;
  2637. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2638. }
  2639. }
  2640. class Vector extends MathArray {
  2641. get ELEMENTS() {
  2642. assert$4(false);
  2643. return 0;
  2644. }
  2645. copy(vector) {
  2646. assert$4(false);
  2647. return this;
  2648. }
  2649. get x() {
  2650. return this[0];
  2651. }
  2652. set x(value) {
  2653. this[0] = checkNumber(value);
  2654. }
  2655. get y() {
  2656. return this[1];
  2657. }
  2658. set y(value) {
  2659. this[1] = checkNumber(value);
  2660. }
  2661. len() {
  2662. return Math.sqrt(this.lengthSquared());
  2663. }
  2664. magnitude() {
  2665. return this.len();
  2666. }
  2667. lengthSquared() {
  2668. let length = 0;
  2669. for (let i = 0; i < this.ELEMENTS; ++i) {
  2670. length += this[i] * this[i];
  2671. }
  2672. return length;
  2673. }
  2674. magnitudeSquared() {
  2675. return this.lengthSquared();
  2676. }
  2677. distance(mathArray) {
  2678. return Math.sqrt(this.distanceSquared(mathArray));
  2679. }
  2680. distanceSquared(mathArray) {
  2681. let length = 0;
  2682. for (let i = 0; i < this.ELEMENTS; ++i) {
  2683. const dist = this[i] - mathArray[i];
  2684. length += dist * dist;
  2685. }
  2686. return checkNumber(length);
  2687. }
  2688. dot(mathArray) {
  2689. let product = 0;
  2690. for (let i = 0; i < this.ELEMENTS; ++i) {
  2691. product += this[i] * mathArray[i];
  2692. }
  2693. return checkNumber(product);
  2694. }
  2695. normalize() {
  2696. const length = this.magnitude();
  2697. if (length !== 0) {
  2698. for (let i = 0; i < this.ELEMENTS; ++i) {
  2699. this[i] /= length;
  2700. }
  2701. }
  2702. return this.check();
  2703. }
  2704. multiply(...vectors) {
  2705. for (const vector of vectors) {
  2706. for (let i = 0; i < this.ELEMENTS; ++i) {
  2707. this[i] *= vector[i];
  2708. }
  2709. }
  2710. return this.check();
  2711. }
  2712. divide(...vectors) {
  2713. for (const vector of vectors) {
  2714. for (let i = 0; i < this.ELEMENTS; ++i) {
  2715. this[i] /= vector[i];
  2716. }
  2717. }
  2718. return this.check();
  2719. }
  2720. lengthSq() {
  2721. return this.lengthSquared();
  2722. }
  2723. distanceTo(vector) {
  2724. return this.distance(vector);
  2725. }
  2726. distanceToSquared(vector) {
  2727. return this.distanceSquared(vector);
  2728. }
  2729. getComponent(i) {
  2730. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2731. return checkNumber(this[i]);
  2732. }
  2733. setComponent(i, value) {
  2734. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2735. this[i] = value;
  2736. return this.check();
  2737. }
  2738. addVectors(a, b) {
  2739. return this.copy(a).add(b);
  2740. }
  2741. subVectors(a, b) {
  2742. return this.copy(a).subtract(b);
  2743. }
  2744. multiplyVectors(a, b) {
  2745. return this.copy(a).multiply(b);
  2746. }
  2747. addScaledVector(a, b) {
  2748. return this.add(new this.constructor(a).multiplyScalar(b));
  2749. }
  2750. }
  2751. /**
  2752. * Common utilities
  2753. * @module glMatrix
  2754. */
  2755. // Configuration Constants
  2756. var EPSILON = 0.000001;
  2757. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2758. if (!Math.hypot) Math.hypot = function () {
  2759. var y = 0,
  2760. i = arguments.length;
  2761. while (i--) {
  2762. y += arguments[i] * arguments[i];
  2763. }
  2764. return Math.sqrt(y);
  2765. };
  2766. /**
  2767. * 2 Dimensional Vector
  2768. * @module vec2
  2769. */
  2770. /**
  2771. * Creates a new, empty vec2
  2772. *
  2773. * @returns {vec2} a new 2D vector
  2774. */
  2775. function create$4() {
  2776. var out = new ARRAY_TYPE(2);
  2777. if (ARRAY_TYPE != Float32Array) {
  2778. out[0] = 0;
  2779. out[1] = 0;
  2780. }
  2781. return out;
  2782. }
  2783. /**
  2784. * Transforms the vec2 with a mat2
  2785. *
  2786. * @param {vec2} out the receiving vector
  2787. * @param {ReadonlyVec2} a the vector to transform
  2788. * @param {ReadonlyMat2} m matrix to transform with
  2789. * @returns {vec2} out
  2790. */
  2791. function transformMat2(out, a, m) {
  2792. var x = a[0],
  2793. y = a[1];
  2794. out[0] = m[0] * x + m[2] * y;
  2795. out[1] = m[1] * x + m[3] * y;
  2796. return out;
  2797. }
  2798. /**
  2799. * Transforms the vec2 with a mat2d
  2800. *
  2801. * @param {vec2} out the receiving vector
  2802. * @param {ReadonlyVec2} a the vector to transform
  2803. * @param {ReadonlyMat2d} m matrix to transform with
  2804. * @returns {vec2} out
  2805. */
  2806. function transformMat2d(out, a, m) {
  2807. var x = a[0],
  2808. y = a[1];
  2809. out[0] = m[0] * x + m[2] * y + m[4];
  2810. out[1] = m[1] * x + m[3] * y + m[5];
  2811. return out;
  2812. }
  2813. /**
  2814. * Transforms the vec2 with a mat3
  2815. * 3rd vector component is implicitly '1'
  2816. *
  2817. * @param {vec2} out the receiving vector
  2818. * @param {ReadonlyVec2} a the vector to transform
  2819. * @param {ReadonlyMat3} m matrix to transform with
  2820. * @returns {vec2} out
  2821. */
  2822. function transformMat3$1(out, a, m) {
  2823. var x = a[0],
  2824. y = a[1];
  2825. out[0] = m[0] * x + m[3] * y + m[6];
  2826. out[1] = m[1] * x + m[4] * y + m[7];
  2827. return out;
  2828. }
  2829. /**
  2830. * Transforms the vec2 with a mat4
  2831. * 3rd vector component is implicitly '0'
  2832. * 4th vector component is implicitly '1'
  2833. *
  2834. * @param {vec2} out the receiving vector
  2835. * @param {ReadonlyVec2} a the vector to transform
  2836. * @param {ReadonlyMat4} m matrix to transform with
  2837. * @returns {vec2} out
  2838. */
  2839. function transformMat4$2(out, a, m) {
  2840. var x = a[0];
  2841. var y = a[1];
  2842. out[0] = m[0] * x + m[4] * y + m[12];
  2843. out[1] = m[1] * x + m[5] * y + m[13];
  2844. return out;
  2845. }
  2846. /**
  2847. * Perform some operation over an array of vec2s.
  2848. *
  2849. * @param {Array} a the array of vectors to iterate over
  2850. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2851. * @param {Number} offset Number of elements to skip at the beginning of the array
  2852. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2853. * @param {Function} fn Function to call for each vector in the array
  2854. * @param {Object} [arg] additional argument to pass to fn
  2855. * @returns {Array} a
  2856. * @function
  2857. */
  2858. (function () {
  2859. var vec = create$4();
  2860. return function (a, stride, offset, count, fn, arg) {
  2861. var i, l;
  2862. if (!stride) {
  2863. stride = 2;
  2864. }
  2865. if (!offset) {
  2866. offset = 0;
  2867. }
  2868. if (count) {
  2869. l = Math.min(count * stride + offset, a.length);
  2870. } else {
  2871. l = a.length;
  2872. }
  2873. for (i = offset; i < l; i += stride) {
  2874. vec[0] = a[i];
  2875. vec[1] = a[i + 1];
  2876. fn(vec, vec, arg);
  2877. a[i] = vec[0];
  2878. a[i + 1] = vec[1];
  2879. }
  2880. return a;
  2881. };
  2882. })();
  2883. function vec2_transformMat4AsVector(out, a, m) {
  2884. const x = a[0];
  2885. const y = a[1];
  2886. const w = m[3] * x + m[7] * y || 1.0;
  2887. out[0] = (m[0] * x + m[4] * y) / w;
  2888. out[1] = (m[1] * x + m[5] * y) / w;
  2889. return out;
  2890. }
  2891. function vec3_transformMat4AsVector(out, a, m) {
  2892. const x = a[0];
  2893. const y = a[1];
  2894. const z = a[2];
  2895. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2896. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2897. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2898. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2899. return out;
  2900. }
  2901. function vec3_transformMat2(out, a, m) {
  2902. const x = a[0];
  2903. const y = a[1];
  2904. out[0] = m[0] * x + m[2] * y;
  2905. out[1] = m[1] * x + m[3] * y;
  2906. out[2] = a[2];
  2907. return out;
  2908. }
  2909. function vec4_transformMat3(out, a, m) {
  2910. const x = a[0];
  2911. const y = a[1];
  2912. const z = a[2];
  2913. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2914. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2915. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2916. out[3] = a[3];
  2917. return out;
  2918. }
  2919. class Vector2 extends Vector {
  2920. constructor(x = 0, y = 0) {
  2921. super(2);
  2922. if (isArray(x) && arguments.length === 1) {
  2923. this.copy(x);
  2924. } else {
  2925. if (config.debug) {
  2926. checkNumber(x);
  2927. checkNumber(y);
  2928. }
  2929. this[0] = x;
  2930. this[1] = y;
  2931. }
  2932. }
  2933. set(x, y) {
  2934. this[0] = x;
  2935. this[1] = y;
  2936. return this.check();
  2937. }
  2938. copy(array) {
  2939. this[0] = array[0];
  2940. this[1] = array[1];
  2941. return this.check();
  2942. }
  2943. fromObject(object) {
  2944. if (config.debug) {
  2945. checkNumber(object.x);
  2946. checkNumber(object.y);
  2947. }
  2948. this[0] = object.x;
  2949. this[1] = object.y;
  2950. return this.check();
  2951. }
  2952. toObject(object) {
  2953. object.x = this[0];
  2954. object.y = this[1];
  2955. return object;
  2956. }
  2957. get ELEMENTS() {
  2958. return 2;
  2959. }
  2960. horizontalAngle() {
  2961. return Math.atan2(this.y, this.x);
  2962. }
  2963. verticalAngle() {
  2964. return Math.atan2(this.x, this.y);
  2965. }
  2966. transform(matrix4) {
  2967. return this.transformAsPoint(matrix4);
  2968. }
  2969. transformAsPoint(matrix4) {
  2970. transformMat4$2(this, this, matrix4);
  2971. return this.check();
  2972. }
  2973. transformAsVector(matrix4) {
  2974. vec2_transformMat4AsVector(this, this, matrix4);
  2975. return this.check();
  2976. }
  2977. transformByMatrix3(matrix3) {
  2978. transformMat3$1(this, this, matrix3);
  2979. return this.check();
  2980. }
  2981. transformByMatrix2x3(matrix2x3) {
  2982. transformMat2d(this, this, matrix2x3);
  2983. return this.check();
  2984. }
  2985. transformByMatrix2(matrix2) {
  2986. transformMat2(this, this, matrix2);
  2987. return this.check();
  2988. }
  2989. }
  2990. /**
  2991. * 3 Dimensional Vector
  2992. * @module vec3
  2993. */
  2994. /**
  2995. * Creates a new, empty vec3
  2996. *
  2997. * @returns {vec3} a new 3D vector
  2998. */
  2999. function create$3() {
  3000. var out = new ARRAY_TYPE(3);
  3001. if (ARRAY_TYPE != Float32Array) {
  3002. out[0] = 0;
  3003. out[1] = 0;
  3004. out[2] = 0;
  3005. }
  3006. return out;
  3007. }
  3008. /**
  3009. * Calculates the length of a vec3
  3010. *
  3011. * @param {ReadonlyVec3} a vector to calculate length of
  3012. * @returns {Number} length of a
  3013. */
  3014. function length$2(a) {
  3015. var x = a[0];
  3016. var y = a[1];
  3017. var z = a[2];
  3018. return Math.hypot(x, y, z);
  3019. }
  3020. /**
  3021. * Creates a new vec3 initialized with the given values
  3022. *
  3023. * @param {Number} x X component
  3024. * @param {Number} y Y component
  3025. * @param {Number} z Z component
  3026. * @returns {vec3} a new 3D vector
  3027. */
  3028. function fromValues(x, y, z) {
  3029. var out = new ARRAY_TYPE(3);
  3030. out[0] = x;
  3031. out[1] = y;
  3032. out[2] = z;
  3033. return out;
  3034. }
  3035. /**
  3036. * Normalize a vec3
  3037. *
  3038. * @param {vec3} out the receiving vector
  3039. * @param {ReadonlyVec3} a vector to normalize
  3040. * @returns {vec3} out
  3041. */
  3042. function normalize$2(out, a) {
  3043. var x = a[0];
  3044. var y = a[1];
  3045. var z = a[2];
  3046. var len = x * x + y * y + z * z;
  3047. if (len > 0) {
  3048. //TODO: evaluate use of glm_invsqrt here?
  3049. len = 1 / Math.sqrt(len);
  3050. }
  3051. out[0] = a[0] * len;
  3052. out[1] = a[1] * len;
  3053. out[2] = a[2] * len;
  3054. return out;
  3055. }
  3056. /**
  3057. * Calculates the dot product of two vec3's
  3058. *
  3059. * @param {ReadonlyVec3} a the first operand
  3060. * @param {ReadonlyVec3} b the second operand
  3061. * @returns {Number} dot product of a and b
  3062. */
  3063. function dot$2(a, b) {
  3064. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3065. }
  3066. /**
  3067. * Computes the cross product of two vec3's
  3068. *
  3069. * @param {vec3} out the receiving vector
  3070. * @param {ReadonlyVec3} a the first operand
  3071. * @param {ReadonlyVec3} b the second operand
  3072. * @returns {vec3} out
  3073. */
  3074. function cross(out, a, b) {
  3075. var ax = a[0],
  3076. ay = a[1],
  3077. az = a[2];
  3078. var bx = b[0],
  3079. by = b[1],
  3080. bz = b[2];
  3081. out[0] = ay * bz - az * by;
  3082. out[1] = az * bx - ax * bz;
  3083. out[2] = ax * by - ay * bx;
  3084. return out;
  3085. }
  3086. /**
  3087. * Transforms the vec3 with a mat4.
  3088. * 4th vector component is implicitly '1'
  3089. *
  3090. * @param {vec3} out the receiving vector
  3091. * @param {ReadonlyVec3} a the vector to transform
  3092. * @param {ReadonlyMat4} m matrix to transform with
  3093. * @returns {vec3} out
  3094. */
  3095. function transformMat4$1(out, a, m) {
  3096. var x = a[0],
  3097. y = a[1],
  3098. z = a[2];
  3099. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3100. w = w || 1.0;
  3101. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3102. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3103. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3104. return out;
  3105. }
  3106. /**
  3107. * Transforms the vec3 with a mat3.
  3108. *
  3109. * @param {vec3} out the receiving vector
  3110. * @param {ReadonlyVec3} a the vector to transform
  3111. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3112. * @returns {vec3} out
  3113. */
  3114. function transformMat3(out, a, m) {
  3115. var x = a[0],
  3116. y = a[1],
  3117. z = a[2];
  3118. out[0] = x * m[0] + y * m[3] + z * m[6];
  3119. out[1] = x * m[1] + y * m[4] + z * m[7];
  3120. out[2] = x * m[2] + y * m[5] + z * m[8];
  3121. return out;
  3122. }
  3123. /**
  3124. * Transforms the vec3 with a quat
  3125. * Can also be used for dual quaternions. (Multiply it with the real part)
  3126. *
  3127. * @param {vec3} out the receiving vector
  3128. * @param {ReadonlyVec3} a the vector to transform
  3129. * @param {ReadonlyQuat} q quaternion to transform with
  3130. * @returns {vec3} out
  3131. */
  3132. function transformQuat$1(out, a, q) {
  3133. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3134. var qx = q[0],
  3135. qy = q[1],
  3136. qz = q[2],
  3137. qw = q[3];
  3138. var x = a[0],
  3139. y = a[1],
  3140. z = a[2]; // var qvec = [qx, qy, qz];
  3141. // var uv = vec3.cross([], qvec, a);
  3142. var uvx = qy * z - qz * y,
  3143. uvy = qz * x - qx * z,
  3144. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3145. var uuvx = qy * uvz - qz * uvy,
  3146. uuvy = qz * uvx - qx * uvz,
  3147. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3148. var w2 = qw * 2;
  3149. uvx *= w2;
  3150. uvy *= w2;
  3151. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3152. uuvx *= 2;
  3153. uuvy *= 2;
  3154. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3155. out[0] = x + uvx + uuvx;
  3156. out[1] = y + uvy + uuvy;
  3157. out[2] = z + uvz + uuvz;
  3158. return out;
  3159. }
  3160. /**
  3161. * Rotate a 3D vector around the x-axis
  3162. * @param {vec3} out The receiving vec3
  3163. * @param {ReadonlyVec3} a The vec3 point to rotate
  3164. * @param {ReadonlyVec3} b The origin of the rotation
  3165. * @param {Number} rad The angle of rotation in radians
  3166. * @returns {vec3} out
  3167. */
  3168. function rotateX$2(out, a, b, rad) {
  3169. var p = [],
  3170. r = []; //Translate point to the origin
  3171. p[0] = a[0] - b[0];
  3172. p[1] = a[1] - b[1];
  3173. p[2] = a[2] - b[2]; //perform rotation
  3174. r[0] = p[0];
  3175. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3176. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3177. out[0] = r[0] + b[0];
  3178. out[1] = r[1] + b[1];
  3179. out[2] = r[2] + b[2];
  3180. return out;
  3181. }
  3182. /**
  3183. * Rotate a 3D vector around the y-axis
  3184. * @param {vec3} out The receiving vec3
  3185. * @param {ReadonlyVec3} a The vec3 point to rotate
  3186. * @param {ReadonlyVec3} b The origin of the rotation
  3187. * @param {Number} rad The angle of rotation in radians
  3188. * @returns {vec3} out
  3189. */
  3190. function rotateY$2(out, a, b, rad) {
  3191. var p = [],
  3192. r = []; //Translate point to the origin
  3193. p[0] = a[0] - b[0];
  3194. p[1] = a[1] - b[1];
  3195. p[2] = a[2] - b[2]; //perform rotation
  3196. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3197. r[1] = p[1];
  3198. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3199. out[0] = r[0] + b[0];
  3200. out[1] = r[1] + b[1];
  3201. out[2] = r[2] + b[2];
  3202. return out;
  3203. }
  3204. /**
  3205. * Rotate a 3D vector around the z-axis
  3206. * @param {vec3} out The receiving vec3
  3207. * @param {ReadonlyVec3} a The vec3 point to rotate
  3208. * @param {ReadonlyVec3} b The origin of the rotation
  3209. * @param {Number} rad The angle of rotation in radians
  3210. * @returns {vec3} out
  3211. */
  3212. function rotateZ$2(out, a, b, rad) {
  3213. var p = [],
  3214. r = []; //Translate point to the origin
  3215. p[0] = a[0] - b[0];
  3216. p[1] = a[1] - b[1];
  3217. p[2] = a[2] - b[2]; //perform rotation
  3218. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3219. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3220. r[2] = p[2]; //translate to correct position
  3221. out[0] = r[0] + b[0];
  3222. out[1] = r[1] + b[1];
  3223. out[2] = r[2] + b[2];
  3224. return out;
  3225. }
  3226. /**
  3227. * Get the angle between two 3D vectors
  3228. * @param {ReadonlyVec3} a The first operand
  3229. * @param {ReadonlyVec3} b The second operand
  3230. * @returns {Number} The angle in radians
  3231. */
  3232. function angle(a, b) {
  3233. var ax = a[0],
  3234. ay = a[1],
  3235. az = a[2],
  3236. bx = b[0],
  3237. by = b[1],
  3238. bz = b[2],
  3239. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3240. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3241. mag = mag1 * mag2,
  3242. cosine = mag && dot$2(a, b) / mag;
  3243. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3244. }
  3245. /**
  3246. * Alias for {@link vec3.length}
  3247. * @function
  3248. */
  3249. var len = length$2;
  3250. /**
  3251. * Perform some operation over an array of vec3s.
  3252. *
  3253. * @param {Array} a the array of vectors to iterate over
  3254. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3255. * @param {Number} offset Number of elements to skip at the beginning of the array
  3256. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3257. * @param {Function} fn Function to call for each vector in the array
  3258. * @param {Object} [arg] additional argument to pass to fn
  3259. * @returns {Array} a
  3260. * @function
  3261. */
  3262. (function () {
  3263. var vec = create$3();
  3264. return function (a, stride, offset, count, fn, arg) {
  3265. var i, l;
  3266. if (!stride) {
  3267. stride = 3;
  3268. }
  3269. if (!offset) {
  3270. offset = 0;
  3271. }
  3272. if (count) {
  3273. l = Math.min(count * stride + offset, a.length);
  3274. } else {
  3275. l = a.length;
  3276. }
  3277. for (i = offset; i < l; i += stride) {
  3278. vec[0] = a[i];
  3279. vec[1] = a[i + 1];
  3280. vec[2] = a[i + 2];
  3281. fn(vec, vec, arg);
  3282. a[i] = vec[0];
  3283. a[i + 1] = vec[1];
  3284. a[i + 2] = vec[2];
  3285. }
  3286. return a;
  3287. };
  3288. })();
  3289. const ORIGIN = [0, 0, 0];
  3290. const constants$2 = {};
  3291. class Vector3 extends Vector {
  3292. static get ZERO() {
  3293. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3294. }
  3295. constructor(x = 0, y = 0, z = 0) {
  3296. super(-0, -0, -0);
  3297. if (arguments.length === 1 && isArray(x)) {
  3298. this.copy(x);
  3299. } else {
  3300. if (config.debug) {
  3301. checkNumber(x);
  3302. checkNumber(y);
  3303. checkNumber(z);
  3304. }
  3305. this[0] = x;
  3306. this[1] = y;
  3307. this[2] = z;
  3308. }
  3309. }
  3310. set(x, y, z) {
  3311. this[0] = x;
  3312. this[1] = y;
  3313. this[2] = z;
  3314. return this.check();
  3315. }
  3316. copy(array) {
  3317. this[0] = array[0];
  3318. this[1] = array[1];
  3319. this[2] = array[2];
  3320. return this.check();
  3321. }
  3322. fromObject(object) {
  3323. if (config.debug) {
  3324. checkNumber(object.x);
  3325. checkNumber(object.y);
  3326. checkNumber(object.z);
  3327. }
  3328. this[0] = object.x;
  3329. this[1] = object.y;
  3330. this[2] = object.z;
  3331. return this.check();
  3332. }
  3333. toObject(object) {
  3334. object.x = this[0];
  3335. object.y = this[1];
  3336. object.z = this[2];
  3337. return object;
  3338. }
  3339. get ELEMENTS() {
  3340. return 3;
  3341. }
  3342. get z() {
  3343. return this[2];
  3344. }
  3345. set z(value) {
  3346. this[2] = checkNumber(value);
  3347. }
  3348. angle(vector) {
  3349. return angle(this, vector);
  3350. }
  3351. cross(vector) {
  3352. cross(this, this, vector);
  3353. return this.check();
  3354. }
  3355. rotateX({
  3356. radians,
  3357. origin = ORIGIN
  3358. }) {
  3359. rotateX$2(this, this, origin, radians);
  3360. return this.check();
  3361. }
  3362. rotateY({
  3363. radians,
  3364. origin = ORIGIN
  3365. }) {
  3366. rotateY$2(this, this, origin, radians);
  3367. return this.check();
  3368. }
  3369. rotateZ({
  3370. radians,
  3371. origin = ORIGIN
  3372. }) {
  3373. rotateZ$2(this, this, origin, radians);
  3374. return this.check();
  3375. }
  3376. transform(matrix4) {
  3377. return this.transformAsPoint(matrix4);
  3378. }
  3379. transformAsPoint(matrix4) {
  3380. transformMat4$1(this, this, matrix4);
  3381. return this.check();
  3382. }
  3383. transformAsVector(matrix4) {
  3384. vec3_transformMat4AsVector(this, this, matrix4);
  3385. return this.check();
  3386. }
  3387. transformByMatrix3(matrix3) {
  3388. transformMat3(this, this, matrix3);
  3389. return this.check();
  3390. }
  3391. transformByMatrix2(matrix2) {
  3392. vec3_transformMat2(this, this, matrix2);
  3393. return this.check();
  3394. }
  3395. transformByQuaternion(quaternion) {
  3396. transformQuat$1(this, this, quaternion);
  3397. return this.check();
  3398. }
  3399. }
  3400. class Matrix extends MathArray {
  3401. get ELEMENTS() {
  3402. assert$4(false);
  3403. return 0;
  3404. }
  3405. get RANK() {
  3406. assert$4(false);
  3407. return 0;
  3408. }
  3409. toString() {
  3410. let string = '[';
  3411. if (config.printRowMajor) {
  3412. string += 'row-major:';
  3413. for (let row = 0; row < this.RANK; ++row) {
  3414. for (let col = 0; col < this.RANK; ++col) {
  3415. string += " ".concat(this[col * this.RANK + row]);
  3416. }
  3417. }
  3418. } else {
  3419. string += 'column-major:';
  3420. for (let i = 0; i < this.ELEMENTS; ++i) {
  3421. string += " ".concat(this[i]);
  3422. }
  3423. }
  3424. string += ']';
  3425. return string;
  3426. }
  3427. getElementIndex(row, col) {
  3428. return col * this.RANK + row;
  3429. }
  3430. getElement(row, col) {
  3431. return this[col * this.RANK + row];
  3432. }
  3433. setElement(row, col, value) {
  3434. this[col * this.RANK + row] = checkNumber(value);
  3435. return this;
  3436. }
  3437. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3438. const firstIndex = columnIndex * this.RANK;
  3439. for (let i = 0; i < this.RANK; ++i) {
  3440. result[i] = this[firstIndex + i];
  3441. }
  3442. return result;
  3443. }
  3444. setColumn(columnIndex, columnVector) {
  3445. const firstIndex = columnIndex * this.RANK;
  3446. for (let i = 0; i < this.RANK; ++i) {
  3447. this[firstIndex + i] = columnVector[i];
  3448. }
  3449. return this;
  3450. }
  3451. }
  3452. /**
  3453. * 3x3 Matrix
  3454. * @module mat3
  3455. */
  3456. /**
  3457. * Creates a new identity mat3
  3458. *
  3459. * @returns {mat3} a new 3x3 matrix
  3460. */
  3461. function create$2() {
  3462. var out = new ARRAY_TYPE(9);
  3463. if (ARRAY_TYPE != Float32Array) {
  3464. out[1] = 0;
  3465. out[2] = 0;
  3466. out[3] = 0;
  3467. out[5] = 0;
  3468. out[6] = 0;
  3469. out[7] = 0;
  3470. }
  3471. out[0] = 1;
  3472. out[4] = 1;
  3473. out[8] = 1;
  3474. return out;
  3475. }
  3476. /**
  3477. * Transpose the values of a mat3
  3478. *
  3479. * @param {mat3} out the receiving matrix
  3480. * @param {ReadonlyMat3} a the source matrix
  3481. * @returns {mat3} out
  3482. */
  3483. function transpose$1(out, a) {
  3484. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3485. if (out === a) {
  3486. var a01 = a[1],
  3487. a02 = a[2],
  3488. a12 = a[5];
  3489. out[1] = a[3];
  3490. out[2] = a[6];
  3491. out[3] = a01;
  3492. out[5] = a[7];
  3493. out[6] = a02;
  3494. out[7] = a12;
  3495. } else {
  3496. out[0] = a[0];
  3497. out[1] = a[3];
  3498. out[2] = a[6];
  3499. out[3] = a[1];
  3500. out[4] = a[4];
  3501. out[5] = a[7];
  3502. out[6] = a[2];
  3503. out[7] = a[5];
  3504. out[8] = a[8];
  3505. }
  3506. return out;
  3507. }
  3508. /**
  3509. * Inverts a mat3
  3510. *
  3511. * @param {mat3} out the receiving matrix
  3512. * @param {ReadonlyMat3} a the source matrix
  3513. * @returns {mat3} out
  3514. */
  3515. function invert$2(out, a) {
  3516. var a00 = a[0],
  3517. a01 = a[1],
  3518. a02 = a[2];
  3519. var a10 = a[3],
  3520. a11 = a[4],
  3521. a12 = a[5];
  3522. var a20 = a[6],
  3523. a21 = a[7],
  3524. a22 = a[8];
  3525. var b01 = a22 * a11 - a12 * a21;
  3526. var b11 = -a22 * a10 + a12 * a20;
  3527. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3528. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3529. if (!det) {
  3530. return null;
  3531. }
  3532. det = 1.0 / det;
  3533. out[0] = b01 * det;
  3534. out[1] = (-a22 * a01 + a02 * a21) * det;
  3535. out[2] = (a12 * a01 - a02 * a11) * det;
  3536. out[3] = b11 * det;
  3537. out[4] = (a22 * a00 - a02 * a20) * det;
  3538. out[5] = (-a12 * a00 + a02 * a10) * det;
  3539. out[6] = b21 * det;
  3540. out[7] = (-a21 * a00 + a01 * a20) * det;
  3541. out[8] = (a11 * a00 - a01 * a10) * det;
  3542. return out;
  3543. }
  3544. /**
  3545. * Calculates the determinant of a mat3
  3546. *
  3547. * @param {ReadonlyMat3} a the source matrix
  3548. * @returns {Number} determinant of a
  3549. */
  3550. function determinant$1(a) {
  3551. var a00 = a[0],
  3552. a01 = a[1],
  3553. a02 = a[2];
  3554. var a10 = a[3],
  3555. a11 = a[4],
  3556. a12 = a[5];
  3557. var a20 = a[6],
  3558. a21 = a[7],
  3559. a22 = a[8];
  3560. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3561. }
  3562. /**
  3563. * Multiplies two mat3's
  3564. *
  3565. * @param {mat3} out the receiving matrix
  3566. * @param {ReadonlyMat3} a the first operand
  3567. * @param {ReadonlyMat3} b the second operand
  3568. * @returns {mat3} out
  3569. */
  3570. function multiply$2(out, a, b) {
  3571. var a00 = a[0],
  3572. a01 = a[1],
  3573. a02 = a[2];
  3574. var a10 = a[3],
  3575. a11 = a[4],
  3576. a12 = a[5];
  3577. var a20 = a[6],
  3578. a21 = a[7],
  3579. a22 = a[8];
  3580. var b00 = b[0],
  3581. b01 = b[1],
  3582. b02 = b[2];
  3583. var b10 = b[3],
  3584. b11 = b[4],
  3585. b12 = b[5];
  3586. var b20 = b[6],
  3587. b21 = b[7],
  3588. b22 = b[8];
  3589. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3590. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3591. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3592. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3593. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3594. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3595. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3596. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3597. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3598. return out;
  3599. }
  3600. /**
  3601. * Translate a mat3 by the given vector
  3602. *
  3603. * @param {mat3} out the receiving matrix
  3604. * @param {ReadonlyMat3} a the matrix to translate
  3605. * @param {ReadonlyVec2} v vector to translate by
  3606. * @returns {mat3} out
  3607. */
  3608. function translate$1(out, a, v) {
  3609. var a00 = a[0],
  3610. a01 = a[1],
  3611. a02 = a[2],
  3612. a10 = a[3],
  3613. a11 = a[4],
  3614. a12 = a[5],
  3615. a20 = a[6],
  3616. a21 = a[7],
  3617. a22 = a[8],
  3618. x = v[0],
  3619. y = v[1];
  3620. out[0] = a00;
  3621. out[1] = a01;
  3622. out[2] = a02;
  3623. out[3] = a10;
  3624. out[4] = a11;
  3625. out[5] = a12;
  3626. out[6] = x * a00 + y * a10 + a20;
  3627. out[7] = x * a01 + y * a11 + a21;
  3628. out[8] = x * a02 + y * a12 + a22;
  3629. return out;
  3630. }
  3631. /**
  3632. * Rotates a mat3 by the given angle
  3633. *
  3634. * @param {mat3} out the receiving matrix
  3635. * @param {ReadonlyMat3} a the matrix to rotate
  3636. * @param {Number} rad the angle to rotate the matrix by
  3637. * @returns {mat3} out
  3638. */
  3639. function rotate$1(out, a, rad) {
  3640. var a00 = a[0],
  3641. a01 = a[1],
  3642. a02 = a[2],
  3643. a10 = a[3],
  3644. a11 = a[4],
  3645. a12 = a[5],
  3646. a20 = a[6],
  3647. a21 = a[7],
  3648. a22 = a[8],
  3649. s = Math.sin(rad),
  3650. c = Math.cos(rad);
  3651. out[0] = c * a00 + s * a10;
  3652. out[1] = c * a01 + s * a11;
  3653. out[2] = c * a02 + s * a12;
  3654. out[3] = c * a10 - s * a00;
  3655. out[4] = c * a11 - s * a01;
  3656. out[5] = c * a12 - s * a02;
  3657. out[6] = a20;
  3658. out[7] = a21;
  3659. out[8] = a22;
  3660. return out;
  3661. }
  3662. /**
  3663. * Scales the mat3 by the dimensions in the given vec2
  3664. *
  3665. * @param {mat3} out the receiving matrix
  3666. * @param {ReadonlyMat3} a the matrix to rotate
  3667. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3668. * @returns {mat3} out
  3669. **/
  3670. function scale$3(out, a, v) {
  3671. var x = v[0],
  3672. y = v[1];
  3673. out[0] = x * a[0];
  3674. out[1] = x * a[1];
  3675. out[2] = x * a[2];
  3676. out[3] = y * a[3];
  3677. out[4] = y * a[4];
  3678. out[5] = y * a[5];
  3679. out[6] = a[6];
  3680. out[7] = a[7];
  3681. out[8] = a[8];
  3682. return out;
  3683. }
  3684. /**
  3685. * Calculates a 3x3 matrix from the given quaternion
  3686. *
  3687. * @param {mat3} out mat3 receiving operation result
  3688. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3689. *
  3690. * @returns {mat3} out
  3691. */
  3692. function fromQuat$1(out, q) {
  3693. var x = q[0],
  3694. y = q[1],
  3695. z = q[2],
  3696. w = q[3];
  3697. var x2 = x + x;
  3698. var y2 = y + y;
  3699. var z2 = z + z;
  3700. var xx = x * x2;
  3701. var yx = y * x2;
  3702. var yy = y * y2;
  3703. var zx = z * x2;
  3704. var zy = z * y2;
  3705. var zz = z * z2;
  3706. var wx = w * x2;
  3707. var wy = w * y2;
  3708. var wz = w * z2;
  3709. out[0] = 1 - yy - zz;
  3710. out[3] = yx - wz;
  3711. out[6] = zx + wy;
  3712. out[1] = yx + wz;
  3713. out[4] = 1 - xx - zz;
  3714. out[7] = zy - wx;
  3715. out[2] = zx - wy;
  3716. out[5] = zy + wx;
  3717. out[8] = 1 - xx - yy;
  3718. return out;
  3719. }
  3720. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3721. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3722. const INDICES$1 = Object.freeze({
  3723. COL0ROW0: 0,
  3724. COL0ROW1: 1,
  3725. COL0ROW2: 2,
  3726. COL1ROW0: 3,
  3727. COL1ROW1: 4,
  3728. COL1ROW2: 5,
  3729. COL2ROW0: 6,
  3730. COL2ROW1: 7,
  3731. COL2ROW2: 8
  3732. });
  3733. const constants$1 = {};
  3734. class Matrix3 extends Matrix {
  3735. static get IDENTITY() {
  3736. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3737. return constants$1.IDENTITY;
  3738. }
  3739. static get ZERO() {
  3740. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3741. return constants$1.ZERO;
  3742. }
  3743. get ELEMENTS() {
  3744. return 9;
  3745. }
  3746. get RANK() {
  3747. return 3;
  3748. }
  3749. get INDICES() {
  3750. return INDICES$1;
  3751. }
  3752. constructor(array) {
  3753. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3754. if (arguments.length === 1 && Array.isArray(array)) {
  3755. this.copy(array);
  3756. } else {
  3757. this.identity();
  3758. }
  3759. }
  3760. copy(array) {
  3761. this[0] = array[0];
  3762. this[1] = array[1];
  3763. this[2] = array[2];
  3764. this[3] = array[3];
  3765. this[4] = array[4];
  3766. this[5] = array[5];
  3767. this[6] = array[6];
  3768. this[7] = array[7];
  3769. this[8] = array[8];
  3770. return this.check();
  3771. }
  3772. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3773. this[0] = m00;
  3774. this[1] = m10;
  3775. this[2] = m20;
  3776. this[3] = m01;
  3777. this[4] = m11;
  3778. this[5] = m21;
  3779. this[6] = m02;
  3780. this[7] = m12;
  3781. this[8] = m22;
  3782. return this.check();
  3783. }
  3784. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3785. this[0] = m00;
  3786. this[1] = m10;
  3787. this[2] = m20;
  3788. this[3] = m01;
  3789. this[4] = m11;
  3790. this[5] = m21;
  3791. this[6] = m02;
  3792. this[7] = m12;
  3793. this[8] = m22;
  3794. return this.check();
  3795. }
  3796. determinant() {
  3797. return determinant$1(this);
  3798. }
  3799. identity() {
  3800. return this.copy(IDENTITY$1);
  3801. }
  3802. fromQuaternion(q) {
  3803. fromQuat$1(this, q);
  3804. return this.check();
  3805. }
  3806. transpose() {
  3807. transpose$1(this, this);
  3808. return this.check();
  3809. }
  3810. invert() {
  3811. invert$2(this, this);
  3812. return this.check();
  3813. }
  3814. multiplyLeft(a) {
  3815. multiply$2(this, a, this);
  3816. return this.check();
  3817. }
  3818. multiplyRight(a) {
  3819. multiply$2(this, this, a);
  3820. return this.check();
  3821. }
  3822. rotate(radians) {
  3823. rotate$1(this, this, radians);
  3824. return this.check();
  3825. }
  3826. scale(factor) {
  3827. if (Array.isArray(factor)) {
  3828. scale$3(this, this, factor);
  3829. } else {
  3830. scale$3(this, this, [factor, factor, factor]);
  3831. }
  3832. return this.check();
  3833. }
  3834. translate(vec) {
  3835. translate$1(this, this, vec);
  3836. return this.check();
  3837. }
  3838. transform(vector, result) {
  3839. switch (vector.length) {
  3840. case 2:
  3841. result = transformMat3$1(result || [-0, -0], vector, this);
  3842. break;
  3843. case 3:
  3844. result = transformMat3(result || [-0, -0, -0], vector, this);
  3845. break;
  3846. case 4:
  3847. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3848. break;
  3849. default:
  3850. throw new Error('Illegal vector');
  3851. }
  3852. checkVector(result, vector.length);
  3853. return result;
  3854. }
  3855. transformVector(vector, result) {
  3856. deprecated('Matrix3.transformVector');
  3857. return this.transform(vector, result);
  3858. }
  3859. transformVector2(vector, result) {
  3860. deprecated('Matrix3.transformVector');
  3861. return this.transform(vector, result);
  3862. }
  3863. transformVector3(vector, result) {
  3864. deprecated('Matrix3.transformVector');
  3865. return this.transform(vector, result);
  3866. }
  3867. }
  3868. /**
  3869. * Set a mat4 to the identity matrix
  3870. *
  3871. * @param {mat4} out the receiving matrix
  3872. * @returns {mat4} out
  3873. */
  3874. function identity$1(out) {
  3875. out[0] = 1;
  3876. out[1] = 0;
  3877. out[2] = 0;
  3878. out[3] = 0;
  3879. out[4] = 0;
  3880. out[5] = 1;
  3881. out[6] = 0;
  3882. out[7] = 0;
  3883. out[8] = 0;
  3884. out[9] = 0;
  3885. out[10] = 1;
  3886. out[11] = 0;
  3887. out[12] = 0;
  3888. out[13] = 0;
  3889. out[14] = 0;
  3890. out[15] = 1;
  3891. return out;
  3892. }
  3893. /**
  3894. * Transpose the values of a mat4
  3895. *
  3896. * @param {mat4} out the receiving matrix
  3897. * @param {ReadonlyMat4} a the source matrix
  3898. * @returns {mat4} out
  3899. */
  3900. function transpose(out, a) {
  3901. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3902. if (out === a) {
  3903. var a01 = a[1],
  3904. a02 = a[2],
  3905. a03 = a[3];
  3906. var a12 = a[6],
  3907. a13 = a[7];
  3908. var a23 = a[11];
  3909. out[1] = a[4];
  3910. out[2] = a[8];
  3911. out[3] = a[12];
  3912. out[4] = a01;
  3913. out[6] = a[9];
  3914. out[7] = a[13];
  3915. out[8] = a02;
  3916. out[9] = a12;
  3917. out[11] = a[14];
  3918. out[12] = a03;
  3919. out[13] = a13;
  3920. out[14] = a23;
  3921. } else {
  3922. out[0] = a[0];
  3923. out[1] = a[4];
  3924. out[2] = a[8];
  3925. out[3] = a[12];
  3926. out[4] = a[1];
  3927. out[5] = a[5];
  3928. out[6] = a[9];
  3929. out[7] = a[13];
  3930. out[8] = a[2];
  3931. out[9] = a[6];
  3932. out[10] = a[10];
  3933. out[11] = a[14];
  3934. out[12] = a[3];
  3935. out[13] = a[7];
  3936. out[14] = a[11];
  3937. out[15] = a[15];
  3938. }
  3939. return out;
  3940. }
  3941. /**
  3942. * Inverts a mat4
  3943. *
  3944. * @param {mat4} out the receiving matrix
  3945. * @param {ReadonlyMat4} a the source matrix
  3946. * @returns {mat4} out
  3947. */
  3948. function invert$1(out, a) {
  3949. var a00 = a[0],
  3950. a01 = a[1],
  3951. a02 = a[2],
  3952. a03 = a[3];
  3953. var a10 = a[4],
  3954. a11 = a[5],
  3955. a12 = a[6],
  3956. a13 = a[7];
  3957. var a20 = a[8],
  3958. a21 = a[9],
  3959. a22 = a[10],
  3960. a23 = a[11];
  3961. var a30 = a[12],
  3962. a31 = a[13],
  3963. a32 = a[14],
  3964. a33 = a[15];
  3965. var b00 = a00 * a11 - a01 * a10;
  3966. var b01 = a00 * a12 - a02 * a10;
  3967. var b02 = a00 * a13 - a03 * a10;
  3968. var b03 = a01 * a12 - a02 * a11;
  3969. var b04 = a01 * a13 - a03 * a11;
  3970. var b05 = a02 * a13 - a03 * a12;
  3971. var b06 = a20 * a31 - a21 * a30;
  3972. var b07 = a20 * a32 - a22 * a30;
  3973. var b08 = a20 * a33 - a23 * a30;
  3974. var b09 = a21 * a32 - a22 * a31;
  3975. var b10 = a21 * a33 - a23 * a31;
  3976. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  3977. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  3978. if (!det) {
  3979. return null;
  3980. }
  3981. det = 1.0 / det;
  3982. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  3983. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  3984. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  3985. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  3986. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  3987. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  3988. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  3989. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  3990. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  3991. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  3992. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  3993. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  3994. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  3995. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  3996. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  3997. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  3998. return out;
  3999. }
  4000. /**
  4001. * Calculates the determinant of a mat4
  4002. *
  4003. * @param {ReadonlyMat4} a the source matrix
  4004. * @returns {Number} determinant of a
  4005. */
  4006. function determinant(a) {
  4007. var a00 = a[0],
  4008. a01 = a[1],
  4009. a02 = a[2],
  4010. a03 = a[3];
  4011. var a10 = a[4],
  4012. a11 = a[5],
  4013. a12 = a[6],
  4014. a13 = a[7];
  4015. var a20 = a[8],
  4016. a21 = a[9],
  4017. a22 = a[10],
  4018. a23 = a[11];
  4019. var a30 = a[12],
  4020. a31 = a[13],
  4021. a32 = a[14],
  4022. a33 = a[15];
  4023. var b00 = a00 * a11 - a01 * a10;
  4024. var b01 = a00 * a12 - a02 * a10;
  4025. var b02 = a00 * a13 - a03 * a10;
  4026. var b03 = a01 * a12 - a02 * a11;
  4027. var b04 = a01 * a13 - a03 * a11;
  4028. var b05 = a02 * a13 - a03 * a12;
  4029. var b06 = a20 * a31 - a21 * a30;
  4030. var b07 = a20 * a32 - a22 * a30;
  4031. var b08 = a20 * a33 - a23 * a30;
  4032. var b09 = a21 * a32 - a22 * a31;
  4033. var b10 = a21 * a33 - a23 * a31;
  4034. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4035. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4036. }
  4037. /**
  4038. * Multiplies two mat4s
  4039. *
  4040. * @param {mat4} out the receiving matrix
  4041. * @param {ReadonlyMat4} a the first operand
  4042. * @param {ReadonlyMat4} b the second operand
  4043. * @returns {mat4} out
  4044. */
  4045. function multiply$1(out, a, b) {
  4046. var a00 = a[0],
  4047. a01 = a[1],
  4048. a02 = a[2],
  4049. a03 = a[3];
  4050. var a10 = a[4],
  4051. a11 = a[5],
  4052. a12 = a[6],
  4053. a13 = a[7];
  4054. var a20 = a[8],
  4055. a21 = a[9],
  4056. a22 = a[10],
  4057. a23 = a[11];
  4058. var a30 = a[12],
  4059. a31 = a[13],
  4060. a32 = a[14],
  4061. a33 = a[15]; // Cache only the current line of the second matrix
  4062. var b0 = b[0],
  4063. b1 = b[1],
  4064. b2 = b[2],
  4065. b3 = b[3];
  4066. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4067. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4068. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4069. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4070. b0 = b[4];
  4071. b1 = b[5];
  4072. b2 = b[6];
  4073. b3 = b[7];
  4074. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4075. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4076. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4077. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4078. b0 = b[8];
  4079. b1 = b[9];
  4080. b2 = b[10];
  4081. b3 = b[11];
  4082. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4083. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4084. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4085. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4086. b0 = b[12];
  4087. b1 = b[13];
  4088. b2 = b[14];
  4089. b3 = b[15];
  4090. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4091. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4092. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4093. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4094. return out;
  4095. }
  4096. /**
  4097. * Translate a mat4 by the given vector
  4098. *
  4099. * @param {mat4} out the receiving matrix
  4100. * @param {ReadonlyMat4} a the matrix to translate
  4101. * @param {ReadonlyVec3} v vector to translate by
  4102. * @returns {mat4} out
  4103. */
  4104. function translate(out, a, v) {
  4105. var x = v[0],
  4106. y = v[1],
  4107. z = v[2];
  4108. var a00, a01, a02, a03;
  4109. var a10, a11, a12, a13;
  4110. var a20, a21, a22, a23;
  4111. if (a === out) {
  4112. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4113. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4114. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4115. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4116. } else {
  4117. a00 = a[0];
  4118. a01 = a[1];
  4119. a02 = a[2];
  4120. a03 = a[3];
  4121. a10 = a[4];
  4122. a11 = a[5];
  4123. a12 = a[6];
  4124. a13 = a[7];
  4125. a20 = a[8];
  4126. a21 = a[9];
  4127. a22 = a[10];
  4128. a23 = a[11];
  4129. out[0] = a00;
  4130. out[1] = a01;
  4131. out[2] = a02;
  4132. out[3] = a03;
  4133. out[4] = a10;
  4134. out[5] = a11;
  4135. out[6] = a12;
  4136. out[7] = a13;
  4137. out[8] = a20;
  4138. out[9] = a21;
  4139. out[10] = a22;
  4140. out[11] = a23;
  4141. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4142. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4143. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4144. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4145. }
  4146. return out;
  4147. }
  4148. /**
  4149. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4150. *
  4151. * @param {mat4} out the receiving matrix
  4152. * @param {ReadonlyMat4} a the matrix to scale
  4153. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4154. * @returns {mat4} out
  4155. **/
  4156. function scale$2(out, a, v) {
  4157. var x = v[0],
  4158. y = v[1],
  4159. z = v[2];
  4160. out[0] = a[0] * x;
  4161. out[1] = a[1] * x;
  4162. out[2] = a[2] * x;
  4163. out[3] = a[3] * x;
  4164. out[4] = a[4] * y;
  4165. out[5] = a[5] * y;
  4166. out[6] = a[6] * y;
  4167. out[7] = a[7] * y;
  4168. out[8] = a[8] * z;
  4169. out[9] = a[9] * z;
  4170. out[10] = a[10] * z;
  4171. out[11] = a[11] * z;
  4172. out[12] = a[12];
  4173. out[13] = a[13];
  4174. out[14] = a[14];
  4175. out[15] = a[15];
  4176. return out;
  4177. }
  4178. /**
  4179. * Rotates a mat4 by the given angle around the given axis
  4180. *
  4181. * @param {mat4} out the receiving matrix
  4182. * @param {ReadonlyMat4} a the matrix to rotate
  4183. * @param {Number} rad the angle to rotate the matrix by
  4184. * @param {ReadonlyVec3} axis the axis to rotate around
  4185. * @returns {mat4} out
  4186. */
  4187. function rotate(out, a, rad, axis) {
  4188. var x = axis[0],
  4189. y = axis[1],
  4190. z = axis[2];
  4191. var len = Math.hypot(x, y, z);
  4192. var s, c, t;
  4193. var a00, a01, a02, a03;
  4194. var a10, a11, a12, a13;
  4195. var a20, a21, a22, a23;
  4196. var b00, b01, b02;
  4197. var b10, b11, b12;
  4198. var b20, b21, b22;
  4199. if (len < EPSILON) {
  4200. return null;
  4201. }
  4202. len = 1 / len;
  4203. x *= len;
  4204. y *= len;
  4205. z *= len;
  4206. s = Math.sin(rad);
  4207. c = Math.cos(rad);
  4208. t = 1 - c;
  4209. a00 = a[0];
  4210. a01 = a[1];
  4211. a02 = a[2];
  4212. a03 = a[3];
  4213. a10 = a[4];
  4214. a11 = a[5];
  4215. a12 = a[6];
  4216. a13 = a[7];
  4217. a20 = a[8];
  4218. a21 = a[9];
  4219. a22 = a[10];
  4220. a23 = a[11]; // Construct the elements of the rotation matrix
  4221. b00 = x * x * t + c;
  4222. b01 = y * x * t + z * s;
  4223. b02 = z * x * t - y * s;
  4224. b10 = x * y * t - z * s;
  4225. b11 = y * y * t + c;
  4226. b12 = z * y * t + x * s;
  4227. b20 = x * z * t + y * s;
  4228. b21 = y * z * t - x * s;
  4229. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4230. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4231. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4232. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4233. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4234. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4235. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4236. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4237. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4238. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4239. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4240. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4241. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4242. if (a !== out) {
  4243. // If the source and destination differ, copy the unchanged last row
  4244. out[12] = a[12];
  4245. out[13] = a[13];
  4246. out[14] = a[14];
  4247. out[15] = a[15];
  4248. }
  4249. return out;
  4250. }
  4251. /**
  4252. * Rotates a matrix by the given angle around the X axis
  4253. *
  4254. * @param {mat4} out the receiving matrix
  4255. * @param {ReadonlyMat4} a the matrix to rotate
  4256. * @param {Number} rad the angle to rotate the matrix by
  4257. * @returns {mat4} out
  4258. */
  4259. function rotateX$1(out, a, rad) {
  4260. var s = Math.sin(rad);
  4261. var c = Math.cos(rad);
  4262. var a10 = a[4];
  4263. var a11 = a[5];
  4264. var a12 = a[6];
  4265. var a13 = a[7];
  4266. var a20 = a[8];
  4267. var a21 = a[9];
  4268. var a22 = a[10];
  4269. var a23 = a[11];
  4270. if (a !== out) {
  4271. // If the source and destination differ, copy the unchanged rows
  4272. out[0] = a[0];
  4273. out[1] = a[1];
  4274. out[2] = a[2];
  4275. out[3] = a[3];
  4276. out[12] = a[12];
  4277. out[13] = a[13];
  4278. out[14] = a[14];
  4279. out[15] = a[15];
  4280. } // Perform axis-specific matrix multiplication
  4281. out[4] = a10 * c + a20 * s;
  4282. out[5] = a11 * c + a21 * s;
  4283. out[6] = a12 * c + a22 * s;
  4284. out[7] = a13 * c + a23 * s;
  4285. out[8] = a20 * c - a10 * s;
  4286. out[9] = a21 * c - a11 * s;
  4287. out[10] = a22 * c - a12 * s;
  4288. out[11] = a23 * c - a13 * s;
  4289. return out;
  4290. }
  4291. /**
  4292. * Rotates a matrix by the given angle around the Y axis
  4293. *
  4294. * @param {mat4} out the receiving matrix
  4295. * @param {ReadonlyMat4} a the matrix to rotate
  4296. * @param {Number} rad the angle to rotate the matrix by
  4297. * @returns {mat4} out
  4298. */
  4299. function rotateY$1(out, a, rad) {
  4300. var s = Math.sin(rad);
  4301. var c = Math.cos(rad);
  4302. var a00 = a[0];
  4303. var a01 = a[1];
  4304. var a02 = a[2];
  4305. var a03 = a[3];
  4306. var a20 = a[8];
  4307. var a21 = a[9];
  4308. var a22 = a[10];
  4309. var a23 = a[11];
  4310. if (a !== out) {
  4311. // If the source and destination differ, copy the unchanged rows
  4312. out[4] = a[4];
  4313. out[5] = a[5];
  4314. out[6] = a[6];
  4315. out[7] = a[7];
  4316. out[12] = a[12];
  4317. out[13] = a[13];
  4318. out[14] = a[14];
  4319. out[15] = a[15];
  4320. } // Perform axis-specific matrix multiplication
  4321. out[0] = a00 * c - a20 * s;
  4322. out[1] = a01 * c - a21 * s;
  4323. out[2] = a02 * c - a22 * s;
  4324. out[3] = a03 * c - a23 * s;
  4325. out[8] = a00 * s + a20 * c;
  4326. out[9] = a01 * s + a21 * c;
  4327. out[10] = a02 * s + a22 * c;
  4328. out[11] = a03 * s + a23 * c;
  4329. return out;
  4330. }
  4331. /**
  4332. * Rotates a matrix by the given angle around the Z axis
  4333. *
  4334. * @param {mat4} out the receiving matrix
  4335. * @param {ReadonlyMat4} a the matrix to rotate
  4336. * @param {Number} rad the angle to rotate the matrix by
  4337. * @returns {mat4} out
  4338. */
  4339. function rotateZ$1(out, a, rad) {
  4340. var s = Math.sin(rad);
  4341. var c = Math.cos(rad);
  4342. var a00 = a[0];
  4343. var a01 = a[1];
  4344. var a02 = a[2];
  4345. var a03 = a[3];
  4346. var a10 = a[4];
  4347. var a11 = a[5];
  4348. var a12 = a[6];
  4349. var a13 = a[7];
  4350. if (a !== out) {
  4351. // If the source and destination differ, copy the unchanged last row
  4352. out[8] = a[8];
  4353. out[9] = a[9];
  4354. out[10] = a[10];
  4355. out[11] = a[11];
  4356. out[12] = a[12];
  4357. out[13] = a[13];
  4358. out[14] = a[14];
  4359. out[15] = a[15];
  4360. } // Perform axis-specific matrix multiplication
  4361. out[0] = a00 * c + a10 * s;
  4362. out[1] = a01 * c + a11 * s;
  4363. out[2] = a02 * c + a12 * s;
  4364. out[3] = a03 * c + a13 * s;
  4365. out[4] = a10 * c - a00 * s;
  4366. out[5] = a11 * c - a01 * s;
  4367. out[6] = a12 * c - a02 * s;
  4368. out[7] = a13 * c - a03 * s;
  4369. return out;
  4370. }
  4371. /**
  4372. * Returns the scaling factor component of a transformation
  4373. * matrix. If a matrix is built with fromRotationTranslationScale
  4374. * with a normalized Quaternion paramter, the returned vector will be
  4375. * the same as the scaling vector
  4376. * originally supplied.
  4377. * @param {vec3} out Vector to receive scaling factor component
  4378. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4379. * @return {vec3} out
  4380. */
  4381. function getScaling(out, mat) {
  4382. var m11 = mat[0];
  4383. var m12 = mat[1];
  4384. var m13 = mat[2];
  4385. var m21 = mat[4];
  4386. var m22 = mat[5];
  4387. var m23 = mat[6];
  4388. var m31 = mat[8];
  4389. var m32 = mat[9];
  4390. var m33 = mat[10];
  4391. out[0] = Math.hypot(m11, m12, m13);
  4392. out[1] = Math.hypot(m21, m22, m23);
  4393. out[2] = Math.hypot(m31, m32, m33);
  4394. return out;
  4395. }
  4396. /**
  4397. * Calculates a 4x4 matrix from the given quaternion
  4398. *
  4399. * @param {mat4} out mat4 receiving operation result
  4400. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4401. *
  4402. * @returns {mat4} out
  4403. */
  4404. function fromQuat(out, q) {
  4405. var x = q[0],
  4406. y = q[1],
  4407. z = q[2],
  4408. w = q[3];
  4409. var x2 = x + x;
  4410. var y2 = y + y;
  4411. var z2 = z + z;
  4412. var xx = x * x2;
  4413. var yx = y * x2;
  4414. var yy = y * y2;
  4415. var zx = z * x2;
  4416. var zy = z * y2;
  4417. var zz = z * z2;
  4418. var wx = w * x2;
  4419. var wy = w * y2;
  4420. var wz = w * z2;
  4421. out[0] = 1 - yy - zz;
  4422. out[1] = yx + wz;
  4423. out[2] = zx - wy;
  4424. out[3] = 0;
  4425. out[4] = yx - wz;
  4426. out[5] = 1 - xx - zz;
  4427. out[6] = zy + wx;
  4428. out[7] = 0;
  4429. out[8] = zx + wy;
  4430. out[9] = zy - wx;
  4431. out[10] = 1 - xx - yy;
  4432. out[11] = 0;
  4433. out[12] = 0;
  4434. out[13] = 0;
  4435. out[14] = 0;
  4436. out[15] = 1;
  4437. return out;
  4438. }
  4439. /**
  4440. * Generates a frustum matrix with the given bounds
  4441. *
  4442. * @param {mat4} out mat4 frustum matrix will be written into
  4443. * @param {Number} left Left bound of the frustum
  4444. * @param {Number} right Right bound of the frustum
  4445. * @param {Number} bottom Bottom bound of the frustum
  4446. * @param {Number} top Top bound of the frustum
  4447. * @param {Number} near Near bound of the frustum
  4448. * @param {Number} far Far bound of the frustum
  4449. * @returns {mat4} out
  4450. */
  4451. function frustum(out, left, right, bottom, top, near, far) {
  4452. var rl = 1 / (right - left);
  4453. var tb = 1 / (top - bottom);
  4454. var nf = 1 / (near - far);
  4455. out[0] = near * 2 * rl;
  4456. out[1] = 0;
  4457. out[2] = 0;
  4458. out[3] = 0;
  4459. out[4] = 0;
  4460. out[5] = near * 2 * tb;
  4461. out[6] = 0;
  4462. out[7] = 0;
  4463. out[8] = (right + left) * rl;
  4464. out[9] = (top + bottom) * tb;
  4465. out[10] = (far + near) * nf;
  4466. out[11] = -1;
  4467. out[12] = 0;
  4468. out[13] = 0;
  4469. out[14] = far * near * 2 * nf;
  4470. out[15] = 0;
  4471. return out;
  4472. }
  4473. /**
  4474. * Generates a perspective projection matrix with the given bounds.
  4475. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4476. *
  4477. * @param {mat4} out mat4 frustum matrix will be written into
  4478. * @param {number} fovy Vertical field of view in radians
  4479. * @param {number} aspect Aspect ratio. typically viewport width/height
  4480. * @param {number} near Near bound of the frustum
  4481. * @param {number} far Far bound of the frustum, can be null or Infinity
  4482. * @returns {mat4} out
  4483. */
  4484. function perspective(out, fovy, aspect, near, far) {
  4485. var f = 1.0 / Math.tan(fovy / 2),
  4486. nf;
  4487. out[0] = f / aspect;
  4488. out[1] = 0;
  4489. out[2] = 0;
  4490. out[3] = 0;
  4491. out[4] = 0;
  4492. out[5] = f;
  4493. out[6] = 0;
  4494. out[7] = 0;
  4495. out[8] = 0;
  4496. out[9] = 0;
  4497. out[11] = -1;
  4498. out[12] = 0;
  4499. out[13] = 0;
  4500. out[15] = 0;
  4501. if (far != null && far !== Infinity) {
  4502. nf = 1 / (near - far);
  4503. out[10] = (far + near) * nf;
  4504. out[14] = 2 * far * near * nf;
  4505. } else {
  4506. out[10] = -1;
  4507. out[14] = -2 * near;
  4508. }
  4509. return out;
  4510. }
  4511. /**
  4512. * Generates a orthogonal projection matrix with the given bounds
  4513. *
  4514. * @param {mat4} out mat4 frustum matrix will be written into
  4515. * @param {number} left Left bound of the frustum
  4516. * @param {number} right Right bound of the frustum
  4517. * @param {number} bottom Bottom bound of the frustum
  4518. * @param {number} top Top bound of the frustum
  4519. * @param {number} near Near bound of the frustum
  4520. * @param {number} far Far bound of the frustum
  4521. * @returns {mat4} out
  4522. */
  4523. function ortho(out, left, right, bottom, top, near, far) {
  4524. var lr = 1 / (left - right);
  4525. var bt = 1 / (bottom - top);
  4526. var nf = 1 / (near - far);
  4527. out[0] = -2 * lr;
  4528. out[1] = 0;
  4529. out[2] = 0;
  4530. out[3] = 0;
  4531. out[4] = 0;
  4532. out[5] = -2 * bt;
  4533. out[6] = 0;
  4534. out[7] = 0;
  4535. out[8] = 0;
  4536. out[9] = 0;
  4537. out[10] = 2 * nf;
  4538. out[11] = 0;
  4539. out[12] = (left + right) * lr;
  4540. out[13] = (top + bottom) * bt;
  4541. out[14] = (far + near) * nf;
  4542. out[15] = 1;
  4543. return out;
  4544. }
  4545. /**
  4546. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4547. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4548. *
  4549. * @param {mat4} out mat4 frustum matrix will be written into
  4550. * @param {ReadonlyVec3} eye Position of the viewer
  4551. * @param {ReadonlyVec3} center Point the viewer is looking at
  4552. * @param {ReadonlyVec3} up vec3 pointing up
  4553. * @returns {mat4} out
  4554. */
  4555. function lookAt(out, eye, center, up) {
  4556. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4557. var eyex = eye[0];
  4558. var eyey = eye[1];
  4559. var eyez = eye[2];
  4560. var upx = up[0];
  4561. var upy = up[1];
  4562. var upz = up[2];
  4563. var centerx = center[0];
  4564. var centery = center[1];
  4565. var centerz = center[2];
  4566. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4567. return identity$1(out);
  4568. }
  4569. z0 = eyex - centerx;
  4570. z1 = eyey - centery;
  4571. z2 = eyez - centerz;
  4572. len = 1 / Math.hypot(z0, z1, z2);
  4573. z0 *= len;
  4574. z1 *= len;
  4575. z2 *= len;
  4576. x0 = upy * z2 - upz * z1;
  4577. x1 = upz * z0 - upx * z2;
  4578. x2 = upx * z1 - upy * z0;
  4579. len = Math.hypot(x0, x1, x2);
  4580. if (!len) {
  4581. x0 = 0;
  4582. x1 = 0;
  4583. x2 = 0;
  4584. } else {
  4585. len = 1 / len;
  4586. x0 *= len;
  4587. x1 *= len;
  4588. x2 *= len;
  4589. }
  4590. y0 = z1 * x2 - z2 * x1;
  4591. y1 = z2 * x0 - z0 * x2;
  4592. y2 = z0 * x1 - z1 * x0;
  4593. len = Math.hypot(y0, y1, y2);
  4594. if (!len) {
  4595. y0 = 0;
  4596. y1 = 0;
  4597. y2 = 0;
  4598. } else {
  4599. len = 1 / len;
  4600. y0 *= len;
  4601. y1 *= len;
  4602. y2 *= len;
  4603. }
  4604. out[0] = x0;
  4605. out[1] = y0;
  4606. out[2] = z0;
  4607. out[3] = 0;
  4608. out[4] = x1;
  4609. out[5] = y1;
  4610. out[6] = z1;
  4611. out[7] = 0;
  4612. out[8] = x2;
  4613. out[9] = y2;
  4614. out[10] = z2;
  4615. out[11] = 0;
  4616. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4617. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4618. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4619. out[15] = 1;
  4620. return out;
  4621. }
  4622. /**
  4623. * 4 Dimensional Vector
  4624. * @module vec4
  4625. */
  4626. /**
  4627. * Creates a new, empty vec4
  4628. *
  4629. * @returns {vec4} a new 4D vector
  4630. */
  4631. function create$1() {
  4632. var out = new ARRAY_TYPE(4);
  4633. if (ARRAY_TYPE != Float32Array) {
  4634. out[0] = 0;
  4635. out[1] = 0;
  4636. out[2] = 0;
  4637. out[3] = 0;
  4638. }
  4639. return out;
  4640. }
  4641. /**
  4642. * Adds two vec4's
  4643. *
  4644. * @param {vec4} out the receiving vector
  4645. * @param {ReadonlyVec4} a the first operand
  4646. * @param {ReadonlyVec4} b the second operand
  4647. * @returns {vec4} out
  4648. */
  4649. function add$1(out, a, b) {
  4650. out[0] = a[0] + b[0];
  4651. out[1] = a[1] + b[1];
  4652. out[2] = a[2] + b[2];
  4653. out[3] = a[3] + b[3];
  4654. return out;
  4655. }
  4656. /**
  4657. * Scales a vec4 by a scalar number
  4658. *
  4659. * @param {vec4} out the receiving vector
  4660. * @param {ReadonlyVec4} a the vector to scale
  4661. * @param {Number} b amount to scale the vector by
  4662. * @returns {vec4} out
  4663. */
  4664. function scale$1(out, a, b) {
  4665. out[0] = a[0] * b;
  4666. out[1] = a[1] * b;
  4667. out[2] = a[2] * b;
  4668. out[3] = a[3] * b;
  4669. return out;
  4670. }
  4671. /**
  4672. * Calculates the length of a vec4
  4673. *
  4674. * @param {ReadonlyVec4} a vector to calculate length of
  4675. * @returns {Number} length of a
  4676. */
  4677. function length$1(a) {
  4678. var x = a[0];
  4679. var y = a[1];
  4680. var z = a[2];
  4681. var w = a[3];
  4682. return Math.hypot(x, y, z, w);
  4683. }
  4684. /**
  4685. * Calculates the squared length of a vec4
  4686. *
  4687. * @param {ReadonlyVec4} a vector to calculate squared length of
  4688. * @returns {Number} squared length of a
  4689. */
  4690. function squaredLength$1(a) {
  4691. var x = a[0];
  4692. var y = a[1];
  4693. var z = a[2];
  4694. var w = a[3];
  4695. return x * x + y * y + z * z + w * w;
  4696. }
  4697. /**
  4698. * Normalize a vec4
  4699. *
  4700. * @param {vec4} out the receiving vector
  4701. * @param {ReadonlyVec4} a vector to normalize
  4702. * @returns {vec4} out
  4703. */
  4704. function normalize$1(out, a) {
  4705. var x = a[0];
  4706. var y = a[1];
  4707. var z = a[2];
  4708. var w = a[3];
  4709. var len = x * x + y * y + z * z + w * w;
  4710. if (len > 0) {
  4711. len = 1 / Math.sqrt(len);
  4712. }
  4713. out[0] = x * len;
  4714. out[1] = y * len;
  4715. out[2] = z * len;
  4716. out[3] = w * len;
  4717. return out;
  4718. }
  4719. /**
  4720. * Calculates the dot product of two vec4's
  4721. *
  4722. * @param {ReadonlyVec4} a the first operand
  4723. * @param {ReadonlyVec4} b the second operand
  4724. * @returns {Number} dot product of a and b
  4725. */
  4726. function dot$1(a, b) {
  4727. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4728. }
  4729. /**
  4730. * Performs a linear interpolation between two vec4's
  4731. *
  4732. * @param {vec4} out the receiving vector
  4733. * @param {ReadonlyVec4} a the first operand
  4734. * @param {ReadonlyVec4} b the second operand
  4735. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4736. * @returns {vec4} out
  4737. */
  4738. function lerp$1(out, a, b, t) {
  4739. var ax = a[0];
  4740. var ay = a[1];
  4741. var az = a[2];
  4742. var aw = a[3];
  4743. out[0] = ax + t * (b[0] - ax);
  4744. out[1] = ay + t * (b[1] - ay);
  4745. out[2] = az + t * (b[2] - az);
  4746. out[3] = aw + t * (b[3] - aw);
  4747. return out;
  4748. }
  4749. /**
  4750. * Transforms the vec4 with a mat4.
  4751. *
  4752. * @param {vec4} out the receiving vector
  4753. * @param {ReadonlyVec4} a the vector to transform
  4754. * @param {ReadonlyMat4} m matrix to transform with
  4755. * @returns {vec4} out
  4756. */
  4757. function transformMat4(out, a, m) {
  4758. var x = a[0],
  4759. y = a[1],
  4760. z = a[2],
  4761. w = a[3];
  4762. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4763. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4764. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4765. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4766. return out;
  4767. }
  4768. /**
  4769. * Transforms the vec4 with a quat
  4770. *
  4771. * @param {vec4} out the receiving vector
  4772. * @param {ReadonlyVec4} a the vector to transform
  4773. * @param {ReadonlyQuat} q quaternion to transform with
  4774. * @returns {vec4} out
  4775. */
  4776. function transformQuat(out, a, q) {
  4777. var x = a[0],
  4778. y = a[1],
  4779. z = a[2];
  4780. var qx = q[0],
  4781. qy = q[1],
  4782. qz = q[2],
  4783. qw = q[3]; // calculate quat * vec
  4784. var ix = qw * x + qy * z - qz * y;
  4785. var iy = qw * y + qz * x - qx * z;
  4786. var iz = qw * z + qx * y - qy * x;
  4787. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4788. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4789. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4790. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4791. out[3] = a[3];
  4792. return out;
  4793. }
  4794. /**
  4795. * Perform some operation over an array of vec4s.
  4796. *
  4797. * @param {Array} a the array of vectors to iterate over
  4798. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4799. * @param {Number} offset Number of elements to skip at the beginning of the array
  4800. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4801. * @param {Function} fn Function to call for each vector in the array
  4802. * @param {Object} [arg] additional argument to pass to fn
  4803. * @returns {Array} a
  4804. * @function
  4805. */
  4806. (function () {
  4807. var vec = create$1();
  4808. return function (a, stride, offset, count, fn, arg) {
  4809. var i, l;
  4810. if (!stride) {
  4811. stride = 4;
  4812. }
  4813. if (!offset) {
  4814. offset = 0;
  4815. }
  4816. if (count) {
  4817. l = Math.min(count * stride + offset, a.length);
  4818. } else {
  4819. l = a.length;
  4820. }
  4821. for (i = offset; i < l; i += stride) {
  4822. vec[0] = a[i];
  4823. vec[1] = a[i + 1];
  4824. vec[2] = a[i + 2];
  4825. vec[3] = a[i + 3];
  4826. fn(vec, vec, arg);
  4827. a[i] = vec[0];
  4828. a[i + 1] = vec[1];
  4829. a[i + 2] = vec[2];
  4830. a[i + 3] = vec[3];
  4831. }
  4832. return a;
  4833. };
  4834. })();
  4835. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4836. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4837. const INDICES = Object.freeze({
  4838. COL0ROW0: 0,
  4839. COL0ROW1: 1,
  4840. COL0ROW2: 2,
  4841. COL0ROW3: 3,
  4842. COL1ROW0: 4,
  4843. COL1ROW1: 5,
  4844. COL1ROW2: 6,
  4845. COL1ROW3: 7,
  4846. COL2ROW0: 8,
  4847. COL2ROW1: 9,
  4848. COL2ROW2: 10,
  4849. COL2ROW3: 11,
  4850. COL3ROW0: 12,
  4851. COL3ROW1: 13,
  4852. COL3ROW2: 14,
  4853. COL3ROW3: 15
  4854. });
  4855. const constants = {};
  4856. class Matrix4 extends Matrix {
  4857. static get IDENTITY() {
  4858. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4859. return constants.IDENTITY;
  4860. }
  4861. static get ZERO() {
  4862. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4863. return constants.ZERO;
  4864. }
  4865. get INDICES() {
  4866. return INDICES;
  4867. }
  4868. get ELEMENTS() {
  4869. return 16;
  4870. }
  4871. get RANK() {
  4872. return 4;
  4873. }
  4874. constructor(array) {
  4875. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4876. if (arguments.length === 1 && Array.isArray(array)) {
  4877. this.copy(array);
  4878. } else {
  4879. this.identity();
  4880. }
  4881. }
  4882. copy(array) {
  4883. this[0] = array[0];
  4884. this[1] = array[1];
  4885. this[2] = array[2];
  4886. this[3] = array[3];
  4887. this[4] = array[4];
  4888. this[5] = array[5];
  4889. this[6] = array[6];
  4890. this[7] = array[7];
  4891. this[8] = array[8];
  4892. this[9] = array[9];
  4893. this[10] = array[10];
  4894. this[11] = array[11];
  4895. this[12] = array[12];
  4896. this[13] = array[13];
  4897. this[14] = array[14];
  4898. this[15] = array[15];
  4899. return this.check();
  4900. }
  4901. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4902. this[0] = m00;
  4903. this[1] = m10;
  4904. this[2] = m20;
  4905. this[3] = m30;
  4906. this[4] = m01;
  4907. this[5] = m11;
  4908. this[6] = m21;
  4909. this[7] = m31;
  4910. this[8] = m02;
  4911. this[9] = m12;
  4912. this[10] = m22;
  4913. this[11] = m32;
  4914. this[12] = m03;
  4915. this[13] = m13;
  4916. this[14] = m23;
  4917. this[15] = m33;
  4918. return this.check();
  4919. }
  4920. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4921. this[0] = m00;
  4922. this[1] = m10;
  4923. this[2] = m20;
  4924. this[3] = m30;
  4925. this[4] = m01;
  4926. this[5] = m11;
  4927. this[6] = m21;
  4928. this[7] = m31;
  4929. this[8] = m02;
  4930. this[9] = m12;
  4931. this[10] = m22;
  4932. this[11] = m32;
  4933. this[12] = m03;
  4934. this[13] = m13;
  4935. this[14] = m23;
  4936. this[15] = m33;
  4937. return this.check();
  4938. }
  4939. toRowMajor(result) {
  4940. result[0] = this[0];
  4941. result[1] = this[4];
  4942. result[2] = this[8];
  4943. result[3] = this[12];
  4944. result[4] = this[1];
  4945. result[5] = this[5];
  4946. result[6] = this[9];
  4947. result[7] = this[13];
  4948. result[8] = this[2];
  4949. result[9] = this[6];
  4950. result[10] = this[10];
  4951. result[11] = this[14];
  4952. result[12] = this[3];
  4953. result[13] = this[7];
  4954. result[14] = this[11];
  4955. result[15] = this[15];
  4956. return result;
  4957. }
  4958. identity() {
  4959. return this.copy(IDENTITY);
  4960. }
  4961. fromQuaternion(q) {
  4962. fromQuat(this, q);
  4963. return this.check();
  4964. }
  4965. frustum({
  4966. left,
  4967. right,
  4968. bottom,
  4969. top,
  4970. near,
  4971. far
  4972. }) {
  4973. if (far === Infinity) {
  4974. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  4975. } else {
  4976. frustum(this, left, right, bottom, top, near, far);
  4977. }
  4978. return this.check();
  4979. }
  4980. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  4981. const column0Row0 = 2.0 * near / (right - left);
  4982. const column1Row1 = 2.0 * near / (top - bottom);
  4983. const column2Row0 = (right + left) / (right - left);
  4984. const column2Row1 = (top + bottom) / (top - bottom);
  4985. const column2Row2 = -1.0;
  4986. const column2Row3 = -1.0;
  4987. const column3Row2 = -2.0 * near;
  4988. result[0] = column0Row0;
  4989. result[1] = 0.0;
  4990. result[2] = 0.0;
  4991. result[3] = 0.0;
  4992. result[4] = 0.0;
  4993. result[5] = column1Row1;
  4994. result[6] = 0.0;
  4995. result[7] = 0.0;
  4996. result[8] = column2Row0;
  4997. result[9] = column2Row1;
  4998. result[10] = column2Row2;
  4999. result[11] = column2Row3;
  5000. result[12] = 0.0;
  5001. result[13] = 0.0;
  5002. result[14] = column3Row2;
  5003. result[15] = 0.0;
  5004. return result;
  5005. }
  5006. lookAt(eye, center, up) {
  5007. if (arguments.length === 1) {
  5008. ({
  5009. eye,
  5010. center,
  5011. up
  5012. } = eye);
  5013. }
  5014. center = center || [0, 0, 0];
  5015. up = up || [0, 1, 0];
  5016. lookAt(this, eye, center, up);
  5017. return this.check();
  5018. }
  5019. ortho({
  5020. left,
  5021. right,
  5022. bottom,
  5023. top,
  5024. near = 0.1,
  5025. far = 500
  5026. }) {
  5027. ortho(this, left, right, bottom, top, near, far);
  5028. return this.check();
  5029. }
  5030. orthographic({
  5031. fovy = 45 * Math.PI / 180,
  5032. aspect = 1,
  5033. focalDistance = 1,
  5034. near = 0.1,
  5035. far = 500
  5036. }) {
  5037. if (fovy > Math.PI * 2) {
  5038. throw Error('radians');
  5039. }
  5040. const halfY = fovy / 2;
  5041. const top = focalDistance * Math.tan(halfY);
  5042. const right = top * aspect;
  5043. return new Matrix4().ortho({
  5044. left: -right,
  5045. right,
  5046. bottom: -top,
  5047. top,
  5048. near,
  5049. far
  5050. });
  5051. }
  5052. perspective({
  5053. fovy = undefined,
  5054. fov = 45 * Math.PI / 180,
  5055. aspect = 1,
  5056. near = 0.1,
  5057. far = 500
  5058. } = {}) {
  5059. fovy = fovy || fov;
  5060. if (fovy > Math.PI * 2) {
  5061. throw Error('radians');
  5062. }
  5063. perspective(this, fovy, aspect, near, far);
  5064. return this.check();
  5065. }
  5066. determinant() {
  5067. return determinant(this);
  5068. }
  5069. getScale(result = [-0, -0, -0]) {
  5070. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5071. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5072. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5073. return result;
  5074. }
  5075. getTranslation(result = [-0, -0, -0]) {
  5076. result[0] = this[12];
  5077. result[1] = this[13];
  5078. result[2] = this[14];
  5079. return result;
  5080. }
  5081. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5082. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5083. const inverseScale0 = 1 / scale[0];
  5084. const inverseScale1 = 1 / scale[1];
  5085. const inverseScale2 = 1 / scale[2];
  5086. result[0] = this[0] * inverseScale0;
  5087. result[1] = this[1] * inverseScale1;
  5088. result[2] = this[2] * inverseScale2;
  5089. result[3] = 0;
  5090. result[4] = this[4] * inverseScale0;
  5091. result[5] = this[5] * inverseScale1;
  5092. result[6] = this[6] * inverseScale2;
  5093. result[7] = 0;
  5094. result[8] = this[8] * inverseScale0;
  5095. result[9] = this[9] * inverseScale1;
  5096. result[10] = this[10] * inverseScale2;
  5097. result[11] = 0;
  5098. result[12] = 0;
  5099. result[13] = 0;
  5100. result[14] = 0;
  5101. result[15] = 1;
  5102. return result;
  5103. }
  5104. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5105. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5106. const inverseScale0 = 1 / scale[0];
  5107. const inverseScale1 = 1 / scale[1];
  5108. const inverseScale2 = 1 / scale[2];
  5109. result[0] = this[0] * inverseScale0;
  5110. result[1] = this[1] * inverseScale1;
  5111. result[2] = this[2] * inverseScale2;
  5112. result[3] = this[4] * inverseScale0;
  5113. result[4] = this[5] * inverseScale1;
  5114. result[5] = this[6] * inverseScale2;
  5115. result[6] = this[8] * inverseScale0;
  5116. result[7] = this[9] * inverseScale1;
  5117. result[8] = this[10] * inverseScale2;
  5118. return result;
  5119. }
  5120. transpose() {
  5121. transpose(this, this);
  5122. return this.check();
  5123. }
  5124. invert() {
  5125. invert$1(this, this);
  5126. return this.check();
  5127. }
  5128. multiplyLeft(a) {
  5129. multiply$1(this, a, this);
  5130. return this.check();
  5131. }
  5132. multiplyRight(a) {
  5133. multiply$1(this, this, a);
  5134. return this.check();
  5135. }
  5136. rotateX(radians) {
  5137. rotateX$1(this, this, radians);
  5138. return this.check();
  5139. }
  5140. rotateY(radians) {
  5141. rotateY$1(this, this, radians);
  5142. return this.check();
  5143. }
  5144. rotateZ(radians) {
  5145. rotateZ$1(this, this, radians);
  5146. return this.check();
  5147. }
  5148. rotateXYZ([rx, ry, rz]) {
  5149. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5150. }
  5151. rotateAxis(radians, axis) {
  5152. rotate(this, this, radians, axis);
  5153. return this.check();
  5154. }
  5155. scale(factor) {
  5156. if (Array.isArray(factor)) {
  5157. scale$2(this, this, factor);
  5158. } else {
  5159. scale$2(this, this, [factor, factor, factor]);
  5160. }
  5161. return this.check();
  5162. }
  5163. translate(vec) {
  5164. translate(this, this, vec);
  5165. return this.check();
  5166. }
  5167. transform(vector, result) {
  5168. if (vector.length === 4) {
  5169. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5170. checkVector(result, 4);
  5171. return result;
  5172. }
  5173. return this.transformAsPoint(vector, result);
  5174. }
  5175. transformAsPoint(vector, result) {
  5176. const {
  5177. length
  5178. } = vector;
  5179. switch (length) {
  5180. case 2:
  5181. result = transformMat4$2(result || [-0, -0], vector, this);
  5182. break;
  5183. case 3:
  5184. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5185. break;
  5186. default:
  5187. throw new Error('Illegal vector');
  5188. }
  5189. checkVector(result, vector.length);
  5190. return result;
  5191. }
  5192. transformAsVector(vector, result) {
  5193. switch (vector.length) {
  5194. case 2:
  5195. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5196. break;
  5197. case 3:
  5198. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5199. break;
  5200. default:
  5201. throw new Error('Illegal vector');
  5202. }
  5203. checkVector(result, vector.length);
  5204. return result;
  5205. }
  5206. makeRotationX(radians) {
  5207. return this.identity().rotateX(radians);
  5208. }
  5209. makeTranslation(x, y, z) {
  5210. return this.identity().translate([x, y, z]);
  5211. }
  5212. transformPoint(vector, result) {
  5213. deprecated('Matrix4.transformPoint', '3.0');
  5214. return this.transformAsPoint(vector, result);
  5215. }
  5216. transformVector(vector, result) {
  5217. deprecated('Matrix4.transformVector', '3.0');
  5218. return this.transformAsPoint(vector, result);
  5219. }
  5220. transformDirection(vector, result) {
  5221. deprecated('Matrix4.transformDirection', '3.0');
  5222. return this.transformAsVector(vector, result);
  5223. }
  5224. }
  5225. /**
  5226. * Quaternion
  5227. * @module quat
  5228. */
  5229. /**
  5230. * Creates a new identity quat
  5231. *
  5232. * @returns {quat} a new quaternion
  5233. */
  5234. function create() {
  5235. var out = new ARRAY_TYPE(4);
  5236. if (ARRAY_TYPE != Float32Array) {
  5237. out[0] = 0;
  5238. out[1] = 0;
  5239. out[2] = 0;
  5240. }
  5241. out[3] = 1;
  5242. return out;
  5243. }
  5244. /**
  5245. * Set a quat to the identity quaternion
  5246. *
  5247. * @param {quat} out the receiving quaternion
  5248. * @returns {quat} out
  5249. */
  5250. function identity(out) {
  5251. out[0] = 0;
  5252. out[1] = 0;
  5253. out[2] = 0;
  5254. out[3] = 1;
  5255. return out;
  5256. }
  5257. /**
  5258. * Sets a quat from the given angle and rotation axis,
  5259. * then returns it.
  5260. *
  5261. * @param {quat} out the receiving quaternion
  5262. * @param {ReadonlyVec3} axis the axis around which to rotate
  5263. * @param {Number} rad the angle in radians
  5264. * @returns {quat} out
  5265. **/
  5266. function setAxisAngle(out, axis, rad) {
  5267. rad = rad * 0.5;
  5268. var s = Math.sin(rad);
  5269. out[0] = s * axis[0];
  5270. out[1] = s * axis[1];
  5271. out[2] = s * axis[2];
  5272. out[3] = Math.cos(rad);
  5273. return out;
  5274. }
  5275. /**
  5276. * Multiplies two quat's
  5277. *
  5278. * @param {quat} out the receiving quaternion
  5279. * @param {ReadonlyQuat} a the first operand
  5280. * @param {ReadonlyQuat} b the second operand
  5281. * @returns {quat} out
  5282. */
  5283. function multiply(out, a, b) {
  5284. var ax = a[0],
  5285. ay = a[1],
  5286. az = a[2],
  5287. aw = a[3];
  5288. var bx = b[0],
  5289. by = b[1],
  5290. bz = b[2],
  5291. bw = b[3];
  5292. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5293. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5294. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5295. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5296. return out;
  5297. }
  5298. /**
  5299. * Rotates a quaternion by the given angle about the X axis
  5300. *
  5301. * @param {quat} out quat receiving operation result
  5302. * @param {ReadonlyQuat} a quat to rotate
  5303. * @param {number} rad angle (in radians) to rotate
  5304. * @returns {quat} out
  5305. */
  5306. function rotateX(out, a, rad) {
  5307. rad *= 0.5;
  5308. var ax = a[0],
  5309. ay = a[1],
  5310. az = a[2],
  5311. aw = a[3];
  5312. var bx = Math.sin(rad),
  5313. bw = Math.cos(rad);
  5314. out[0] = ax * bw + aw * bx;
  5315. out[1] = ay * bw + az * bx;
  5316. out[2] = az * bw - ay * bx;
  5317. out[3] = aw * bw - ax * bx;
  5318. return out;
  5319. }
  5320. /**
  5321. * Rotates a quaternion by the given angle about the Y axis
  5322. *
  5323. * @param {quat} out quat receiving operation result
  5324. * @param {ReadonlyQuat} a quat to rotate
  5325. * @param {number} rad angle (in radians) to rotate
  5326. * @returns {quat} out
  5327. */
  5328. function rotateY(out, a, rad) {
  5329. rad *= 0.5;
  5330. var ax = a[0],
  5331. ay = a[1],
  5332. az = a[2],
  5333. aw = a[3];
  5334. var by = Math.sin(rad),
  5335. bw = Math.cos(rad);
  5336. out[0] = ax * bw - az * by;
  5337. out[1] = ay * bw + aw * by;
  5338. out[2] = az * bw + ax * by;
  5339. out[3] = aw * bw - ay * by;
  5340. return out;
  5341. }
  5342. /**
  5343. * Rotates a quaternion by the given angle about the Z axis
  5344. *
  5345. * @param {quat} out quat receiving operation result
  5346. * @param {ReadonlyQuat} a quat to rotate
  5347. * @param {number} rad angle (in radians) to rotate
  5348. * @returns {quat} out
  5349. */
  5350. function rotateZ(out, a, rad) {
  5351. rad *= 0.5;
  5352. var ax = a[0],
  5353. ay = a[1],
  5354. az = a[2],
  5355. aw = a[3];
  5356. var bz = Math.sin(rad),
  5357. bw = Math.cos(rad);
  5358. out[0] = ax * bw + ay * bz;
  5359. out[1] = ay * bw - ax * bz;
  5360. out[2] = az * bw + aw * bz;
  5361. out[3] = aw * bw - az * bz;
  5362. return out;
  5363. }
  5364. /**
  5365. * Calculates the W component of a quat from the X, Y, and Z components.
  5366. * Assumes that quaternion is 1 unit in length.
  5367. * Any existing W component will be ignored.
  5368. *
  5369. * @param {quat} out the receiving quaternion
  5370. * @param {ReadonlyQuat} a quat to calculate W component of
  5371. * @returns {quat} out
  5372. */
  5373. function calculateW(out, a) {
  5374. var x = a[0],
  5375. y = a[1],
  5376. z = a[2];
  5377. out[0] = x;
  5378. out[1] = y;
  5379. out[2] = z;
  5380. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5381. return out;
  5382. }
  5383. /**
  5384. * Performs a spherical linear interpolation between two quat
  5385. *
  5386. * @param {quat} out the receiving quaternion
  5387. * @param {ReadonlyQuat} a the first operand
  5388. * @param {ReadonlyQuat} b the second operand
  5389. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5390. * @returns {quat} out
  5391. */
  5392. function slerp(out, a, b, t) {
  5393. // benchmarks:
  5394. // http://jsperf.com/quaternion-slerp-implementations
  5395. var ax = a[0],
  5396. ay = a[1],
  5397. az = a[2],
  5398. aw = a[3];
  5399. var bx = b[0],
  5400. by = b[1],
  5401. bz = b[2],
  5402. bw = b[3];
  5403. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5404. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5405. if (cosom < 0.0) {
  5406. cosom = -cosom;
  5407. bx = -bx;
  5408. by = -by;
  5409. bz = -bz;
  5410. bw = -bw;
  5411. } // calculate coefficients
  5412. if (1.0 - cosom > EPSILON) {
  5413. // standard case (slerp)
  5414. omega = Math.acos(cosom);
  5415. sinom = Math.sin(omega);
  5416. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5417. scale1 = Math.sin(t * omega) / sinom;
  5418. } else {
  5419. // "from" and "to" quaternions are very close
  5420. // ... so we can do a linear interpolation
  5421. scale0 = 1.0 - t;
  5422. scale1 = t;
  5423. } // calculate final values
  5424. out[0] = scale0 * ax + scale1 * bx;
  5425. out[1] = scale0 * ay + scale1 * by;
  5426. out[2] = scale0 * az + scale1 * bz;
  5427. out[3] = scale0 * aw + scale1 * bw;
  5428. return out;
  5429. }
  5430. /**
  5431. * Calculates the inverse of a quat
  5432. *
  5433. * @param {quat} out the receiving quaternion
  5434. * @param {ReadonlyQuat} a quat to calculate inverse of
  5435. * @returns {quat} out
  5436. */
  5437. function invert(out, a) {
  5438. var a0 = a[0],
  5439. a1 = a[1],
  5440. a2 = a[2],
  5441. a3 = a[3];
  5442. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5443. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5444. out[0] = -a0 * invDot;
  5445. out[1] = -a1 * invDot;
  5446. out[2] = -a2 * invDot;
  5447. out[3] = a3 * invDot;
  5448. return out;
  5449. }
  5450. /**
  5451. * Calculates the conjugate of a quat
  5452. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5453. *
  5454. * @param {quat} out the receiving quaternion
  5455. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5456. * @returns {quat} out
  5457. */
  5458. function conjugate(out, a) {
  5459. out[0] = -a[0];
  5460. out[1] = -a[1];
  5461. out[2] = -a[2];
  5462. out[3] = a[3];
  5463. return out;
  5464. }
  5465. /**
  5466. * Creates a quaternion from the given 3x3 rotation matrix.
  5467. *
  5468. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5469. * to renormalize the quaternion yourself where necessary.
  5470. *
  5471. * @param {quat} out the receiving quaternion
  5472. * @param {ReadonlyMat3} m rotation matrix
  5473. * @returns {quat} out
  5474. * @function
  5475. */
  5476. function fromMat3(out, m) {
  5477. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5478. // article "Quaternion Calculus and Fast Animation".
  5479. var fTrace = m[0] + m[4] + m[8];
  5480. var fRoot;
  5481. if (fTrace > 0.0) {
  5482. // |w| > 1/2, may as well choose w > 1/2
  5483. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5484. out[3] = 0.5 * fRoot;
  5485. fRoot = 0.5 / fRoot; // 1/(4w)
  5486. out[0] = (m[5] - m[7]) * fRoot;
  5487. out[1] = (m[6] - m[2]) * fRoot;
  5488. out[2] = (m[1] - m[3]) * fRoot;
  5489. } else {
  5490. // |w| <= 1/2
  5491. var i = 0;
  5492. if (m[4] > m[0]) i = 1;
  5493. if (m[8] > m[i * 3 + i]) i = 2;
  5494. var j = (i + 1) % 3;
  5495. var k = (i + 2) % 3;
  5496. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5497. out[i] = 0.5 * fRoot;
  5498. fRoot = 0.5 / fRoot;
  5499. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5500. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5501. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5502. }
  5503. return out;
  5504. }
  5505. /**
  5506. * Adds two quat's
  5507. *
  5508. * @param {quat} out the receiving quaternion
  5509. * @param {ReadonlyQuat} a the first operand
  5510. * @param {ReadonlyQuat} b the second operand
  5511. * @returns {quat} out
  5512. * @function
  5513. */
  5514. var add = add$1;
  5515. /**
  5516. * Scales a quat by a scalar number
  5517. *
  5518. * @param {quat} out the receiving vector
  5519. * @param {ReadonlyQuat} a the vector to scale
  5520. * @param {Number} b amount to scale the vector by
  5521. * @returns {quat} out
  5522. * @function
  5523. */
  5524. var scale = scale$1;
  5525. /**
  5526. * Calculates the dot product of two quat's
  5527. *
  5528. * @param {ReadonlyQuat} a the first operand
  5529. * @param {ReadonlyQuat} b the second operand
  5530. * @returns {Number} dot product of a and b
  5531. * @function
  5532. */
  5533. var dot = dot$1;
  5534. /**
  5535. * Performs a linear interpolation between two quat's
  5536. *
  5537. * @param {quat} out the receiving quaternion
  5538. * @param {ReadonlyQuat} a the first operand
  5539. * @param {ReadonlyQuat} b the second operand
  5540. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5541. * @returns {quat} out
  5542. * @function
  5543. */
  5544. var lerp = lerp$1;
  5545. /**
  5546. * Calculates the length of a quat
  5547. *
  5548. * @param {ReadonlyQuat} a vector to calculate length of
  5549. * @returns {Number} length of a
  5550. */
  5551. var length = length$1;
  5552. /**
  5553. * Calculates the squared length of a quat
  5554. *
  5555. * @param {ReadonlyQuat} a vector to calculate squared length of
  5556. * @returns {Number} squared length of a
  5557. * @function
  5558. */
  5559. var squaredLength = squaredLength$1;
  5560. /**
  5561. * Normalize a quat
  5562. *
  5563. * @param {quat} out the receiving quaternion
  5564. * @param {ReadonlyQuat} a quaternion to normalize
  5565. * @returns {quat} out
  5566. * @function
  5567. */
  5568. var normalize = normalize$1;
  5569. /**
  5570. * Sets a quaternion to represent the shortest rotation from one
  5571. * vector to another.
  5572. *
  5573. * Both vectors are assumed to be unit length.
  5574. *
  5575. * @param {quat} out the receiving quaternion.
  5576. * @param {ReadonlyVec3} a the initial vector
  5577. * @param {ReadonlyVec3} b the destination vector
  5578. * @returns {quat} out
  5579. */
  5580. var rotationTo = function () {
  5581. var tmpvec3 = create$3();
  5582. var xUnitVec3 = fromValues(1, 0, 0);
  5583. var yUnitVec3 = fromValues(0, 1, 0);
  5584. return function (out, a, b) {
  5585. var dot = dot$2(a, b);
  5586. if (dot < -0.999999) {
  5587. cross(tmpvec3, xUnitVec3, a);
  5588. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5589. normalize$2(tmpvec3, tmpvec3);
  5590. setAxisAngle(out, tmpvec3, Math.PI);
  5591. return out;
  5592. } else if (dot > 0.999999) {
  5593. out[0] = 0;
  5594. out[1] = 0;
  5595. out[2] = 0;
  5596. out[3] = 1;
  5597. return out;
  5598. } else {
  5599. cross(tmpvec3, a, b);
  5600. out[0] = tmpvec3[0];
  5601. out[1] = tmpvec3[1];
  5602. out[2] = tmpvec3[2];
  5603. out[3] = 1 + dot;
  5604. return normalize(out, out);
  5605. }
  5606. };
  5607. }();
  5608. /**
  5609. * Performs a spherical linear interpolation with two control points
  5610. *
  5611. * @param {quat} out the receiving quaternion
  5612. * @param {ReadonlyQuat} a the first operand
  5613. * @param {ReadonlyQuat} b the second operand
  5614. * @param {ReadonlyQuat} c the third operand
  5615. * @param {ReadonlyQuat} d the fourth operand
  5616. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5617. * @returns {quat} out
  5618. */
  5619. (function () {
  5620. var temp1 = create();
  5621. var temp2 = create();
  5622. return function (out, a, b, c, d, t) {
  5623. slerp(temp1, a, d, t);
  5624. slerp(temp2, b, c, t);
  5625. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5626. return out;
  5627. };
  5628. })();
  5629. /**
  5630. * Sets the specified quaternion with values corresponding to the given
  5631. * axes. Each axis is a vec3 and is expected to be unit length and
  5632. * perpendicular to all other specified axes.
  5633. *
  5634. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5635. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5636. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5637. * @returns {quat} out
  5638. */
  5639. (function () {
  5640. var matr = create$2();
  5641. return function (out, view, right, up) {
  5642. matr[0] = right[0];
  5643. matr[3] = right[1];
  5644. matr[6] = right[2];
  5645. matr[1] = up[0];
  5646. matr[4] = up[1];
  5647. matr[7] = up[2];
  5648. matr[2] = -view[0];
  5649. matr[5] = -view[1];
  5650. matr[8] = -view[2];
  5651. return normalize(out, fromMat3(out, matr));
  5652. };
  5653. })();
  5654. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5655. class Quaternion extends MathArray {
  5656. constructor(x = 0, y = 0, z = 0, w = 1) {
  5657. super(-0, -0, -0, -0);
  5658. if (Array.isArray(x) && arguments.length === 1) {
  5659. this.copy(x);
  5660. } else {
  5661. this.set(x, y, z, w);
  5662. }
  5663. }
  5664. copy(array) {
  5665. this[0] = array[0];
  5666. this[1] = array[1];
  5667. this[2] = array[2];
  5668. this[3] = array[3];
  5669. return this.check();
  5670. }
  5671. set(x, y, z, w) {
  5672. this[0] = x;
  5673. this[1] = y;
  5674. this[2] = z;
  5675. this[3] = w;
  5676. return this.check();
  5677. }
  5678. fromMatrix3(m) {
  5679. fromMat3(this, m);
  5680. return this.check();
  5681. }
  5682. identity() {
  5683. identity(this);
  5684. return this.check();
  5685. }
  5686. fromAxisRotation(axis, rad) {
  5687. setAxisAngle(this, axis, rad);
  5688. return this.check();
  5689. }
  5690. setAxisAngle(axis, rad) {
  5691. return this.fromAxisRotation(axis, rad);
  5692. }
  5693. get ELEMENTS() {
  5694. return 4;
  5695. }
  5696. get x() {
  5697. return this[0];
  5698. }
  5699. set x(value) {
  5700. this[0] = checkNumber(value);
  5701. }
  5702. get y() {
  5703. return this[1];
  5704. }
  5705. set y(value) {
  5706. this[1] = checkNumber(value);
  5707. }
  5708. get z() {
  5709. return this[2];
  5710. }
  5711. set z(value) {
  5712. this[2] = checkNumber(value);
  5713. }
  5714. get w() {
  5715. return this[3];
  5716. }
  5717. set w(value) {
  5718. this[3] = checkNumber(value);
  5719. }
  5720. len() {
  5721. return length(this);
  5722. }
  5723. lengthSquared() {
  5724. return squaredLength(this);
  5725. }
  5726. dot(a, b) {
  5727. if (b !== undefined) {
  5728. throw new Error('Quaternion.dot only takes one argument');
  5729. }
  5730. return dot(this, a);
  5731. }
  5732. rotationTo(vectorA, vectorB) {
  5733. rotationTo(this, vectorA, vectorB);
  5734. return this.check();
  5735. }
  5736. add(a, b) {
  5737. if (b !== undefined) {
  5738. throw new Error('Quaternion.add only takes one argument');
  5739. }
  5740. add(this, this, a);
  5741. return this.check();
  5742. }
  5743. calculateW() {
  5744. calculateW(this, this);
  5745. return this.check();
  5746. }
  5747. conjugate() {
  5748. conjugate(this, this);
  5749. return this.check();
  5750. }
  5751. invert() {
  5752. invert(this, this);
  5753. return this.check();
  5754. }
  5755. lerp(a, b, t) {
  5756. lerp(this, a, b, t);
  5757. return this.check();
  5758. }
  5759. multiplyRight(a, b) {
  5760. assert$4(!b);
  5761. multiply(this, this, a);
  5762. return this.check();
  5763. }
  5764. multiplyLeft(a, b) {
  5765. assert$4(!b);
  5766. multiply(this, a, this);
  5767. return this.check();
  5768. }
  5769. normalize() {
  5770. const length = this.len();
  5771. const l = length > 0 ? 1 / length : 0;
  5772. this[0] = this[0] * l;
  5773. this[1] = this[1] * l;
  5774. this[2] = this[2] * l;
  5775. this[3] = this[3] * l;
  5776. if (length === 0) {
  5777. this[3] = 1;
  5778. }
  5779. return this.check();
  5780. }
  5781. rotateX(rad) {
  5782. rotateX(this, this, rad);
  5783. return this.check();
  5784. }
  5785. rotateY(rad) {
  5786. rotateY(this, this, rad);
  5787. return this.check();
  5788. }
  5789. rotateZ(rad) {
  5790. rotateZ(this, this, rad);
  5791. return this.check();
  5792. }
  5793. scale(b) {
  5794. scale(this, this, b);
  5795. return this.check();
  5796. }
  5797. slerp(start, target, ratio) {
  5798. switch (arguments.length) {
  5799. case 1:
  5800. ({
  5801. start = IDENTITY_QUATERNION,
  5802. target,
  5803. ratio
  5804. } = arguments[0]);
  5805. break;
  5806. case 2:
  5807. [target, ratio] = arguments;
  5808. start = this;
  5809. break;
  5810. }
  5811. slerp(this, start, target, ratio);
  5812. return this.check();
  5813. }
  5814. transformVector4(vector, result = vector) {
  5815. transformQuat(result, vector, this);
  5816. return checkVector(result, 4);
  5817. }
  5818. lengthSq() {
  5819. return this.lengthSquared();
  5820. }
  5821. setFromAxisAngle(axis, rad) {
  5822. return this.setAxisAngle(axis, rad);
  5823. }
  5824. premultiply(a, b) {
  5825. return this.multiplyLeft(a, b);
  5826. }
  5827. multiply(a, b) {
  5828. return this.multiplyRight(a, b);
  5829. }
  5830. }
  5831. var _MathUtils = {
  5832. EPSILON1: 1e-1,
  5833. EPSILON2: 1e-2,
  5834. EPSILON3: 1e-3,
  5835. EPSILON4: 1e-4,
  5836. EPSILON5: 1e-5,
  5837. EPSILON6: 1e-6,
  5838. EPSILON7: 1e-7,
  5839. EPSILON8: 1e-8,
  5840. EPSILON9: 1e-9,
  5841. EPSILON10: 1e-10,
  5842. EPSILON11: 1e-11,
  5843. EPSILON12: 1e-12,
  5844. EPSILON13: 1e-13,
  5845. EPSILON14: 1e-14,
  5846. EPSILON15: 1e-15,
  5847. EPSILON16: 1e-16,
  5848. EPSILON17: 1e-17,
  5849. EPSILON18: 1e-18,
  5850. EPSILON19: 1e-19,
  5851. EPSILON20: 1e-20,
  5852. PI_OVER_TWO: Math.PI / 2,
  5853. PI_OVER_FOUR: Math.PI / 4,
  5854. PI_OVER_SIX: Math.PI / 6,
  5855. TWO_PI: Math.PI * 2
  5856. };
  5857. const WGS84_RADIUS_X$1 = 6378137.0;
  5858. const WGS84_RADIUS_Y$1 = 6378137.0;
  5859. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5860. const noop = x => x;
  5861. const scratchVector$6 = new Vector3();
  5862. function fromCartographic(cartographic, result, map = noop) {
  5863. if (isArray(cartographic)) {
  5864. result[0] = map(cartographic[0]);
  5865. result[1] = map(cartographic[1]);
  5866. result[2] = cartographic[2];
  5867. } else if ('longitude' in cartographic) {
  5868. result[0] = map(cartographic.longitude);
  5869. result[1] = map(cartographic.latitude);
  5870. result[2] = cartographic.height;
  5871. } else {
  5872. result[0] = map(cartographic.x);
  5873. result[1] = map(cartographic.y);
  5874. result[2] = cartographic.z;
  5875. }
  5876. return result;
  5877. }
  5878. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5879. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5880. }
  5881. function toCartographic(vector, cartographic, map = noop) {
  5882. if (isArray(cartographic)) {
  5883. cartographic[0] = map(vector[0]);
  5884. cartographic[1] = map(vector[1]);
  5885. cartographic[2] = vector[2];
  5886. } else if ('longitude' in cartographic) {
  5887. cartographic.longitude = map(vector[0]);
  5888. cartographic.latitude = map(vector[1]);
  5889. cartographic.height = vector[2];
  5890. } else {
  5891. cartographic.x = map(vector[0]);
  5892. cartographic.y = map(vector[1]);
  5893. cartographic.z = vector[2];
  5894. }
  5895. return cartographic;
  5896. }
  5897. function toCartographicFromRadians(vector, cartographic) {
  5898. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5899. }
  5900. const scratchVector$5 = new Vector3();
  5901. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5902. const scaleToGeodeticSurfaceGradient = new Vector3();
  5903. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5904. const {
  5905. oneOverRadii,
  5906. oneOverRadiiSquared,
  5907. centerToleranceSquared
  5908. } = ellipsoid;
  5909. scratchVector$5.from(cartesian);
  5910. const positionX = cartesian.x;
  5911. const positionY = cartesian.y;
  5912. const positionZ = cartesian.z;
  5913. const oneOverRadiiX = oneOverRadii.x;
  5914. const oneOverRadiiY = oneOverRadii.y;
  5915. const oneOverRadiiZ = oneOverRadii.z;
  5916. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5917. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5918. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5919. const squaredNorm = x2 + y2 + z2;
  5920. const ratio = Math.sqrt(1.0 / squaredNorm);
  5921. if (!Number.isFinite(ratio)) {
  5922. return undefined;
  5923. }
  5924. const intersection = scaleToGeodeticSurfaceIntersection;
  5925. intersection.copy(cartesian).scale(ratio);
  5926. if (squaredNorm < centerToleranceSquared) {
  5927. return intersection.to(result);
  5928. }
  5929. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5930. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5931. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5932. const gradient = scaleToGeodeticSurfaceGradient;
  5933. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5934. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5935. let correction = 0.0;
  5936. let xMultiplier;
  5937. let yMultiplier;
  5938. let zMultiplier;
  5939. let func;
  5940. do {
  5941. lambda -= correction;
  5942. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5943. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5944. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5945. const xMultiplier2 = xMultiplier * xMultiplier;
  5946. const yMultiplier2 = yMultiplier * yMultiplier;
  5947. const zMultiplier2 = zMultiplier * zMultiplier;
  5948. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5949. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5950. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5951. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5952. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5953. const derivative = -2.0 * denominator;
  5954. correction = func / derivative;
  5955. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5956. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5957. }
  5958. const EPSILON14 = 1e-14;
  5959. const scratchOrigin = new Vector3();
  5960. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5961. up: {
  5962. south: 'east',
  5963. north: 'west',
  5964. west: 'south',
  5965. east: 'north'
  5966. },
  5967. down: {
  5968. south: 'west',
  5969. north: 'east',
  5970. west: 'north',
  5971. east: 'south'
  5972. },
  5973. south: {
  5974. up: 'west',
  5975. down: 'east',
  5976. west: 'down',
  5977. east: 'up'
  5978. },
  5979. north: {
  5980. up: 'east',
  5981. down: 'west',
  5982. west: 'up',
  5983. east: 'down'
  5984. },
  5985. west: {
  5986. up: 'north',
  5987. down: 'south',
  5988. north: 'down',
  5989. south: 'up'
  5990. },
  5991. east: {
  5992. up: 'south',
  5993. down: 'north',
  5994. north: 'up',
  5995. south: 'down'
  5996. }
  5997. };
  5998. const degeneratePositionLocalFrame = {
  5999. north: [-1, 0, 0],
  6000. east: [0, 1, 0],
  6001. up: [0, 0, 1],
  6002. south: [1, 0, 0],
  6003. west: [0, -1, 0],
  6004. down: [0, 0, -1]
  6005. };
  6006. const scratchAxisVectors = {
  6007. east: new Vector3(),
  6008. north: new Vector3(),
  6009. up: new Vector3(),
  6010. west: new Vector3(),
  6011. south: new Vector3(),
  6012. down: new Vector3()
  6013. };
  6014. const scratchVector1 = new Vector3();
  6015. const scratchVector2$1 = new Vector3();
  6016. const scratchVector3$1 = new Vector3();
  6017. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6018. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6019. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6020. let firstAxisVector;
  6021. let secondAxisVector;
  6022. let thirdAxisVector;
  6023. const origin = scratchOrigin.copy(cartesianOrigin);
  6024. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6025. if (atPole) {
  6026. const sign = Math.sign(origin.z);
  6027. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6028. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6029. firstAxisVector.scale(sign);
  6030. }
  6031. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6032. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6033. secondAxisVector.scale(sign);
  6034. }
  6035. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6036. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6037. thirdAxisVector.scale(sign);
  6038. }
  6039. } else {
  6040. const {
  6041. up,
  6042. east,
  6043. north
  6044. } = scratchAxisVectors;
  6045. east.set(-origin.y, origin.x, 0.0).normalize();
  6046. ellipsoid.geodeticSurfaceNormal(origin, up);
  6047. north.copy(up).cross(east);
  6048. const {
  6049. down,
  6050. west,
  6051. south
  6052. } = scratchAxisVectors;
  6053. down.copy(up).scale(-1);
  6054. west.copy(east).scale(-1);
  6055. south.copy(north).scale(-1);
  6056. firstAxisVector = scratchAxisVectors[firstAxis];
  6057. secondAxisVector = scratchAxisVectors[secondAxis];
  6058. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6059. }
  6060. result[0] = firstAxisVector.x;
  6061. result[1] = firstAxisVector.y;
  6062. result[2] = firstAxisVector.z;
  6063. result[3] = 0.0;
  6064. result[4] = secondAxisVector.x;
  6065. result[5] = secondAxisVector.y;
  6066. result[6] = secondAxisVector.z;
  6067. result[7] = 0.0;
  6068. result[8] = thirdAxisVector.x;
  6069. result[9] = thirdAxisVector.y;
  6070. result[10] = thirdAxisVector.z;
  6071. result[11] = 0.0;
  6072. result[12] = origin.x;
  6073. result[13] = origin.y;
  6074. result[14] = origin.z;
  6075. result[15] = 1.0;
  6076. return result;
  6077. }
  6078. const scratchVector$4 = new Vector3();
  6079. const scratchNormal$2 = new Vector3();
  6080. const scratchK = new Vector3();
  6081. const scratchPosition$2 = new Vector3();
  6082. const scratchHeight = new Vector3();
  6083. const scratchCartesian = new Vector3();
  6084. let wgs84;
  6085. class Ellipsoid {
  6086. static get WGS84() {
  6087. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6088. return wgs84;
  6089. }
  6090. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6091. assert$4(x >= 0.0);
  6092. assert$4(y >= 0.0);
  6093. assert$4(z >= 0.0);
  6094. this.radii = new Vector3(x, y, z);
  6095. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6096. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6097. 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);
  6098. 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));
  6099. this.minimumRadius = Math.min(x, y, z);
  6100. this.maximumRadius = Math.max(x, y, z);
  6101. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6102. if (this.radiiSquared.z !== 0) {
  6103. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6104. }
  6105. Object.freeze(this);
  6106. }
  6107. equals(right) {
  6108. return this === right || Boolean(right && this.radii.equals(right.radii));
  6109. }
  6110. toString() {
  6111. return this.radii.toString();
  6112. }
  6113. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6114. const normal = scratchNormal$2;
  6115. const k = scratchK;
  6116. const [,, height] = cartographic;
  6117. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6118. k.copy(this.radiiSquared).scale(normal);
  6119. const gamma = Math.sqrt(normal.dot(k));
  6120. k.scale(1 / gamma);
  6121. normal.scale(height);
  6122. k.add(normal);
  6123. return k.to(result);
  6124. }
  6125. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6126. scratchCartesian.from(cartesian);
  6127. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6128. if (!point) {
  6129. return undefined;
  6130. }
  6131. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6132. const h = scratchHeight;
  6133. h.copy(scratchCartesian).subtract(point);
  6134. const longitude = Math.atan2(normal.y, normal.x);
  6135. const latitude = Math.asin(normal.z);
  6136. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6137. return toCartographicFromRadians([longitude, latitude, height], result);
  6138. }
  6139. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6140. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6141. }
  6142. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6143. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6144. }
  6145. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6146. return scratchVector$4.from(cartesian).normalize().to(result);
  6147. }
  6148. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6149. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6150. const longitude = cartographicVectorRadians[0];
  6151. const latitude = cartographicVectorRadians[1];
  6152. const cosLatitude = Math.cos(latitude);
  6153. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6154. return scratchVector$4.to(result);
  6155. }
  6156. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6157. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6158. }
  6159. scaleToGeodeticSurface(cartesian, result) {
  6160. return scaleToGeodeticSurface(cartesian, this, result);
  6161. }
  6162. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6163. scratchPosition$2.from(cartesian);
  6164. const positionX = scratchPosition$2.x;
  6165. const positionY = scratchPosition$2.y;
  6166. const positionZ = scratchPosition$2.z;
  6167. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6168. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6169. return scratchPosition$2.multiplyScalar(beta).to(result);
  6170. }
  6171. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6172. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6173. }
  6174. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6175. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6176. }
  6177. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6178. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6179. assert$4(this.radii.z > 0);
  6180. scratchPosition$2.from(position);
  6181. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6182. if (Math.abs(z) >= this.radii.z - buffer) {
  6183. return undefined;
  6184. }
  6185. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6186. }
  6187. }
  6188. class DoublyLinkedListNode {
  6189. constructor(item, previous, next) {
  6190. _defineProperty(this, "item", void 0);
  6191. _defineProperty(this, "previous", void 0);
  6192. _defineProperty(this, "next", void 0);
  6193. this.item = item;
  6194. this.previous = previous;
  6195. this.next = next;
  6196. }
  6197. }
  6198. class DoublyLinkedList {
  6199. constructor() {
  6200. _defineProperty(this, "head", null);
  6201. _defineProperty(this, "tail", null);
  6202. _defineProperty(this, "_length", 0);
  6203. }
  6204. get length() {
  6205. return this._length;
  6206. }
  6207. add(item) {
  6208. const node = new DoublyLinkedListNode(item, this.tail, null);
  6209. if (this.tail) {
  6210. this.tail.next = node;
  6211. this.tail = node;
  6212. } else {
  6213. this.head = node;
  6214. this.tail = node;
  6215. }
  6216. ++this._length;
  6217. return node;
  6218. }
  6219. remove(node) {
  6220. if (!node) {
  6221. return;
  6222. }
  6223. if (node.previous && node.next) {
  6224. node.previous.next = node.next;
  6225. node.next.previous = node.previous;
  6226. } else if (node.previous) {
  6227. node.previous.next = null;
  6228. this.tail = node.previous;
  6229. } else if (node.next) {
  6230. node.next.previous = null;
  6231. this.head = node.next;
  6232. } else {
  6233. this.head = null;
  6234. this.tail = null;
  6235. }
  6236. node.next = null;
  6237. node.previous = null;
  6238. --this._length;
  6239. }
  6240. splice(node, nextNode) {
  6241. if (node === nextNode) {
  6242. return;
  6243. }
  6244. this.remove(nextNode);
  6245. this._insert(node, nextNode);
  6246. }
  6247. _insert(node, nextNode) {
  6248. const oldNodeNext = node.next;
  6249. node.next = nextNode;
  6250. if (this.tail === node) {
  6251. this.tail = nextNode;
  6252. } else {
  6253. oldNodeNext.previous = nextNode;
  6254. }
  6255. nextNode.next = oldNodeNext;
  6256. nextNode.previous = node;
  6257. ++this._length;
  6258. }
  6259. }
  6260. function defined$5(x) {
  6261. return x !== undefined && x !== null;
  6262. }
  6263. class TilesetCache {
  6264. constructor() {
  6265. _defineProperty(this, "_list", void 0);
  6266. _defineProperty(this, "_sentinel", void 0);
  6267. _defineProperty(this, "_trimTiles", void 0);
  6268. this._list = new DoublyLinkedList();
  6269. this._sentinel = this._list.add('sentinel');
  6270. this._trimTiles = false;
  6271. }
  6272. reset() {
  6273. this._list.splice(this._list.tail, this._sentinel);
  6274. }
  6275. touch(tile) {
  6276. const node = tile._cacheNode;
  6277. if (defined$5(node)) {
  6278. this._list.splice(this._sentinel, node);
  6279. }
  6280. }
  6281. add(tileset, tile, addCallback) {
  6282. if (!defined$5(tile._cacheNode)) {
  6283. tile._cacheNode = this._list.add(tile);
  6284. if (addCallback) {
  6285. addCallback(tileset, tile);
  6286. }
  6287. }
  6288. }
  6289. unloadTile(tileset, tile, unloadCallback) {
  6290. const node = tile._cacheNode;
  6291. if (!defined$5(node)) {
  6292. return;
  6293. }
  6294. this._list.remove(node);
  6295. tile._cacheNode = undefined;
  6296. if (unloadCallback) {
  6297. unloadCallback(tileset, tile);
  6298. }
  6299. }
  6300. unloadTiles(tileset, unloadCallback) {
  6301. const trimTiles = this._trimTiles;
  6302. this._trimTiles = false;
  6303. const list = this._list;
  6304. const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
  6305. const sentinel = this._sentinel;
  6306. let node = list.head;
  6307. while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6308. const tile = node.item;
  6309. node = node.next;
  6310. this.unloadTile(tileset, tile, unloadCallback);
  6311. }
  6312. }
  6313. trim() {
  6314. this._trimTiles = true;
  6315. }
  6316. }
  6317. function calculateTransformProps(tileHeader, tile) {
  6318. assert$7(tileHeader);
  6319. assert$7(tile);
  6320. const {
  6321. rtcCenter,
  6322. gltfUpAxis
  6323. } = tile;
  6324. const {
  6325. computedTransform,
  6326. boundingVolume: {
  6327. center
  6328. }
  6329. } = tileHeader;
  6330. let modelMatrix = new Matrix4(computedTransform);
  6331. if (rtcCenter) {
  6332. modelMatrix.translate(rtcCenter);
  6333. }
  6334. switch (gltfUpAxis) {
  6335. case 'Z':
  6336. break;
  6337. case 'Y':
  6338. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6339. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6340. break;
  6341. case 'X':
  6342. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6343. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6344. break;
  6345. }
  6346. if (tile.isQuantized) {
  6347. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6348. }
  6349. const cartesianOrigin = new Vector3(center);
  6350. tile.cartesianModelMatrix = modelMatrix;
  6351. tile.cartesianOrigin = cartesianOrigin;
  6352. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6353. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6354. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6355. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6356. tile.cartographicOrigin = cartographicOrigin;
  6357. if (!tile.coordinateSystem) {
  6358. tile.modelMatrix = tile.cartographicModelMatrix;
  6359. }
  6360. }
  6361. const INTERSECTION = Object.freeze({
  6362. OUTSIDE: -1,
  6363. INTERSECTING: 0,
  6364. INSIDE: 1
  6365. });
  6366. new Vector3();
  6367. new Vector3();
  6368. const scratchVector$3 = new Vector3();
  6369. const scratchVector2 = new Vector3();
  6370. class BoundingSphere {
  6371. constructor(center = [0, 0, 0], radius = 0.0) {
  6372. this.radius = -0;
  6373. this.center = new Vector3();
  6374. this.fromCenterRadius(center, radius);
  6375. }
  6376. fromCenterRadius(center, radius) {
  6377. this.center.from(center);
  6378. this.radius = radius;
  6379. return this;
  6380. }
  6381. fromCornerPoints(corner, oppositeCorner) {
  6382. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6383. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6384. this.radius = this.center.distance(oppositeCorner);
  6385. return this;
  6386. }
  6387. equals(right) {
  6388. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6389. }
  6390. clone() {
  6391. return new BoundingSphere(this.center, this.radius);
  6392. }
  6393. union(boundingSphere) {
  6394. const leftCenter = this.center;
  6395. const leftRadius = this.radius;
  6396. const rightCenter = boundingSphere.center;
  6397. const rightRadius = boundingSphere.radius;
  6398. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6399. const centerSeparation = toRightCenter.magnitude();
  6400. if (leftRadius >= centerSeparation + rightRadius) {
  6401. return this.clone();
  6402. }
  6403. if (rightRadius >= centerSeparation + leftRadius) {
  6404. return boundingSphere.clone();
  6405. }
  6406. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6407. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6408. this.center.copy(scratchVector2);
  6409. this.radius = halfDistanceBetweenTangentPoints;
  6410. return this;
  6411. }
  6412. expand(point) {
  6413. point = scratchVector$3.from(point);
  6414. const radius = point.subtract(this.center).magnitude();
  6415. if (radius > this.radius) {
  6416. this.radius = radius;
  6417. }
  6418. return this;
  6419. }
  6420. transform(transform) {
  6421. this.center.transform(transform);
  6422. const scale = getScaling(scratchVector$3, transform);
  6423. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6424. return this;
  6425. }
  6426. distanceSquaredTo(point) {
  6427. const d = this.distanceTo(point);
  6428. return d * d;
  6429. }
  6430. distanceTo(point) {
  6431. point = scratchVector$3.from(point);
  6432. const delta = point.subtract(this.center);
  6433. return Math.max(0, delta.len() - this.radius);
  6434. }
  6435. intersectPlane(plane) {
  6436. const center = this.center;
  6437. const radius = this.radius;
  6438. const normal = plane.normal;
  6439. const distanceToPlane = normal.dot(center) + plane.distance;
  6440. if (distanceToPlane < -radius) {
  6441. return INTERSECTION.OUTSIDE;
  6442. }
  6443. if (distanceToPlane < radius) {
  6444. return INTERSECTION.INTERSECTING;
  6445. }
  6446. return INTERSECTION.INSIDE;
  6447. }
  6448. }
  6449. const scratchVector3 = new Vector3();
  6450. const scratchOffset = new Vector3();
  6451. const scratchVectorU = new Vector3();
  6452. const scratchVectorV = new Vector3();
  6453. const scratchVectorW = new Vector3();
  6454. const scratchCorner = new Vector3();
  6455. const scratchToCenter = new Vector3();
  6456. const MATRIX3 = {
  6457. COLUMN0ROW0: 0,
  6458. COLUMN0ROW1: 1,
  6459. COLUMN0ROW2: 2,
  6460. COLUMN1ROW0: 3,
  6461. COLUMN1ROW1: 4,
  6462. COLUMN1ROW2: 5,
  6463. COLUMN2ROW0: 6,
  6464. COLUMN2ROW1: 7,
  6465. COLUMN2ROW2: 8
  6466. };
  6467. class OrientedBoundingBox {
  6468. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6469. this.center = new Vector3().from(center);
  6470. this.halfAxes = new Matrix3(halfAxes);
  6471. }
  6472. get halfSize() {
  6473. const xAxis = this.halfAxes.getColumn(0);
  6474. const yAxis = this.halfAxes.getColumn(1);
  6475. const zAxis = this.halfAxes.getColumn(2);
  6476. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6477. }
  6478. get quaternion() {
  6479. const xAxis = this.halfAxes.getColumn(0);
  6480. const yAxis = this.halfAxes.getColumn(1);
  6481. const zAxis = this.halfAxes.getColumn(2);
  6482. const normXAxis = new Vector3(xAxis).normalize();
  6483. const normYAxis = new Vector3(yAxis).normalize();
  6484. const normZAxis = new Vector3(zAxis).normalize();
  6485. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6486. }
  6487. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6488. const quaternionObject = new Quaternion(quaternion);
  6489. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6490. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6491. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6492. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6493. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6494. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6495. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6496. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6497. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6498. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6499. this.center = new Vector3().from(center);
  6500. this.halfAxes = directionsMatrix;
  6501. return this;
  6502. }
  6503. clone() {
  6504. return new OrientedBoundingBox(this.center, this.halfAxes);
  6505. }
  6506. equals(right) {
  6507. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6508. }
  6509. getBoundingSphere(result = new BoundingSphere()) {
  6510. const halfAxes = this.halfAxes;
  6511. const u = halfAxes.getColumn(0, scratchVectorU);
  6512. const v = halfAxes.getColumn(1, scratchVectorV);
  6513. const w = halfAxes.getColumn(2, scratchVectorW);
  6514. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6515. result.center.copy(this.center);
  6516. result.radius = cornerVector.magnitude();
  6517. return result;
  6518. }
  6519. intersectPlane(plane) {
  6520. const center = this.center;
  6521. const normal = plane.normal;
  6522. const halfAxes = this.halfAxes;
  6523. const normalX = normal.x;
  6524. const normalY = normal.y;
  6525. const normalZ = normal.z;
  6526. 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]);
  6527. const distanceToPlane = normal.dot(center) + plane.distance;
  6528. if (distanceToPlane <= -radEffective) {
  6529. return INTERSECTION.OUTSIDE;
  6530. } else if (distanceToPlane >= radEffective) {
  6531. return INTERSECTION.INSIDE;
  6532. }
  6533. return INTERSECTION.INTERSECTING;
  6534. }
  6535. distanceTo(point) {
  6536. return Math.sqrt(this.distanceSquaredTo(point));
  6537. }
  6538. distanceSquaredTo(point) {
  6539. const offset = scratchOffset.from(point).subtract(this.center);
  6540. const halfAxes = this.halfAxes;
  6541. const u = halfAxes.getColumn(0, scratchVectorU);
  6542. const v = halfAxes.getColumn(1, scratchVectorV);
  6543. const w = halfAxes.getColumn(2, scratchVectorW);
  6544. const uHalf = u.magnitude();
  6545. const vHalf = v.magnitude();
  6546. const wHalf = w.magnitude();
  6547. u.normalize();
  6548. v.normalize();
  6549. w.normalize();
  6550. let distanceSquared = 0.0;
  6551. let d;
  6552. d = Math.abs(offset.dot(u)) - uHalf;
  6553. if (d > 0) {
  6554. distanceSquared += d * d;
  6555. }
  6556. d = Math.abs(offset.dot(v)) - vHalf;
  6557. if (d > 0) {
  6558. distanceSquared += d * d;
  6559. }
  6560. d = Math.abs(offset.dot(w)) - wHalf;
  6561. if (d > 0) {
  6562. distanceSquared += d * d;
  6563. }
  6564. return distanceSquared;
  6565. }
  6566. computePlaneDistances(position, direction, result = [-0, -0]) {
  6567. let minDist = Number.POSITIVE_INFINITY;
  6568. let maxDist = Number.NEGATIVE_INFINITY;
  6569. const center = this.center;
  6570. const halfAxes = this.halfAxes;
  6571. const u = halfAxes.getColumn(0, scratchVectorU);
  6572. const v = halfAxes.getColumn(1, scratchVectorV);
  6573. const w = halfAxes.getColumn(2, scratchVectorW);
  6574. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6575. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6576. let mag = direction.dot(toCenter);
  6577. minDist = Math.min(mag, minDist);
  6578. maxDist = Math.max(mag, maxDist);
  6579. corner.copy(center).add(u).add(v).subtract(w);
  6580. toCenter.copy(corner).subtract(position);
  6581. mag = direction.dot(toCenter);
  6582. minDist = Math.min(mag, minDist);
  6583. maxDist = Math.max(mag, maxDist);
  6584. corner.copy(center).add(u).subtract(v).add(w);
  6585. toCenter.copy(corner).subtract(position);
  6586. mag = direction.dot(toCenter);
  6587. minDist = Math.min(mag, minDist);
  6588. maxDist = Math.max(mag, maxDist);
  6589. corner.copy(center).add(u).subtract(v).subtract(w);
  6590. toCenter.copy(corner).subtract(position);
  6591. mag = direction.dot(toCenter);
  6592. minDist = Math.min(mag, minDist);
  6593. maxDist = Math.max(mag, maxDist);
  6594. center.copy(corner).subtract(u).add(v).add(w);
  6595. toCenter.copy(corner).subtract(position);
  6596. mag = direction.dot(toCenter);
  6597. minDist = Math.min(mag, minDist);
  6598. maxDist = Math.max(mag, maxDist);
  6599. center.copy(corner).subtract(u).add(v).subtract(w);
  6600. toCenter.copy(corner).subtract(position);
  6601. mag = direction.dot(toCenter);
  6602. minDist = Math.min(mag, minDist);
  6603. maxDist = Math.max(mag, maxDist);
  6604. center.copy(corner).subtract(u).subtract(v).add(w);
  6605. toCenter.copy(corner).subtract(position);
  6606. mag = direction.dot(toCenter);
  6607. minDist = Math.min(mag, minDist);
  6608. maxDist = Math.max(mag, maxDist);
  6609. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6610. toCenter.copy(corner).subtract(position);
  6611. mag = direction.dot(toCenter);
  6612. minDist = Math.min(mag, minDist);
  6613. maxDist = Math.max(mag, maxDist);
  6614. result[0] = minDist;
  6615. result[1] = maxDist;
  6616. return result;
  6617. }
  6618. transform(transformation) {
  6619. this.center.transformAsPoint(transformation);
  6620. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6621. xAxis.transformAsPoint(transformation);
  6622. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6623. yAxis.transformAsPoint(transformation);
  6624. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6625. zAxis.transformAsPoint(transformation);
  6626. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6627. return this;
  6628. }
  6629. getTransform() {
  6630. throw new Error('not implemented');
  6631. }
  6632. }
  6633. const scratchPosition$1 = new Vector3();
  6634. const scratchNormal$1 = new Vector3();
  6635. class Plane {
  6636. constructor(normal = [0, 0, 1], distance = 0) {
  6637. this.normal = new Vector3();
  6638. this.distance = -0;
  6639. this.fromNormalDistance(normal, distance);
  6640. }
  6641. fromNormalDistance(normal, distance) {
  6642. assert$4(Number.isFinite(distance));
  6643. this.normal.from(normal).normalize();
  6644. this.distance = distance;
  6645. return this;
  6646. }
  6647. fromPointNormal(point, normal) {
  6648. point = scratchPosition$1.from(point);
  6649. this.normal.from(normal).normalize();
  6650. const distance = -this.normal.dot(point);
  6651. this.distance = distance;
  6652. return this;
  6653. }
  6654. fromCoefficients(a, b, c, d) {
  6655. this.normal.set(a, b, c);
  6656. assert$4(equals(this.normal.len(), 1));
  6657. this.distance = d;
  6658. return this;
  6659. }
  6660. clone(plane) {
  6661. return new Plane(this.normal, this.distance);
  6662. }
  6663. equals(right) {
  6664. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6665. }
  6666. getPointDistance(point) {
  6667. return this.normal.dot(point) + this.distance;
  6668. }
  6669. transform(matrix4) {
  6670. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6671. const point = this.normal.scale(-this.distance).transform(matrix4);
  6672. return this.fromPointNormal(point, normal);
  6673. }
  6674. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6675. point = scratchPosition$1.from(point);
  6676. const pointDistance = this.getPointDistance(point);
  6677. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6678. return point.subtract(scaledNormal).to(result);
  6679. }
  6680. }
  6681. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6682. const scratchPlaneCenter = new Vector3();
  6683. const scratchPlaneNormal$1 = new Vector3();
  6684. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6685. class CullingVolume {
  6686. static get MASK_OUTSIDE() {
  6687. return 0xffffffff;
  6688. }
  6689. static get MASK_INSIDE() {
  6690. return 0x00000000;
  6691. }
  6692. static get MASK_INDETERMINATE() {
  6693. return 0x7fffffff;
  6694. }
  6695. constructor(planes = []) {
  6696. this.planes = planes;
  6697. assert$4(this.planes.every(plane => plane instanceof Plane));
  6698. }
  6699. fromBoundingSphere(boundingSphere) {
  6700. this.planes.length = 2 * faces.length;
  6701. const center = boundingSphere.center;
  6702. const radius = boundingSphere.radius;
  6703. let planeIndex = 0;
  6704. for (const faceNormal of faces) {
  6705. let plane0 = this.planes[planeIndex];
  6706. let plane1 = this.planes[planeIndex + 1];
  6707. if (!plane0) {
  6708. plane0 = this.planes[planeIndex] = new Plane();
  6709. }
  6710. if (!plane1) {
  6711. plane1 = this.planes[planeIndex + 1] = new Plane();
  6712. }
  6713. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6714. -faceNormal.dot(plane0Center);
  6715. plane0.fromPointNormal(plane0Center, faceNormal);
  6716. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6717. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6718. -negatedFaceNormal.dot(plane1Center);
  6719. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6720. planeIndex += 2;
  6721. }
  6722. return this;
  6723. }
  6724. computeVisibility(boundingVolume) {
  6725. assert$4(boundingVolume);
  6726. let intersect = INTERSECTION.INSIDE;
  6727. for (const plane of this.planes) {
  6728. const result = boundingVolume.intersectPlane(plane);
  6729. switch (result) {
  6730. case INTERSECTION.OUTSIDE:
  6731. return INTERSECTION.OUTSIDE;
  6732. case INTERSECTION.INTERSECTING:
  6733. intersect = INTERSECTION.INTERSECTING;
  6734. break;
  6735. }
  6736. }
  6737. return intersect;
  6738. }
  6739. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6740. assert$4(boundingVolume, 'boundingVolume is required.');
  6741. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6742. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6743. return parentPlaneMask;
  6744. }
  6745. let mask = CullingVolume.MASK_INSIDE;
  6746. const planes = this.planes;
  6747. for (let k = 0; k < this.planes.length; ++k) {
  6748. const flag = k < 31 ? 1 << k : 0;
  6749. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6750. continue;
  6751. }
  6752. const plane = planes[k];
  6753. const result = boundingVolume.intersectPlane(plane);
  6754. if (result === INTERSECTION.OUTSIDE) {
  6755. return CullingVolume.MASK_OUTSIDE;
  6756. } else if (result === INTERSECTION.INTERSECTING) {
  6757. mask |= flag;
  6758. }
  6759. }
  6760. return mask;
  6761. }
  6762. }
  6763. const scratchPlaneUpVector = new Vector3();
  6764. const scratchPlaneRightVector = new Vector3();
  6765. const scratchPlaneNearCenter = new Vector3();
  6766. const scratchPlaneFarCenter = new Vector3();
  6767. const scratchPlaneNormal = new Vector3();
  6768. class PerspectiveOffCenterFrustum {
  6769. constructor(options = {}) {
  6770. options = {
  6771. near: 1.0,
  6772. far: 500000000.0,
  6773. ...options
  6774. };
  6775. this.left = options.left;
  6776. this._left = undefined;
  6777. this.right = options.right;
  6778. this._right = undefined;
  6779. this.top = options.top;
  6780. this._top = undefined;
  6781. this.bottom = options.bottom;
  6782. this._bottom = undefined;
  6783. this.near = options.near;
  6784. this._near = this.near;
  6785. this.far = options.far;
  6786. this._far = this.far;
  6787. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6788. this._perspectiveMatrix = new Matrix4();
  6789. this._infinitePerspective = new Matrix4();
  6790. }
  6791. clone() {
  6792. return new PerspectiveOffCenterFrustum({
  6793. right: this.right,
  6794. left: this.left,
  6795. top: this.top,
  6796. bottom: this.bottom,
  6797. near: this.near,
  6798. far: this.far
  6799. });
  6800. }
  6801. equals(other) {
  6802. 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;
  6803. }
  6804. get projectionMatrix() {
  6805. update$1(this);
  6806. return this._perspectiveMatrix;
  6807. }
  6808. get infiniteProjectionMatrix() {
  6809. update$1(this);
  6810. return this._infinitePerspective;
  6811. }
  6812. computeCullingVolume(position, direction, up) {
  6813. assert$4(position, 'position is required.');
  6814. assert$4(direction, 'direction is required.');
  6815. assert$4(up, 'up is required.');
  6816. const planes = this._cullingVolume.planes;
  6817. up = scratchPlaneUpVector.copy(up).normalize();
  6818. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6819. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6820. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6821. let normal = scratchPlaneNormal;
  6822. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6823. planes[0].fromPointNormal(position, normal);
  6824. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6825. planes[1].fromPointNormal(position, normal);
  6826. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6827. planes[2].fromPointNormal(position, normal);
  6828. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6829. planes[3].fromPointNormal(position, normal);
  6830. normal = new Vector3().copy(direction);
  6831. planes[4].fromPointNormal(nearCenter, normal);
  6832. normal.negate();
  6833. planes[5].fromPointNormal(farCenter, normal);
  6834. return this._cullingVolume;
  6835. }
  6836. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6837. update$1(this);
  6838. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6839. assert$4(drawingBufferWidth > 0);
  6840. assert$4(drawingBufferHeight > 0);
  6841. assert$4(distance > 0);
  6842. assert$4(result);
  6843. const inverseNear = 1.0 / this.near;
  6844. let tanTheta = this.top * inverseNear;
  6845. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6846. tanTheta = this.right * inverseNear;
  6847. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6848. result.x = pixelWidth;
  6849. result.y = pixelHeight;
  6850. return result;
  6851. }
  6852. }
  6853. function update$1(frustum) {
  6854. assert$4(Number.isFinite(frustum.right) && Number.isFinite(frustum.left) && Number.isFinite(frustum.top) && Number.isFinite(frustum.bottom) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  6855. const {
  6856. top,
  6857. bottom,
  6858. right,
  6859. left,
  6860. near,
  6861. far
  6862. } = frustum;
  6863. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6864. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6865. frustum._left = left;
  6866. frustum._right = right;
  6867. frustum._top = top;
  6868. frustum._bottom = bottom;
  6869. frustum._near = near;
  6870. frustum._far = far;
  6871. frustum._perspectiveMatrix = new Matrix4().frustum({
  6872. left,
  6873. right,
  6874. bottom,
  6875. top,
  6876. near,
  6877. far
  6878. });
  6879. frustum._infinitePerspective = new Matrix4().frustum({
  6880. left,
  6881. right,
  6882. bottom,
  6883. top,
  6884. near,
  6885. far: Infinity
  6886. });
  6887. }
  6888. }
  6889. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6890. class PerspectiveFrustum {
  6891. constructor(options = {}) {
  6892. options = {
  6893. near: 1.0,
  6894. far: 500000000.0,
  6895. xOffset: 0.0,
  6896. yOffset: 0.0,
  6897. ...options
  6898. };
  6899. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6900. this.fov = options.fov;
  6901. this._fov = undefined;
  6902. this._fovy = undefined;
  6903. this._sseDenominator = undefined;
  6904. this.aspectRatio = options.aspectRatio;
  6905. this._aspectRatio = undefined;
  6906. this.near = options.near;
  6907. this._near = this.near;
  6908. this.far = options.far;
  6909. this._far = this.far;
  6910. this.xOffset = options.xOffset;
  6911. this._xOffset = this.xOffset;
  6912. this.yOffset = options.yOffset;
  6913. this._yOffset = this.yOffset;
  6914. }
  6915. clone() {
  6916. return new PerspectiveFrustum({
  6917. aspectRatio: this.aspectRatio,
  6918. fov: this.fov,
  6919. near: this.near,
  6920. far: this.far
  6921. });
  6922. }
  6923. equals(other) {
  6924. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  6925. return false;
  6926. }
  6927. update(this);
  6928. update(other);
  6929. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  6930. }
  6931. get projectionMatrix() {
  6932. update(this);
  6933. return this._offCenterFrustum.projectionMatrix;
  6934. }
  6935. get infiniteProjectionMatrix() {
  6936. update(this);
  6937. return this._offCenterFrustum.infiniteProjectionMatrix;
  6938. }
  6939. get fovy() {
  6940. update(this);
  6941. return this._fovy;
  6942. }
  6943. get sseDenominator() {
  6944. update(this);
  6945. return this._sseDenominator;
  6946. }
  6947. computeCullingVolume(position, direction, up) {
  6948. update(this);
  6949. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  6950. }
  6951. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6952. update(this);
  6953. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  6954. }
  6955. }
  6956. function update(frustum) {
  6957. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  6958. const f = frustum._offCenterFrustum;
  6959. if (frustum.fov !== frustum._fov || frustum.aspectRatio !== frustum._aspectRatio || frustum.near !== frustum._near || frustum.far !== frustum._far || frustum.xOffset !== frustum._xOffset || frustum.yOffset !== frustum._yOffset) {
  6960. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  6961. assert$4(frustum.aspectRatio > 0);
  6962. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  6963. frustum._aspectRatio = frustum.aspectRatio;
  6964. frustum._fov = frustum.fov;
  6965. frustum._fovy = frustum.aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum.aspectRatio) * 2.0;
  6966. frustum._near = frustum.near;
  6967. frustum._far = frustum.far;
  6968. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  6969. frustum._xOffset = frustum.xOffset;
  6970. frustum._yOffset = frustum.yOffset;
  6971. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  6972. f.bottom = -f.top;
  6973. f.right = frustum.aspectRatio * f.top;
  6974. f.left = -f.right;
  6975. f.near = frustum.near;
  6976. f.far = frustum.far;
  6977. f.right += frustum.xOffset;
  6978. f.left += frustum.xOffset;
  6979. f.top += frustum.yOffset;
  6980. f.bottom += frustum.yOffset;
  6981. }
  6982. }
  6983. new Vector3();
  6984. new Vector3();
  6985. new Vector3();
  6986. new Vector3();
  6987. new Vector3();
  6988. new Vector3();
  6989. new Vector3();
  6990. new Vector3();
  6991. new Vector3();
  6992. new Vector3();
  6993. new Vector3();
  6994. new Vector3();
  6995. new Matrix3();
  6996. new Matrix3();
  6997. new Matrix3();
  6998. new Matrix3();
  6999. new Matrix3();
  7000. new Vector3();
  7001. new Vector3();
  7002. new Vector3();
  7003. new Vector3();
  7004. new Vector3();
  7005. new Matrix3();
  7006. ({
  7007. diagonal: new Matrix3(),
  7008. unitary: new Matrix3()
  7009. });
  7010. const scratchVector$2 = new Vector3();
  7011. const scratchPosition = new Vector3();
  7012. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7013. function getFrameState(viewport, frameNumber) {
  7014. const {
  7015. cameraDirection,
  7016. cameraUp,
  7017. height
  7018. } = viewport;
  7019. const {
  7020. metersPerUnit
  7021. } = viewport.distanceScales;
  7022. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7023. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7024. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7025. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7026. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7027. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7028. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7029. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7030. return {
  7031. camera: {
  7032. position: cameraPositionCartesian,
  7033. direction: cameraDirectionCartesian,
  7034. up: cameraUpCartesian
  7035. },
  7036. viewport,
  7037. height,
  7038. cullingVolume,
  7039. frameNumber,
  7040. sseDenominator: 1.15
  7041. };
  7042. }
  7043. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7044. const frustumPlanes = viewport.getFrustumPlanes();
  7045. let i = 0;
  7046. for (const dir in frustumPlanes) {
  7047. const plane = frustumPlanes[dir];
  7048. const distanceToCenter = plane.normal.dot(viewport.center);
  7049. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7050. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7051. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7052. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7053. }
  7054. }
  7055. const WGS84_RADIUS_X = 6378137.0;
  7056. const WGS84_RADIUS_Y = 6378137.0;
  7057. const WGS84_RADIUS_Z = 6356752.3142451793;
  7058. const scratchVector$1 = new Vector3();
  7059. function getZoomFromBoundingVolume(boundingVolume) {
  7060. const {
  7061. halfAxes,
  7062. radius,
  7063. width,
  7064. height
  7065. } = boundingVolume;
  7066. if (halfAxes) {
  7067. const obbSize = getObbSize(halfAxes);
  7068. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7069. } else if (radius) {
  7070. return Math.log2(WGS84_RADIUS_Z / radius);
  7071. } else if (height && width) {
  7072. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7073. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7074. return (zoomX + zoomY) / 2;
  7075. }
  7076. return 1;
  7077. }
  7078. function getObbSize(halfAxes) {
  7079. halfAxes.getColumn(0, scratchVector$1);
  7080. const axeY = halfAxes.getColumn(1);
  7081. const axeZ = halfAxes.getColumn(2);
  7082. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7083. const size = farthestVertex.len();
  7084. return size;
  7085. }
  7086. const TILE_CONTENT_STATE = {
  7087. UNLOADED: 0,
  7088. LOADING: 1,
  7089. PROCESSING: 2,
  7090. READY: 3,
  7091. EXPIRED: 4,
  7092. FAILED: 5
  7093. };
  7094. const TILE_REFINEMENT = {
  7095. ADD: 1,
  7096. REPLACE: 2
  7097. };
  7098. const TILE_TYPE = {
  7099. EMPTY: 'empty',
  7100. SCENEGRAPH: 'scenegraph',
  7101. POINTCLOUD: 'pointcloud',
  7102. MESH: 'mesh'
  7103. };
  7104. const TILESET_TYPE = {
  7105. I3S: 'I3S',
  7106. TILES3D: 'TILES3D'
  7107. };
  7108. const LOD_METRIC_TYPE = {
  7109. GEOMETRIC_ERROR: 'geometricError',
  7110. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7111. };
  7112. const TILE3D_OPTIMIZATION_HINT = {
  7113. NOT_COMPUTED: -1,
  7114. USE_OPTIMIZATION: 1,
  7115. SKIP_OPTIMIZATION: 0
  7116. };
  7117. function defined$3(x) {
  7118. return x !== undefined && x !== null;
  7119. }
  7120. const scratchScale = new Vector3();
  7121. const scratchNorthWest = new Vector3();
  7122. const scratchSouthEast = new Vector3();
  7123. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7124. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7125. if (boundingVolumeHeader.box) {
  7126. return createBox(boundingVolumeHeader.box, transform, result);
  7127. }
  7128. if (boundingVolumeHeader.region) {
  7129. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7130. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7131. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7132. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7133. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7134. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7135. }
  7136. if (boundingVolumeHeader.sphere) {
  7137. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7138. }
  7139. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7140. }
  7141. function createBox(box, transform, result) {
  7142. const center = new Vector3(box[0], box[1], box[2]);
  7143. result && (result.oriCenter = center)//add
  7144. transform.transform(center, center);
  7145. let origin = [];
  7146. if (box.length === 10) {
  7147. const halfSize = box.slice(3, 6);
  7148. const quaternion = new Quaternion();
  7149. quaternion.fromArray(box, 6);
  7150. const x = new Vector3([1, 0, 0]);
  7151. const y = new Vector3([0, 1, 0]);
  7152. const z = new Vector3([0, 0, 1]);
  7153. x.transformByQuaternion(quaternion);
  7154. x.scale(halfSize[0]);
  7155. y.transformByQuaternion(quaternion);
  7156. y.scale(halfSize[1]);
  7157. z.transformByQuaternion(quaternion);
  7158. z.scale(halfSize[2]);
  7159. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7160. } else {
  7161. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7162. }
  7163. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7164. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7165. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7166. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7167. if (defined$3(result)) {
  7168. result.center = center;
  7169. result.halfAxes = halfAxes;
  7170. return result;
  7171. }
  7172. return new OrientedBoundingBox(center, halfAxes);
  7173. }
  7174. function createSphere(sphere, transform, result) {
  7175. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7176. transform.transform(center, center);
  7177. const scale = transform.getScale(scratchScale);
  7178. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7179. const radius = sphere[3] * uniformScale;
  7180. if (defined$3(result)) {
  7181. result.center = center;
  7182. result.radius = radius;
  7183. return result;
  7184. }
  7185. return new BoundingSphere(center, radius);
  7186. }
  7187. new Vector3();
  7188. new Vector3();
  7189. new Matrix4();
  7190. new Vector3();
  7191. new Vector3();
  7192. new Vector3();
  7193. function fog(distanceToCamera, density) {
  7194. const scalar = distanceToCamera * density;
  7195. return 1.0 - Math.exp(-(scalar * scalar));
  7196. }
  7197. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7198. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7199. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7200. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7201. const dynamicError = fog(distanceToCamera, density) * factor;
  7202. return dynamicError;
  7203. }
  7204. return 0;
  7205. }
  7206. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7207. const tileset = tile.tileset;
  7208. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7209. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7210. if (lodMetricValue === 0.0) {
  7211. return 0.0;
  7212. }
  7213. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7214. const {
  7215. height,
  7216. sseDenominator
  7217. } = frameState;
  7218. const {
  7219. viewDistanceScale
  7220. } = tileset.options;
  7221. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7222. error -= getDynamicScreenSpaceError(tileset, distance);
  7223. return error;
  7224. }
  7225. function getLodStatus(tile, frameState) {
  7226. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7227. return 'DIG';
  7228. }
  7229. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7230. if (screenSize < 2) {
  7231. return 'OUT';
  7232. }
  7233. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7234. return 'DRAW';
  7235. } else if (tile.header.children) {
  7236. return 'DIG';
  7237. }
  7238. return 'OUT';
  7239. }
  7240. function getProjectedRadius(tile, frameState) {
  7241. const originalViewport = frameState.viewport;
  7242. const ViewportClass = originalViewport.constructor;
  7243. const {
  7244. longitude,
  7245. latitude,
  7246. height,
  7247. width,
  7248. bearing,
  7249. zoom
  7250. } = originalViewport;
  7251. const viewport = new ViewportClass({
  7252. longitude,
  7253. latitude,
  7254. height,
  7255. width,
  7256. bearing,
  7257. zoom,
  7258. pitch: 0
  7259. });
  7260. const mbsLat = tile.header.mbs[1];
  7261. const mbsLon = tile.header.mbs[0];
  7262. const mbsZ = tile.header.mbs[2];
  7263. const mbsR = tile.header.mbs[3];
  7264. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7265. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7266. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7267. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7268. const enuToCartesianMatrix = new Matrix4();
  7269. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7270. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7271. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7272. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7273. const extraZ = projection * projection / cameraPositionEnu[2];
  7274. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7275. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7276. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7277. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7278. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7279. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7280. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7281. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7282. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7283. return projectedRadius;
  7284. }
  7285. function get3dTilesOptions(tileset) {
  7286. return {
  7287. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7288. };
  7289. }
  7290. class ManagedArray {
  7291. constructor(length = 0) {
  7292. _defineProperty(this, "_map", new Map());
  7293. _defineProperty(this, "_array", void 0);
  7294. _defineProperty(this, "_length", void 0);
  7295. this._array = new Array(length);
  7296. this._length = length;
  7297. }
  7298. get length() {
  7299. return this._length;
  7300. }
  7301. set length(length) {
  7302. this._length = length;
  7303. if (length > this._array.length) {
  7304. this._array.length = length;
  7305. }
  7306. }
  7307. get values() {
  7308. return this._array;
  7309. }
  7310. get(index) {
  7311. assert$7(index < this._array.length);
  7312. return this._array[index];
  7313. }
  7314. set(index, element) {
  7315. assert$7(index >= 0);
  7316. if (index >= this.length) {
  7317. this.length = index + 1;
  7318. }
  7319. if (this._map.has(this._array[index])) {
  7320. this._map.delete(this._array[index]);
  7321. }
  7322. this._array[index] = element;
  7323. this._map.set(element, index);
  7324. }
  7325. delete(element) {
  7326. const index = this._map.get(element);
  7327. if (index >= 0) {
  7328. this._array.splice(index, 1);
  7329. this._map.delete(element);
  7330. this.length--;
  7331. }
  7332. }
  7333. peek() {
  7334. return this._array[this._length - 1];
  7335. }
  7336. push(element) {
  7337. if (!this._map.has(element)) {
  7338. const index = this.length++;
  7339. this._array[index] = element;
  7340. this._map.set(element, index);
  7341. }
  7342. }
  7343. pop() {
  7344. const element = this._array[--this.length];
  7345. this._map.delete(element);
  7346. return element;
  7347. }
  7348. reserve(length) {
  7349. assert$7(length >= 0);
  7350. if (length > this._array.length) {
  7351. this._array.length = length;
  7352. }
  7353. }
  7354. resize(length) {
  7355. assert$7(length >= 0);
  7356. this.length = length;
  7357. }
  7358. trim(length) {
  7359. if (length === null || length === undefined) {
  7360. length = this.length;
  7361. }
  7362. this._array.length = length;
  7363. }
  7364. reset() {
  7365. this._array = [];
  7366. this._map = new Map();
  7367. this._length = 0;
  7368. }
  7369. find(target) {
  7370. return this._map.has(target);
  7371. }
  7372. }
  7373. const DEFAULT_PROPS$1 = {
  7374. loadSiblings: false,
  7375. skipLevelOfDetail: false,
  7376. maximumScreenSpaceError: 2,
  7377. updateTransforms: true,
  7378. onTraversalEnd: () => {},
  7379. viewportTraversersMap: {},
  7380. basePath: ''
  7381. };
  7382. class TilesetTraverser {
  7383. constructor(options) {
  7384. _defineProperty(this, "options", void 0);
  7385. _defineProperty(this, "root", void 0);
  7386. _defineProperty(this, "requestedTiles", void 0);
  7387. _defineProperty(this, "selectedTiles", void 0);
  7388. _defineProperty(this, "emptyTiles", void 0);
  7389. _defineProperty(this, "_traversalStack", void 0);
  7390. _defineProperty(this, "_emptyTraversalStack", void 0);
  7391. _defineProperty(this, "_frameNumber", void 0);
  7392. this.options = { ...DEFAULT_PROPS$1,
  7393. ...options
  7394. };
  7395. this._traversalStack = new ManagedArray();
  7396. this._emptyTraversalStack = new ManagedArray();
  7397. this._frameNumber = null;
  7398. this.root = null;
  7399. this.selectedTiles = {};
  7400. this.requestedTiles = {};
  7401. this.emptyTiles = {};
  7402. }
  7403. traverse(root, frameState, options) {
  7404. this.root = root;
  7405. this.options = { ...this.options,
  7406. ...options
  7407. };
  7408. this.reset();
  7409. this.updateTile(root, frameState);
  7410. this._frameNumber = frameState.frameNumber;
  7411. this.executeTraversal(root, frameState);
  7412. }
  7413. reset() {
  7414. this.requestedTiles = {};
  7415. this.selectedTiles = {};
  7416. this.emptyTiles = {};
  7417. this._traversalStack.reset();
  7418. this._emptyTraversalStack.reset();
  7419. }
  7420. executeTraversal(root, frameState) {// 遍历root
  7421. const stack = this._traversalStack;
  7422. root._selectionDepth = 1;
  7423. stack.push(root);
  7424. while (stack.length > 0) {
  7425. const tile = stack.pop();
  7426. let shouldRefine = false;
  7427. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7428. if (this.canTraverse(tile, frameState) && tile.depth < this.options.maxDepth) {//add maxDepth
  7429. this.updateChildTiles(tile, frameState);
  7430. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7431. }
  7432. const parent = tile.parent;
  7433. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7434. const stoppedRefining = !shouldRefine;
  7435. if (!tile.hasRenderContent) {
  7436. this.emptyTiles[tile.id] = tile;
  7437. this.loadTile(tile, frameState);
  7438. if (stoppedRefining) {
  7439. this.selectTile(tile, frameState);
  7440. }
  7441. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7442. this.loadTile(tile, frameState);
  7443. this.selectTile(tile, frameState);
  7444. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7445. this.loadTile(tile, frameState);
  7446. if (stoppedRefining) {
  7447. this.selectTile(tile, frameState);
  7448. }
  7449. }
  7450. this.touchTile(tile, frameState);
  7451. tile._shouldRefine = shouldRefine && parentRefines;
  7452. }
  7453. this.options.onTraversalEnd(frameState);
  7454. }
  7455. updateChildTiles(tile, frameState) {
  7456. const children = tile.children;
  7457. for (const child of children) {
  7458. this.updateTile(child, frameState);
  7459. }
  7460. return true;
  7461. }
  7462. updateAndPushChildren(tile, frameState, stack, depth) {
  7463. const {
  7464. loadSiblings,
  7465. skipLevelOfDetail
  7466. } = this.options;
  7467. const children = tile.children;
  7468. children.sort(this.compareDistanceToCamera.bind(this));
  7469. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7470. let hasVisibleChild = false;
  7471. let refines = true;
  7472. for (const child of children) {
  7473. child._selectionDepth = depth;
  7474. if (child.isVisibleAndInRequestVolume) {
  7475. if (stack.find(child)) {
  7476. stack.delete(child);
  7477. }
  7478. stack.push(child);
  7479. hasVisibleChild = true;
  7480. } else if (checkRefines || loadSiblings) {
  7481. this.loadTile(child, frameState);
  7482. this.touchTile(child, frameState);
  7483. }
  7484. if (checkRefines) {
  7485. let childRefines;
  7486. if (!child._inRequestVolume) {
  7487. childRefines = false;
  7488. } else if (!child.hasRenderContent) {
  7489. childRefines = this.executeEmptyTraversal(child, frameState);
  7490. } else {
  7491. childRefines = child.contentAvailable;
  7492. }
  7493. refines = refines && childRefines;
  7494. if (!refines) {
  7495. return false;
  7496. }
  7497. }
  7498. }
  7499. if (!hasVisibleChild) {
  7500. refines = false;
  7501. }
  7502. return refines;
  7503. }
  7504. updateTile(tile, frameState) {
  7505. this.updateTileVisibility(tile, frameState);
  7506. }
  7507. selectTile(tile, frameState) {
  7508. if (this.shouldSelectTile(tile)) {
  7509. tile._selectedFrame = frameState.frameNumber;
  7510. this.selectedTiles[tile.id] = tile;
  7511. }
  7512. }
  7513. loadTile(tile, frameState) {
  7514. if (this.shouldLoadTile(tile)) {
  7515. tile._requestedFrame = frameState.frameNumber;
  7516. tile._priority = tile._getPriority();
  7517. this.requestedTiles[tile.id] = tile;
  7518. }
  7519. }
  7520. touchTile(tile, frameState) {
  7521. tile.tileset._cache.touch(tile);
  7522. tile._touchedFrame = frameState.frameNumber;
  7523. }
  7524. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7525. if (!tile.hasChildren) {
  7526. return false;
  7527. }
  7528. if (tile.hasTilesetContent) {
  7529. return !tile.contentExpired;
  7530. }
  7531. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7532. return false;
  7533. }
  7534. return this.shouldRefine(tile, frameState, useParentMetric);
  7535. }
  7536. shouldLoadTile(tile) {
  7537. return tile.hasUnloadedContent || tile.contentExpired;
  7538. }
  7539. shouldSelectTile(tile) {
  7540. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7541. }
  7542. shouldRefine(tile, frameState, useParentMetric) {
  7543. let screenSpaceError = tile._screenSpaceError;
  7544. if (useParentMetric) {
  7545. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7546. }
  7547. return screenSpaceError > this.options.maximumScreenSpaceError;
  7548. }
  7549. updateTileVisibility(tile, frameState) {
  7550. const viewportIds = [];
  7551. if (this.options.viewportTraversersMap) {
  7552. for (const key in this.options.viewportTraversersMap) {
  7553. const value = this.options.viewportTraversersMap[key];
  7554. if (value === frameState.viewport.id) {
  7555. viewportIds.push(key);
  7556. }
  7557. }
  7558. } else {
  7559. viewportIds.push(frameState.viewport.id);
  7560. }
  7561. tile.updateVisibility(frameState, viewportIds);
  7562. }
  7563. compareDistanceToCamera(b, a) {
  7564. return b._distanceToCamera - a._distanceToCamera;
  7565. }
  7566. anyChildrenVisible(tile, frameState) {
  7567. let anyVisible = false;
  7568. for (const child of tile.children) {
  7569. child.updateVisibility(frameState);
  7570. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7571. }
  7572. return anyVisible;
  7573. }
  7574. executeEmptyTraversal(root, frameState) {
  7575. let allDescendantsLoaded = true;
  7576. const stack = this._emptyTraversalStack;
  7577. stack.push(root);
  7578. while (stack.length > 0 && allDescendantsLoaded) {
  7579. const tile = stack.pop();
  7580. this.updateTile(tile, frameState);
  7581. if (!tile.isVisibleAndInRequestVolume) {
  7582. this.loadTile(tile, frameState);
  7583. }
  7584. this.touchTile(tile, frameState);
  7585. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7586. if (traverse) {
  7587. const children = tile.children;
  7588. for (const child of children) {
  7589. if (stack.find(child)) {
  7590. stack.delete(child);
  7591. }
  7592. stack.push(child);
  7593. }
  7594. } else if (!tile.contentAvailable) {
  7595. allDescendantsLoaded = false;
  7596. }
  7597. }
  7598. return allDescendantsLoaded;
  7599. }
  7600. }
  7601. const scratchVector = new Vector3();
  7602. function defined$2(x) {
  7603. return x !== undefined && x !== null;
  7604. }
  7605. class TileHeader {
  7606. constructor(tileset, header, parentHeader, extendedId = '') {
  7607. _defineProperty(this, "tileset", void 0);
  7608. _defineProperty(this, "header", void 0);
  7609. _defineProperty(this, "id", void 0);
  7610. _defineProperty(this, "url", void 0);
  7611. _defineProperty(this, "parent", void 0);
  7612. _defineProperty(this, "refine", void 0);
  7613. _defineProperty(this, "type", void 0);
  7614. _defineProperty(this, "contentUrl", void 0);
  7615. _defineProperty(this, "lodMetricType", void 0);
  7616. _defineProperty(this, "lodMetricValue", void 0);
  7617. _defineProperty(this, "boundingVolume", void 0);
  7618. _defineProperty(this, "content", void 0);
  7619. _defineProperty(this, "contentState", void 0);
  7620. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7621. _defineProperty(this, "children", void 0);
  7622. _defineProperty(this, "depth", void 0);
  7623. _defineProperty(this, "viewportIds", void 0);
  7624. _defineProperty(this, "transform", void 0);
  7625. _defineProperty(this, "extensions", void 0);
  7626. _defineProperty(this, "userData", void 0);
  7627. _defineProperty(this, "computedTransform", void 0);
  7628. _defineProperty(this, "hasEmptyContent", void 0);
  7629. _defineProperty(this, "hasTilesetContent", void 0);
  7630. _defineProperty(this, "traverser", void 0);
  7631. _defineProperty(this, "_cacheNode", void 0);
  7632. _defineProperty(this, "_frameNumber", void 0);
  7633. _defineProperty(this, "_lodJudge", void 0);
  7634. _defineProperty(this, "_expireDate", void 0);
  7635. _defineProperty(this, "_expiredContent", void 0);
  7636. _defineProperty(this, "_shouldRefine", void 0);
  7637. _defineProperty(this, "_distanceToCamera", void 0);
  7638. _defineProperty(this, "_centerZDepth", void 0);
  7639. _defineProperty(this, "_screenSpaceError", void 0);
  7640. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7641. _defineProperty(this, "_visible", void 0);
  7642. _defineProperty(this, "_inRequestVolume", void 0);
  7643. _defineProperty(this, "_stackLength", void 0);
  7644. _defineProperty(this, "_selectionDepth", void 0);
  7645. _defineProperty(this, "_touchedFrame", void 0);
  7646. _defineProperty(this, "_visitedFrame", void 0);
  7647. _defineProperty(this, "_selectedFrame", void 0);
  7648. _defineProperty(this, "_requestedFrame", void 0);
  7649. _defineProperty(this, "_priority", void 0);
  7650. _defineProperty(this, "_contentBoundingVolume", void 0);
  7651. _defineProperty(this, "_viewerRequestVolume", void 0);
  7652. _defineProperty(this, "_initialTransform", void 0);
  7653. this.header = header;
  7654. this.tileset = tileset;
  7655. this.id = extendedId || header.id;
  7656. this.url = header.url;
  7657. this.parent = parentHeader;
  7658. this.refine = this._getRefine(header.refine);
  7659. this.type = header.type;
  7660. this.contentUrl = header.contentUrl;
  7661. this.lodMetricType = 'geometricError';
  7662. this.lodMetricValue = 0;
  7663. this.boundingVolume = null;
  7664. this.content = null;
  7665. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7666. this.gpuMemoryUsageInBytes = 0;
  7667. this.children = [];
  7668. this.hasEmptyContent = false;
  7669. this.hasTilesetContent = false;
  7670. this.depth = 0;
  7671. this.viewportIds = [];
  7672. this.userData = {};
  7673. this.extensions = null;
  7674. this._priority = 0;
  7675. this._touchedFrame = 0;
  7676. this._visitedFrame = 0;
  7677. this._selectedFrame = 0;
  7678. this._requestedFrame = 0;
  7679. this._screenSpaceError = 0;
  7680. this._cacheNode = null;
  7681. this._frameNumber = null;
  7682. this._cacheNode = null;
  7683. this.traverser = new TilesetTraverser({});
  7684. this._shouldRefine = false;
  7685. this._distanceToCamera = 0;
  7686. this._centerZDepth = 0;
  7687. this._visible = undefined;
  7688. this._inRequestVolume = false;
  7689. this._stackLength = 0;
  7690. this._selectionDepth = 0;
  7691. this._initialTransform = new Matrix4();
  7692. this.transform = new Matrix4();
  7693. this._initializeLodMetric(header);
  7694. this._initializeTransforms(header);
  7695. this._initializeBoundingVolumes(header);
  7696. this._initializeContent(header);
  7697. this._initializeRenderingState(header);
  7698. this._lodJudge = null;
  7699. this._expireDate = null;
  7700. this._expiredContent = null;
  7701. Object.seal(this);
  7702. }
  7703. destroy() {
  7704. this.header = null;
  7705. }
  7706. isDestroyed() {
  7707. return this.header === null;
  7708. }
  7709. get selected() {
  7710. return this._selectedFrame === this.tileset._frameNumber;
  7711. }
  7712. get isVisible() {
  7713. return this._visible;
  7714. }
  7715. get isVisibleAndInRequestVolume() {
  7716. return this._visible && this._inRequestVolume;
  7717. }
  7718. get hasRenderContent() {
  7719. return !this.hasEmptyContent && !this.hasTilesetContent;
  7720. }
  7721. get hasChildren() {
  7722. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7723. }
  7724. get contentReady() {
  7725. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7726. }
  7727. get contentAvailable() {
  7728. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7729. }
  7730. get hasUnloadedContent() {
  7731. return this.hasRenderContent && this.contentUnloaded;
  7732. }
  7733. get contentUnloaded() {
  7734. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7735. }
  7736. get contentExpired() {
  7737. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7738. }
  7739. get contentFailed() {
  7740. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7741. }
  7742. getScreenSpaceError(frameState, useParentLodMetric) {
  7743. switch (this.tileset.type) {
  7744. case TILESET_TYPE.I3S:
  7745. return getProjectedRadius(this, frameState);
  7746. case TILESET_TYPE.TILES3D:
  7747. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7748. default:
  7749. throw new Error('Unsupported tileset type');
  7750. }
  7751. }
  7752. _getPriority() {
  7753. const traverser = this.tileset._traverser;
  7754. const {
  7755. skipLevelOfDetail
  7756. } = traverser.options;
  7757. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7758. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7759. return -1;
  7760. }
  7761. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7762. return -1;
  7763. }
  7764. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7765. return -1;
  7766. }
  7767. const parent = this.parent;
  7768. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7769. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7770. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7771. return Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7772. }
  7773. async loadContent() {
  7774. if (this.hasEmptyContent) {
  7775. return false;
  7776. }
  7777. if (this.content) {
  7778. return true;
  7779. }
  7780. const expired = this.contentExpired;
  7781. if (expired) {
  7782. this._expireDate = null;
  7783. }
  7784. this.contentState = TILE_CONTENT_STATE.LOADING;
  7785. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7786. if (!requestToken) {
  7787. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7788. return false;
  7789. }
  7790. try {
  7791. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  7792. const loader = this.tileset.loader;
  7793. const options = { ...this.tileset.loadOptions,
  7794. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7795. isTileset: this.type === 'json',
  7796. ...this._getLoaderSpecificOptions(loader.id)
  7797. }
  7798. };
  7799. this.content = await load(contentUrl, loader, options);
  7800. // !zeg改
  7801. if (this.tileset.options.maxDepth < this.depth) {
  7802. this.unloadContent()
  7803. return false
  7804. }
  7805. if (this.tileset.options.contentLoader) {
  7806. await this.tileset.options.contentLoader(this);
  7807. }
  7808. if (this._isTileset()) {
  7809. this.tileset._initializeTileHeaders(this.content, this);
  7810. }
  7811. this.contentState = TILE_CONTENT_STATE.READY;
  7812. this._onContentLoaded();
  7813. return true;
  7814. } catch (error) {
  7815. this.contentState = TILE_CONTENT_STATE.FAILED;
  7816. throw error;
  7817. } finally {
  7818. requestToken.done();
  7819. }
  7820. }
  7821. unloadContent() {
  7822. if (this.content && this.content.destroy) {
  7823. this.content.destroy();
  7824. }
  7825. this.content = null;
  7826. if (this.header.content && this.header.content.destroy) {
  7827. this.header.content.destroy();
  7828. }
  7829. this.header.content = null;
  7830. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7831. return true;
  7832. }
  7833. updateVisibility(frameState, viewportIds) {
  7834. if (this._frameNumber === frameState.frameNumber) {
  7835. return;
  7836. }
  7837. const parent = this.parent;
  7838. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7839. if (this.tileset._traverser.options.updateTransforms) {
  7840. const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;
  7841. this._updateTransform(parentTransform);
  7842. }
  7843. this._distanceToCamera = this.distanceToTile(frameState);
  7844. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7845. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7846. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7847. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7848. this._frameNumber = frameState.frameNumber;
  7849. this.viewportIds = viewportIds;
  7850. }
  7851. visibility(frameState, parentVisibilityPlaneMask) {
  7852. const {
  7853. cullingVolume
  7854. } = frameState;
  7855. const {
  7856. boundingVolume
  7857. } = this;
  7858. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7859. }
  7860. contentVisibility() {
  7861. return true;
  7862. }
  7863. distanceToTile(frameState) {
  7864. const boundingVolume = this.boundingVolume;
  7865. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7866. }
  7867. cameraSpaceZDepth({
  7868. camera
  7869. }) {
  7870. const boundingVolume = this.boundingVolume;
  7871. scratchVector.subVectors(boundingVolume.center, camera.position);
  7872. return camera.direction.dot(scratchVector);
  7873. }
  7874. insideViewerRequestVolume(frameState) {
  7875. const viewerRequestVolume = this._viewerRequestVolume;
  7876. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7877. }
  7878. updateExpiration() {
  7879. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7880. const now = Date.now();
  7881. if (Date.lessThan(this._expireDate, now)) {
  7882. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7883. this._expiredContent = this.content;
  7884. }
  7885. }
  7886. }
  7887. get extras() {
  7888. return this.header.extras;
  7889. }
  7890. _initializeLodMetric(header) {
  7891. if ('lodMetricType' in header) {
  7892. this.lodMetricType = header.lodMetricType;
  7893. } else {
  7894. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7895. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7896. }
  7897. if ('lodMetricValue' in header) {
  7898. this.lodMetricValue = header.lodMetricValue;
  7899. } else {
  7900. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  7901. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  7902. }
  7903. }
  7904. _initializeTransforms(tileHeader) {
  7905. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  7906. const parent = this.parent;
  7907. const tileset = this.tileset;
  7908. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : tileset.modelMatrix.clone();
  7909. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  7910. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  7911. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  7912. }
  7913. _initializeBoundingVolumes(tileHeader) {
  7914. this._contentBoundingVolume = null;
  7915. this._viewerRequestVolume = null;
  7916. this._updateBoundingVolume(tileHeader);
  7917. }
  7918. _initializeContent(tileHeader) {
  7919. this.content = {
  7920. _tileset: this.tileset,
  7921. _tile: this
  7922. };
  7923. this.hasEmptyContent = true;
  7924. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7925. this.hasTilesetContent = false;
  7926. if (tileHeader.contentUrl) {
  7927. this.content = null;
  7928. this.hasEmptyContent = false;
  7929. }
  7930. }
  7931. _initializeRenderingState(header) {
  7932. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  7933. this._shouldRefine = false;
  7934. this._distanceToCamera = 0;
  7935. this._centerZDepth = 0;
  7936. this._screenSpaceError = 0;
  7937. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  7938. this._visible = undefined;
  7939. this._inRequestVolume = false;
  7940. this._stackLength = 0;
  7941. this._selectionDepth = 0;
  7942. this._frameNumber = 0;
  7943. this._touchedFrame = 0;
  7944. this._visitedFrame = 0;
  7945. this._selectedFrame = 0;
  7946. this._requestedFrame = 0;
  7947. this._priority = 0.0;
  7948. }
  7949. _getRefine(refine) {
  7950. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  7951. }
  7952. _isTileset() {
  7953. return this.contentUrl.indexOf('.json') !== -1;
  7954. }
  7955. _onContentLoaded() {
  7956. switch (this.content && this.content.type) {
  7957. case 'vctr':
  7958. case 'geom':
  7959. this.tileset._traverser.disableSkipLevelOfDetail = true;
  7960. break;
  7961. }
  7962. if (this._isTileset()) {
  7963. this.hasTilesetContent = true;
  7964. }
  7965. }
  7966. _updateBoundingVolume(header) {
  7967. this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume);
  7968. const content = header.content;
  7969. if (!content) {
  7970. return;
  7971. }
  7972. if (content.boundingVolume) {
  7973. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume);
  7974. }
  7975. if (header.viewerRequestVolume) {
  7976. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume);
  7977. }
  7978. }
  7979. _updateTransform(parentTransform = new Matrix4()) {
  7980. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  7981. const didTransformChange = !computedTransform.equals(this.computedTransform);
  7982. if (!didTransformChange) {
  7983. return;
  7984. }
  7985. this.computedTransform = computedTransform;
  7986. this._updateBoundingVolume(this.header);
  7987. }
  7988. _getLoaderSpecificOptions(loaderId) {
  7989. switch (loaderId) {
  7990. case 'i3s':
  7991. return { ...this.tileset.options.i3s,
  7992. tile: this.header,
  7993. tileset: this.tileset.tileset,
  7994. isTileHeader: false
  7995. };
  7996. case '3d-tiles':
  7997. case 'cesium-ion':
  7998. default:
  7999. return get3dTilesOptions(this.tileset.tileset);
  8000. }
  8001. }
  8002. }
  8003. class Tileset3DTraverser extends TilesetTraverser {
  8004. compareDistanceToCamera(a, b) {
  8005. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8006. }
  8007. updateTileVisibility(tile, frameState) {
  8008. super.updateTileVisibility(tile, frameState);
  8009. if (!tile.isVisibleAndInRequestVolume) {
  8010. return;
  8011. }
  8012. const hasChildren = tile.children.length > 0;
  8013. if (tile.hasTilesetContent && hasChildren) {
  8014. const firstChild = tile.children[0];
  8015. this.updateTileVisibility(firstChild, frameState);
  8016. tile._visible = firstChild._visible;
  8017. return;
  8018. }
  8019. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8020. tile._visible = false;
  8021. return;
  8022. }
  8023. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8024. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8025. if (replace && useOptimization && hasChildren) {
  8026. if (!this.anyChildrenVisible(tile, frameState)) {
  8027. tile._visible = false;
  8028. return;
  8029. }
  8030. }
  8031. }
  8032. meetsScreenSpaceErrorEarly(tile, frameState) {
  8033. const {
  8034. parent
  8035. } = tile;
  8036. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8037. return false;
  8038. }
  8039. return !this.shouldRefine(tile, frameState, true);
  8040. }
  8041. }
  8042. const STATUS = {
  8043. REQUESTED: 'REQUESTED',
  8044. COMPLETED: 'COMPLETED',
  8045. ERROR: 'ERROR'
  8046. };
  8047. class I3STileManager {
  8048. constructor() {
  8049. _defineProperty(this, "_statusMap", void 0);
  8050. this._statusMap = {};
  8051. }
  8052. add(request, key, callback, frameState) {
  8053. if (!this._statusMap[key]) {
  8054. this._statusMap[key] = {
  8055. request,
  8056. callback,
  8057. key,
  8058. frameState,
  8059. status: STATUS.REQUESTED
  8060. };
  8061. request().then(data => {
  8062. this._statusMap[key].status = STATUS.COMPLETED;
  8063. this._statusMap[key].callback(data, frameState);
  8064. }).catch(error => {
  8065. this._statusMap[key].status = STATUS.ERROR;
  8066. callback(error);
  8067. });
  8068. }
  8069. }
  8070. update(key, frameState) {
  8071. if (this._statusMap[key]) {
  8072. this._statusMap[key].frameState = frameState;
  8073. }
  8074. }
  8075. find(key) {
  8076. return this._statusMap[key];
  8077. }
  8078. }
  8079. class I3STilesetTraverser extends TilesetTraverser {
  8080. constructor(options) {
  8081. super(options);
  8082. _defineProperty(this, "_tileManager", void 0);
  8083. this._tileManager = new I3STileManager();
  8084. }
  8085. shouldRefine(tile, frameState) {
  8086. tile._lodJudge = getLodStatus(tile, frameState);
  8087. return tile._lodJudge === 'DIG';
  8088. }
  8089. updateChildTiles(tile, frameState) {
  8090. const children = tile.header.children || [];
  8091. const childTiles = tile.children;
  8092. const tileset = tile.tileset;
  8093. for (const child of children) {
  8094. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8095. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8096. if (!childTile) {
  8097. let request = () => this._loadTile(child.id, tileset);
  8098. const cachedRequest = this._tileManager.find(extendedId);
  8099. if (!cachedRequest) {
  8100. if (tileset.tileset.nodePages) {
  8101. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8102. }
  8103. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8104. } else {
  8105. this._tileManager.update(extendedId, frameState);
  8106. }
  8107. } else if (childTile) {
  8108. this.updateTile(childTile, frameState);
  8109. }
  8110. }
  8111. return false;
  8112. }
  8113. async _loadTile(nodeId, tileset) {
  8114. const {
  8115. loader
  8116. } = tileset;
  8117. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8118. const options = { ...tileset.loadOptions,
  8119. i3s: { ...tileset.loadOptions.i3s,
  8120. isTileHeader: true,
  8121. loadContent: false
  8122. }
  8123. };
  8124. return await load(nodeUrl, loader, options);
  8125. }
  8126. _onTileLoad(header, tile, extendedId) {
  8127. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8128. tile.children.push(childTile);
  8129. const frameState = this._tileManager.find(childTile.id).frameState;
  8130. this.updateTile(childTile, frameState);
  8131. if (this._frameNumber === frameState.frameNumber) {
  8132. this.executeTraversal(childTile, frameState);
  8133. }
  8134. }
  8135. }
  8136. const DEFAULT_PROPS = {
  8137. description: '',
  8138. ellipsoid: Ellipsoid.WGS84,
  8139. modelMatrix: new Matrix4(),
  8140. throttleRequests: true,
  8141. maxRequests: 64,
  8142. maximumMemoryUsage: 32,
  8143. onTileLoad: () => {},
  8144. onTileUnload: () => {},
  8145. onTileError: () => {},
  8146. onTraversalComplete: selectedTiles => selectedTiles,
  8147. contentLoader: undefined,
  8148. viewDistanceScale: 1.0,
  8149. maximumScreenSpaceError: 8,
  8150. loadTiles: true,
  8151. updateTransforms: true,
  8152. viewportTraversersMap: null,
  8153. loadOptions: {
  8154. fetch: {}
  8155. },
  8156. attributions: [],
  8157. basePath: '',
  8158. i3s: {}
  8159. };
  8160. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8161. const TILES_IN_MEMORY = 'Tiles In Memory';
  8162. const TILES_IN_VIEW = 'Tiles In View';
  8163. const TILES_RENDERABLE = 'Tiles To Render';
  8164. const TILES_LOADED = 'Tiles Loaded';
  8165. const TILES_LOADING = 'Tiles Loading';
  8166. const TILES_UNLOADED = 'Tiles Unloaded';
  8167. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8168. const POINTS_COUNT = 'Points';
  8169. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8170. let tilesetSid = 0//add
  8171. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8172. constructor(json, options) {
  8173. super()
  8174. _defineProperty(this, "options", void 0);
  8175. _defineProperty(this, "loadOptions", void 0);
  8176. _defineProperty(this, "type", void 0);
  8177. _defineProperty(this, "tileset", void 0);
  8178. _defineProperty(this, "loader", void 0);
  8179. _defineProperty(this, "url", void 0);
  8180. _defineProperty(this, "basePath", void 0);
  8181. _defineProperty(this, "modelMatrix", void 0);
  8182. _defineProperty(this, "ellipsoid", void 0);
  8183. _defineProperty(this, "lodMetricType", void 0);
  8184. _defineProperty(this, "lodMetricValue", void 0);
  8185. _defineProperty(this, "refine", void 0);
  8186. _defineProperty(this, "root", void 0);
  8187. _defineProperty(this, "roots", void 0);
  8188. _defineProperty(this, "asset", void 0);
  8189. _defineProperty(this, "description", void 0);
  8190. _defineProperty(this, "properties", void 0);
  8191. _defineProperty(this, "extras", void 0);
  8192. _defineProperty(this, "attributions", void 0);
  8193. _defineProperty(this, "credits", void 0);
  8194. _defineProperty(this, "stats", void 0);
  8195. _defineProperty(this, "traverseCounter", void 0);
  8196. _defineProperty(this, "geometricError", void 0);
  8197. _defineProperty(this, "selectedTiles", void 0);
  8198. _defineProperty(this, "cartographicCenter", void 0);
  8199. _defineProperty(this, "cartesianCenter", void 0);
  8200. _defineProperty(this, "zoom", void 0);
  8201. _defineProperty(this, "boundingVolume", void 0);
  8202. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8203. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8204. _defineProperty(this, "_traverser", void 0);
  8205. _defineProperty(this, "_cache", void 0);
  8206. _defineProperty(this, "_requestScheduler", void 0);
  8207. _defineProperty(this, "_frameNumber", void 0);
  8208. _defineProperty(this, "_queryParamsString", void 0);
  8209. _defineProperty(this, "_queryParams", void 0);
  8210. _defineProperty(this, "_extensionsUsed", void 0);
  8211. _defineProperty(this, "_tiles", void 0);
  8212. _defineProperty(this, "_pendingCount", void 0);
  8213. _defineProperty(this, "lastUpdatedVieports", void 0);
  8214. _defineProperty(this, "_requestedTiles", void 0);
  8215. _defineProperty(this, "_emptyTiles", void 0);
  8216. _defineProperty(this, "frameStateData", void 0);
  8217. _defineProperty(this, "maximumMemoryUsage", void 0);
  8218. assert$7(json);
  8219. this.options = { ...DEFAULT_PROPS,
  8220. ...options
  8221. };
  8222. this.tileset = json;
  8223. this.loader = json.loader;
  8224. this.type = json.type;
  8225. this.url = json.url;
  8226. this.basePath = json.basePath || dirname(this.url);
  8227. this.modelMatrix = this.options.modelMatrix;
  8228. this.ellipsoid = this.options.ellipsoid;
  8229. this.lodMetricType = json.lodMetricType;
  8230. this.lodMetricValue = json.lodMetricValue;
  8231. this.refine = json.root.refine;
  8232. this.loadOptions = this.options.loadOptions || {};
  8233. this.root = null;
  8234. this.roots = {};
  8235. this.cartographicCenter = null;
  8236. this.cartesianCenter = null;
  8237. this.zoom = 1;
  8238. this.boundingVolume = null;
  8239. this.traverseCounter = 0;
  8240. this.geometricError = 0;
  8241. this._traverser = this._initializeTraverser();
  8242. this._cache = new TilesetCache();
  8243. this._requestScheduler = new RequestScheduler({
  8244. throttleRequests: this.options.throttleRequests,
  8245. maxRequests: this.options.maxRequests
  8246. });
  8247. this._frameNumber = 0;
  8248. this._pendingCount = 0;
  8249. this._tiles = {};
  8250. this.selectedTiles = [];
  8251. this._emptyTiles = [];
  8252. this._requestedTiles = [];
  8253. this.frameStateData = {};
  8254. this.lastUpdatedVieports = null;
  8255. this._queryParams = {};
  8256. this._queryParamsString = '';
  8257. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8258. this.gpuMemoryUsageInBytes = 0;
  8259. this.stats = new Stats({
  8260. id: this.url
  8261. });
  8262. this._initializeStats();
  8263. this._extensionsUsed = undefined;
  8264. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8265. this.extras = null;
  8266. this.asset = {};
  8267. this.credits = {};
  8268. this.description = this.options.description || '';
  8269. this._initializeTileSet(json);
  8270. }
  8271. destroy() {
  8272. this._destroy();
  8273. }
  8274. isLoaded() {
  8275. return this._pendingCount === 0 && this._frameNumber !== 0;
  8276. }
  8277. get tiles() {
  8278. return Object.values(this._tiles);
  8279. }
  8280. get frameNumber() {
  8281. return this._frameNumber;
  8282. }
  8283. get queryParams() {
  8284. if (!this._queryParamsString) {
  8285. this._queryParamsString = getQueryParamString(this._queryParams);
  8286. }
  8287. return this._queryParamsString;
  8288. }
  8289. setProps(props) {
  8290. this.options = { ...this.options,
  8291. ...props
  8292. };
  8293. }
  8294. setOptions(options) {
  8295. this.options = { ...this.options,
  8296. ...options
  8297. };
  8298. }
  8299. getTileUrl(tilePath) {
  8300. const isDataUrl = tilePath.startsWith('data:');
  8301. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8302. if (isDataUrl) {
  8303. return tilePath;
  8304. }
  8305. return "".concat(tilePath).concat(this.queryParams);
  8306. }
  8307. hasExtension(extensionName) {
  8308. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8309. }
  8310. update(viewports) {
  8311. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8312. return;
  8313. }
  8314. if (this.traverseCounter > 0) {
  8315. return;
  8316. }
  8317. if (!viewports && this.lastUpdatedVieports) {
  8318. viewports = this.lastUpdatedVieports;
  8319. } else {
  8320. this.lastUpdatedVieports = viewports;
  8321. }
  8322. if (!(viewports instanceof Array)) {
  8323. viewports = [viewports];
  8324. }
  8325. this._cache.reset();
  8326. this._frameNumber++;
  8327. this.traverseCounter = viewports.length;
  8328. const viewportsToTraverse = [];
  8329. for (const viewport of viewports) {
  8330. const id = viewport.id;
  8331. if (this._needTraverse(id)) {
  8332. viewportsToTraverse.push(id);
  8333. } else {
  8334. this.traverseCounter--;
  8335. }
  8336. }
  8337. for (const viewport of viewports) {
  8338. const id = viewport.id;
  8339. if (!this.roots[id]) {
  8340. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8341. }
  8342. if (!viewportsToTraverse.includes(id)) {
  8343. continue;
  8344. }
  8345. const frameState = getFrameState(viewport, this._frameNumber);
  8346. this._traverser.traverse(this.roots[id], frameState, this.options);
  8347. }
  8348. }
  8349. _needTraverse(viewportId) {
  8350. let traverserId = viewportId;
  8351. if (this.options.viewportTraversersMap) {
  8352. traverserId = this.options.viewportTraversersMap[viewportId];
  8353. }
  8354. if (traverserId !== viewportId) {
  8355. return false;
  8356. }
  8357. return true;
  8358. }
  8359. _onTraversalEnd(frameState) {
  8360. const id = frameState.viewport.id;
  8361. if (!this.frameStateData[id]) {
  8362. this.frameStateData[id] = {
  8363. selectedTiles: [],
  8364. _requestedTiles: [],
  8365. _emptyTiles: []
  8366. };
  8367. }
  8368. const currentFrameStateData = this.frameStateData[id];
  8369. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8370. currentFrameStateData.selectedTiles = selectedTiles;
  8371. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8372. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8373. this.traverseCounter--;
  8374. if (this.traverseCounter > 0) {
  8375. return;
  8376. }
  8377. this._updateTiles();
  8378. }
  8379. _updateTiles() {
  8380. this.selectedTiles = [];
  8381. this._requestedTiles = [];
  8382. this._emptyTiles = [];
  8383. for (const frameStateKey in this.frameStateData) {
  8384. const frameStateDataValue = this.frameStateData[frameStateKey];
  8385. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8386. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8387. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8388. }
  8389. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8390. for (const tile of this.selectedTiles) {
  8391. this._tiles[tile.id] = tile;
  8392. }
  8393. this._loadTiles();
  8394. this._unloadTiles();
  8395. this._updateStats();
  8396. }
  8397. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8398. if (oldSelectedTiles.length !== selectedTiles.length) {
  8399. return true;
  8400. }
  8401. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8402. const set2 = new Set(selectedTiles.map(t => t.id));
  8403. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8404. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8405. return changed;
  8406. }
  8407. _loadTiles() {
  8408. for (const tile of this._requestedTiles) {
  8409. if (tile.contentUnloaded) {
  8410. this._loadTile(tile);
  8411. }
  8412. }
  8413. }
  8414. _unloadTiles() {
  8415. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8416. }
  8417. _updateStats() {
  8418. let tilesRenderable = 0;
  8419. let pointsRenderable = 0;
  8420. for (const tile of this.selectedTiles) {
  8421. if (tile.contentAvailable && tile.content) {
  8422. tilesRenderable++;
  8423. if (tile.content.pointCount) {
  8424. pointsRenderable += tile.content.pointCount;
  8425. }
  8426. }
  8427. }
  8428. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8429. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8430. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8431. }
  8432. _initializeTileSet(tilesetJson) {
  8433. this.root = this._initializeTileHeaders(tilesetJson, null);
  8434. if (this.type === TILESET_TYPE.TILES3D) {
  8435. this._initializeCesiumTileset(tilesetJson);
  8436. }
  8437. if (this.type === TILESET_TYPE.I3S) {
  8438. this._initializeI3STileset();
  8439. }
  8440. this._calculateViewProps();
  8441. }
  8442. _calculateViewProps() {
  8443. const root = this.root;
  8444. assert$7(root);
  8445. const {
  8446. center
  8447. } = root.boundingVolume;
  8448. if (!center) {
  8449. console.warn('center was not pre-calculated for the root tile');
  8450. this.cartographicCenter = new Vector3();
  8451. this.zoom = 1;
  8452. return;
  8453. }
  8454. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8455. this.cartesianCenter = center;
  8456. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8457. }
  8458. _initializeStats() {
  8459. this.stats.get(TILES_TOTAL);
  8460. this.stats.get(TILES_LOADING);
  8461. this.stats.get(TILES_IN_MEMORY);
  8462. this.stats.get(TILES_IN_VIEW);
  8463. this.stats.get(TILES_RENDERABLE);
  8464. this.stats.get(TILES_LOADED);
  8465. this.stats.get(TILES_UNLOADED);
  8466. this.stats.get(TILES_LOAD_FAILED);
  8467. this.stats.get(POINTS_COUNT, 'memory');
  8468. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8469. }
  8470. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8471. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8472. if (parentTileHeader) {
  8473. parentTileHeader.children.push(rootTile);
  8474. rootTile.depth = parentTileHeader.depth + 1;
  8475. }
  8476. if (this.type === TILESET_TYPE.TILES3D) {
  8477. const stack = [];
  8478. stack.push(rootTile);
  8479. while (stack.length > 0) {
  8480. const tile = stack.pop();
  8481. this.stats.get(TILES_TOTAL).incrementCount();
  8482. const children = tile.header.children || [];
  8483. // !zeg改
  8484. if(tile.depth < this.options.maxDepth){
  8485. for (const childHeader of children) {
  8486. const childTile = new TileHeader(this, childHeader, tile);
  8487. tile.children.push(childTile);
  8488. childTile.depth = tile.depth + 1;
  8489. stack.push(childTile);
  8490. }
  8491. }
  8492. window.maxDepth = Math.max(window.maxDepth||0,tile.depth)
  8493. }
  8494. }
  8495. return rootTile;
  8496. }
  8497. _initializeTraverser() {
  8498. let TraverserClass;
  8499. const type = this.type;
  8500. switch (type) {
  8501. case TILESET_TYPE.TILES3D:
  8502. TraverserClass = Tileset3DTraverser;
  8503. break;
  8504. case TILESET_TYPE.I3S:
  8505. TraverserClass = I3STilesetTraverser;
  8506. break;
  8507. default:
  8508. TraverserClass = TilesetTraverser;
  8509. }
  8510. return new TraverserClass({
  8511. basePath: this.basePath,
  8512. onTraversalEnd: this._onTraversalEnd.bind(this)
  8513. });
  8514. }
  8515. _destroyTileHeaders(parentTile) {
  8516. this._destroySubtree(parentTile);
  8517. }
  8518. async _loadTile(tile) {
  8519. let loaded;
  8520. try {
  8521. this._onStartTileLoading();
  8522. loaded = await tile.loadContent();
  8523. } catch (error) {
  8524. this._onTileLoadError(tile, error);
  8525. } finally {
  8526. this._onEndTileLoading(tile);//
  8527. this._onTileLoad(tile, loaded);
  8528. }
  8529. }
  8530. _onTileLoadError(tile, error) {
  8531. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8532. const message = error.message || error.toString();
  8533. const url = tile.url;
  8534. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8535. this.options.onTileError(tile, message, url);
  8536. }
  8537. _onTileLoad(tile, loaded) {
  8538. if (!loaded) {
  8539. return;
  8540. }
  8541. if (tile && tile.content) {
  8542. calculateTransformProps(tile, tile.content);
  8543. }
  8544. this._addTileToCache(tile);
  8545. this.options.onTileLoad(tile);
  8546. }
  8547. _onStartTileLoading() {
  8548. this._pendingCount++;
  8549. this.stats.get(TILES_LOADING).incrementCount();
  8550. }
  8551. _onEndTileLoading(tile) {
  8552. this._pendingCount--;
  8553. this.stats.get(TILES_LOADING).decrementCount();
  8554. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8555. }
  8556. _addTileToCache(tile) {
  8557. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8558. }
  8559. _updateCacheStats(tile) {
  8560. this.stats.get(TILES_LOADED).incrementCount();
  8561. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8562. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8563. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8564. }
  8565. _unloadTile(tile) {
  8566. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8567. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8568. this.stats.get(TILES_UNLOADED).incrementCount();
  8569. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8570. this.options.onTileUnload(tile);
  8571. tile.unloadContent();
  8572. }
  8573. _destroy() {
  8574. const stack = [];
  8575. if (this.root) {
  8576. stack.push(this.root);
  8577. }
  8578. while (stack.length > 0) {
  8579. const tile = stack.pop();
  8580. for (const child of tile.children) {
  8581. stack.push(child);
  8582. }
  8583. this._destroyTile(tile);
  8584. }
  8585. this.root = null;
  8586. }
  8587. _destroySubtree(tile) {
  8588. const root = tile;
  8589. const stack = [];
  8590. stack.push(root);
  8591. while (stack.length > 0) {
  8592. tile = stack.pop();
  8593. for (const child of tile.children) {
  8594. stack.push(child);
  8595. }
  8596. if (tile !== root) {
  8597. this._destroyTile(tile);
  8598. }
  8599. }
  8600. root.children = [];
  8601. }
  8602. _destroyTile(tile) {
  8603. this._cache.unloadTile(this, tile);
  8604. this._unloadTile(tile);
  8605. tile.destroy();
  8606. }
  8607. _initializeCesiumTileset(tilesetJson) {
  8608. this.asset = tilesetJson.asset;
  8609. if (!this.asset) {
  8610. throw new Error('Tileset must have an asset property.');
  8611. }
  8612. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8613. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8614. }
  8615. if ('tilesetVersion' in this.asset) {
  8616. this._queryParams.v = this.asset.tilesetVersion;
  8617. }
  8618. this.credits = {
  8619. attributions: this.options.attributions || []
  8620. };
  8621. this.description = this.options.description || '';
  8622. this.properties = tilesetJson.properties;
  8623. this.geometricError = tilesetJson.geometricError;
  8624. this._extensionsUsed = tilesetJson.extensionsUsed;
  8625. this.extras = tilesetJson.extras;
  8626. }
  8627. _initializeI3STileset() {
  8628. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8629. this._queryParams.token = this.loadOptions.i3s.token;
  8630. }
  8631. }
  8632. }
  8633. function getQueryParamString(queryParams) {
  8634. const queryParamStrings = [];
  8635. for (const key of Object.keys(queryParams)) {
  8636. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8637. }
  8638. switch (queryParamStrings.length) {
  8639. case 0:
  8640. return '';
  8641. case 1:
  8642. return "?".concat(queryParamStrings[0]);
  8643. default:
  8644. return "?".concat(queryParamStrings.join('&'));
  8645. }
  8646. }
  8647. const VERSION$5 = "3.1.4" ;
  8648. const TILE3D_TYPE = {
  8649. COMPOSITE: 'cmpt',
  8650. POINT_CLOUD: 'pnts',
  8651. BATCHED_3D_MODEL: 'b3dm',
  8652. INSTANCED_3D_MODEL: 'i3dm',
  8653. GEOMETRY: 'geom',
  8654. VECTOR: 'vect',
  8655. GLTF: 'glTF'
  8656. };
  8657. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8658. assert$7(arrayBuffer instanceof ArrayBuffer);
  8659. const textDecoder = new TextDecoder('utf8');
  8660. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8661. const string = textDecoder.decode(typedArray);
  8662. return string;
  8663. }
  8664. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8665. const dataView = new DataView(arrayBuffer);
  8666. 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)));
  8667. }
  8668. const VERSION$4 = "3.1.4" ;
  8669. const DEFAULT_DRACO_OPTIONS = {
  8670. draco: {
  8671. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8672. libraryPath: 'libs/',
  8673. extraAttributes: {},
  8674. attributeNameEntry: undefined
  8675. }
  8676. };
  8677. const DracoLoader$1 = {
  8678. name: 'Draco',
  8679. id: 'draco',
  8680. module: 'draco',
  8681. shapes: ['mesh'],
  8682. version: VERSION$4,
  8683. worker: true,
  8684. extensions: ['drc'],
  8685. mimeTypes: ['application/octet-stream'],
  8686. binary: true,
  8687. tests: ['DRACO'],
  8688. options: DEFAULT_DRACO_OPTIONS
  8689. };
  8690. function getMeshBoundingBox(attributes) {
  8691. let minX = Infinity;
  8692. let minY = Infinity;
  8693. let minZ = Infinity;
  8694. let maxX = -Infinity;
  8695. let maxY = -Infinity;
  8696. let maxZ = -Infinity;
  8697. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8698. const len = positions && positions.length;
  8699. for (let i = 0; i < len; i += 3) {
  8700. const x = positions[i];
  8701. const y = positions[i + 1];
  8702. const z = positions[i + 2];
  8703. minX = x < minX ? x : minX;
  8704. minY = y < minY ? y : minY;
  8705. minZ = z < minZ ? z : minZ;
  8706. maxX = x > maxX ? x : maxX;
  8707. maxY = y > maxY ? y : maxY;
  8708. maxZ = z > maxZ ? z : maxZ;
  8709. }
  8710. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8711. }
  8712. function assert$3(condition, message) {
  8713. if (!condition) {
  8714. throw new Error(message || 'loader assertion failed.');
  8715. }
  8716. }
  8717. class Schema {
  8718. constructor(fields, metadata) {
  8719. _defineProperty(this, "fields", void 0);
  8720. _defineProperty(this, "metadata", void 0);
  8721. assert$3(Array.isArray(fields));
  8722. checkNames(fields);
  8723. this.fields = fields;
  8724. this.metadata = metadata || new Map();
  8725. }
  8726. compareTo(other) {
  8727. if (this.metadata !== other.metadata) {
  8728. return false;
  8729. }
  8730. if (this.fields.length !== other.fields.length) {
  8731. return false;
  8732. }
  8733. for (let i = 0; i < this.fields.length; ++i) {
  8734. if (!this.fields[i].compareTo(other.fields[i])) {
  8735. return false;
  8736. }
  8737. }
  8738. return true;
  8739. }
  8740. select(...columnNames) {
  8741. const nameMap = Object.create(null);
  8742. for (const name of columnNames) {
  8743. nameMap[name] = true;
  8744. }
  8745. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8746. return new Schema(selectedFields, this.metadata);
  8747. }
  8748. selectAt(...columnIndices) {
  8749. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8750. return new Schema(selectedFields, this.metadata);
  8751. }
  8752. assign(schemaOrFields) {
  8753. let fields;
  8754. let metadata = this.metadata;
  8755. if (schemaOrFields instanceof Schema) {
  8756. const otherSchema = schemaOrFields;
  8757. fields = otherSchema.fields;
  8758. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8759. } else {
  8760. fields = schemaOrFields;
  8761. }
  8762. const fieldMap = Object.create(null);
  8763. for (const field of this.fields) {
  8764. fieldMap[field.name] = field;
  8765. }
  8766. for (const field of fields) {
  8767. fieldMap[field.name] = field;
  8768. }
  8769. const mergedFields = Object.values(fieldMap);
  8770. return new Schema(mergedFields, metadata);
  8771. }
  8772. }
  8773. function checkNames(fields) {
  8774. const usedNames = {};
  8775. for (const field of fields) {
  8776. if (usedNames[field.name]) {
  8777. console.warn('Schema: duplicated field name', field.name, field);
  8778. }
  8779. usedNames[field.name] = true;
  8780. }
  8781. }
  8782. function mergeMaps(m1, m2) {
  8783. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8784. }
  8785. class Field {
  8786. constructor(name, type, nullable = false, metadata = new Map()) {
  8787. _defineProperty(this, "name", void 0);
  8788. _defineProperty(this, "type", void 0);
  8789. _defineProperty(this, "nullable", void 0);
  8790. _defineProperty(this, "metadata", void 0);
  8791. this.name = name;
  8792. this.type = type;
  8793. this.nullable = nullable;
  8794. this.metadata = metadata;
  8795. }
  8796. get typeId() {
  8797. return this.type && this.type.typeId;
  8798. }
  8799. clone() {
  8800. return new Field(this.name, this.type, this.nullable, this.metadata);
  8801. }
  8802. compareTo(other) {
  8803. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8804. }
  8805. toString() {
  8806. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8807. }
  8808. }
  8809. let Type;
  8810. (function (Type) {
  8811. Type[Type["NONE"] = 0] = "NONE";
  8812. Type[Type["Null"] = 1] = "Null";
  8813. Type[Type["Int"] = 2] = "Int";
  8814. Type[Type["Float"] = 3] = "Float";
  8815. Type[Type["Binary"] = 4] = "Binary";
  8816. Type[Type["Utf8"] = 5] = "Utf8";
  8817. Type[Type["Bool"] = 6] = "Bool";
  8818. Type[Type["Decimal"] = 7] = "Decimal";
  8819. Type[Type["Date"] = 8] = "Date";
  8820. Type[Type["Time"] = 9] = "Time";
  8821. Type[Type["Timestamp"] = 10] = "Timestamp";
  8822. Type[Type["Interval"] = 11] = "Interval";
  8823. Type[Type["List"] = 12] = "List";
  8824. Type[Type["Struct"] = 13] = "Struct";
  8825. Type[Type["Union"] = 14] = "Union";
  8826. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8827. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8828. Type[Type["Map"] = 17] = "Map";
  8829. Type[Type["Dictionary"] = -1] = "Dictionary";
  8830. Type[Type["Int8"] = -2] = "Int8";
  8831. Type[Type["Int16"] = -3] = "Int16";
  8832. Type[Type["Int32"] = -4] = "Int32";
  8833. Type[Type["Int64"] = -5] = "Int64";
  8834. Type[Type["Uint8"] = -6] = "Uint8";
  8835. Type[Type["Uint16"] = -7] = "Uint16";
  8836. Type[Type["Uint32"] = -8] = "Uint32";
  8837. Type[Type["Uint64"] = -9] = "Uint64";
  8838. Type[Type["Float16"] = -10] = "Float16";
  8839. Type[Type["Float32"] = -11] = "Float32";
  8840. Type[Type["Float64"] = -12] = "Float64";
  8841. Type[Type["DateDay"] = -13] = "DateDay";
  8842. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8843. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8844. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8845. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8846. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8847. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8848. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8849. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8850. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8851. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8852. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8853. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  8854. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  8855. })(Type || (Type = {}));
  8856. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  8857. class DataType {
  8858. static isNull(x) {
  8859. return x && x.typeId === Type.Null;
  8860. }
  8861. static isInt(x) {
  8862. return x && x.typeId === Type.Int;
  8863. }
  8864. static isFloat(x) {
  8865. return x && x.typeId === Type.Float;
  8866. }
  8867. static isBinary(x) {
  8868. return x && x.typeId === Type.Binary;
  8869. }
  8870. static isUtf8(x) {
  8871. return x && x.typeId === Type.Utf8;
  8872. }
  8873. static isBool(x) {
  8874. return x && x.typeId === Type.Bool;
  8875. }
  8876. static isDecimal(x) {
  8877. return x && x.typeId === Type.Decimal;
  8878. }
  8879. static isDate(x) {
  8880. return x && x.typeId === Type.Date;
  8881. }
  8882. static isTime(x) {
  8883. return x && x.typeId === Type.Time;
  8884. }
  8885. static isTimestamp(x) {
  8886. return x && x.typeId === Type.Timestamp;
  8887. }
  8888. static isInterval(x) {
  8889. return x && x.typeId === Type.Interval;
  8890. }
  8891. static isList(x) {
  8892. return x && x.typeId === Type.List;
  8893. }
  8894. static isStruct(x) {
  8895. return x && x.typeId === Type.Struct;
  8896. }
  8897. static isUnion(x) {
  8898. return x && x.typeId === Type.Union;
  8899. }
  8900. static isFixedSizeBinary(x) {
  8901. return x && x.typeId === Type.FixedSizeBinary;
  8902. }
  8903. static isFixedSizeList(x) {
  8904. return x && x.typeId === Type.FixedSizeList;
  8905. }
  8906. static isMap(x) {
  8907. return x && x.typeId === Type.Map;
  8908. }
  8909. static isDictionary(x) {
  8910. return x && x.typeId === Type.Dictionary;
  8911. }
  8912. get typeId() {
  8913. return Type.NONE;
  8914. }
  8915. compareTo(other) {
  8916. return this === other;
  8917. }
  8918. }
  8919. _Symbol$toStringTag = Symbol.toStringTag;
  8920. class Int extends DataType {
  8921. constructor(isSigned, bitWidth) {
  8922. super();
  8923. _defineProperty(this, "isSigned", void 0);
  8924. _defineProperty(this, "bitWidth", void 0);
  8925. this.isSigned = isSigned;
  8926. this.bitWidth = bitWidth;
  8927. }
  8928. get typeId() {
  8929. return Type.Int;
  8930. }
  8931. get [_Symbol$toStringTag]() {
  8932. return 'Int';
  8933. }
  8934. toString() {
  8935. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  8936. }
  8937. }
  8938. class Int8 extends Int {
  8939. constructor() {
  8940. super(true, 8);
  8941. }
  8942. }
  8943. class Int16 extends Int {
  8944. constructor() {
  8945. super(true, 16);
  8946. }
  8947. }
  8948. class Int32 extends Int {
  8949. constructor() {
  8950. super(true, 32);
  8951. }
  8952. }
  8953. class Uint8 extends Int {
  8954. constructor() {
  8955. super(false, 8);
  8956. }
  8957. }
  8958. class Uint16 extends Int {
  8959. constructor() {
  8960. super(false, 16);
  8961. }
  8962. }
  8963. class Uint32 extends Int {
  8964. constructor() {
  8965. super(false, 32);
  8966. }
  8967. }
  8968. const Precision = {
  8969. HALF: 16,
  8970. SINGLE: 32,
  8971. DOUBLE: 64
  8972. };
  8973. _Symbol$toStringTag2 = Symbol.toStringTag;
  8974. class Float extends DataType {
  8975. constructor(precision) {
  8976. super();
  8977. _defineProperty(this, "precision", void 0);
  8978. this.precision = precision;
  8979. }
  8980. get typeId() {
  8981. return Type.Float;
  8982. }
  8983. get [_Symbol$toStringTag2]() {
  8984. return 'Float';
  8985. }
  8986. toString() {
  8987. return "Float".concat(this.precision);
  8988. }
  8989. }
  8990. class Float32 extends Float {
  8991. constructor() {
  8992. super(Precision.SINGLE);
  8993. }
  8994. }
  8995. class Float64 extends Float {
  8996. constructor() {
  8997. super(Precision.DOUBLE);
  8998. }
  8999. }
  9000. _Symbol$toStringTag7 = Symbol.toStringTag;
  9001. class FixedSizeList extends DataType {
  9002. constructor(listSize, child) {
  9003. super();
  9004. _defineProperty(this, "listSize", void 0);
  9005. _defineProperty(this, "children", void 0);
  9006. this.listSize = listSize;
  9007. this.children = [child];
  9008. }
  9009. get typeId() {
  9010. return Type.FixedSizeList;
  9011. }
  9012. get valueType() {
  9013. return this.children[0].type;
  9014. }
  9015. get valueField() {
  9016. return this.children[0];
  9017. }
  9018. get [_Symbol$toStringTag7]() {
  9019. return 'FixedSizeList';
  9020. }
  9021. toString() {
  9022. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9023. }
  9024. }
  9025. function getArrowTypeFromTypedArray(array) {
  9026. switch (array.constructor) {
  9027. case Int8Array:
  9028. return new Int8();
  9029. case Uint8Array:
  9030. return new Uint8();
  9031. case Int16Array:
  9032. return new Int16();
  9033. case Uint16Array:
  9034. return new Uint16();
  9035. case Int32Array:
  9036. return new Int32();
  9037. case Uint32Array:
  9038. return new Uint32();
  9039. case Float32Array:
  9040. return new Float32();
  9041. case Float64Array:
  9042. return new Float64();
  9043. default:
  9044. throw new Error('array type not supported');
  9045. }
  9046. }
  9047. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9048. const type = getArrowTypeFromTypedArray(attribute.value);
  9049. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9050. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9051. return field;
  9052. }
  9053. function makeMeshAttributeMetadata(attribute) {
  9054. const result = new Map();
  9055. if ('byteOffset' in attribute) {
  9056. result.set('byteOffset', attribute.byteOffset.toString(10));
  9057. }
  9058. if ('byteStride' in attribute) {
  9059. result.set('byteStride', attribute.byteStride.toString(10));
  9060. }
  9061. if ('normalized' in attribute) {
  9062. result.set('normalized', attribute.normalized.toString());
  9063. }
  9064. return result;
  9065. }
  9066. function getDracoSchema(attributes, loaderData, indices) {
  9067. const metadataMap = makeMetadata(loaderData.metadata);
  9068. const fields = [];
  9069. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9070. for (const attributeName in attributes) {
  9071. const attribute = attributes[attributeName];
  9072. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9073. fields.push(field);
  9074. }
  9075. if (indices) {
  9076. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9077. fields.push(indicesField);
  9078. }
  9079. return new Schema(fields, metadataMap);
  9080. }
  9081. function transformAttributesLoaderData(loaderData) {
  9082. const result = {};
  9083. for (const key in loaderData) {
  9084. const dracoAttribute = loaderData[key];
  9085. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9086. }
  9087. return result;
  9088. }
  9089. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9090. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9091. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9092. return field;
  9093. }
  9094. function makeMetadata(metadata) {
  9095. const metadataMap = new Map();
  9096. for (const key in metadata) {
  9097. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9098. }
  9099. return metadataMap;
  9100. }
  9101. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9102. POSITION: 'POSITION',
  9103. NORMAL: 'NORMAL',
  9104. COLOR: 'COLOR_0',
  9105. TEX_COORD: 'TEXCOORD_0'
  9106. };
  9107. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9108. 1: Int8Array,
  9109. 2: Uint8Array,
  9110. 3: Int16Array,
  9111. 4: Uint16Array,
  9112. 5: Int32Array,
  9113. 6: Uint32Array,
  9114. 9: Float32Array
  9115. };
  9116. const INDEX_ITEM_SIZE = 4;
  9117. class DracoParser {
  9118. constructor(draco) {
  9119. _defineProperty(this, "draco", void 0);
  9120. _defineProperty(this, "decoder", void 0);
  9121. _defineProperty(this, "metadataQuerier", void 0);
  9122. this.draco = draco;
  9123. this.decoder = new this.draco.Decoder();
  9124. this.metadataQuerier = new this.draco.MetadataQuerier();
  9125. }
  9126. destroy() {
  9127. this.draco.destroy(this.decoder);
  9128. this.draco.destroy(this.metadataQuerier);
  9129. }
  9130. parseSync(arrayBuffer, options = {}) {
  9131. const buffer = new this.draco.DecoderBuffer();
  9132. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9133. this._disableAttributeTransforms(options);
  9134. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9135. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9136. try {
  9137. let dracoStatus;
  9138. switch (geometry_type) {
  9139. case this.draco.TRIANGULAR_MESH:
  9140. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9141. break;
  9142. case this.draco.POINT_CLOUD:
  9143. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9144. break;
  9145. default:
  9146. throw new Error('DRACO: Unknown geometry type.');
  9147. }
  9148. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9149. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9150. throw new Error(message);
  9151. }
  9152. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9153. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9154. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9155. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9156. const data = {
  9157. loader: 'draco',
  9158. loaderData,
  9159. header: {
  9160. vertexCount: dracoGeometry.num_points(),
  9161. boundingBox
  9162. },
  9163. ...geometry,
  9164. schema
  9165. };
  9166. return data;
  9167. } finally {
  9168. this.draco.destroy(buffer);
  9169. if (dracoGeometry) {
  9170. this.draco.destroy(dracoGeometry);
  9171. }
  9172. }
  9173. }
  9174. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9175. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9176. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9177. return {
  9178. geometry_type,
  9179. num_attributes: dracoGeometry.num_attributes(),
  9180. num_points: dracoGeometry.num_points(),
  9181. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9182. metadata,
  9183. attributes
  9184. };
  9185. }
  9186. _getDracoAttributes(dracoGeometry, options) {
  9187. const dracoAttributes = {};
  9188. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9189. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9190. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9191. dracoAttributes[dracoAttribute.unique_id()] = {
  9192. unique_id: dracoAttribute.unique_id(),
  9193. attribute_type: dracoAttribute.attribute_type(),
  9194. data_type: dracoAttribute.data_type(),
  9195. num_components: dracoAttribute.num_components(),
  9196. byte_offset: dracoAttribute.byte_offset(),
  9197. byte_stride: dracoAttribute.byte_stride(),
  9198. normalized: dracoAttribute.normalized(),
  9199. attribute_index: attributeId,
  9200. metadata
  9201. };
  9202. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9203. if (quantization) {
  9204. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9205. }
  9206. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9207. if (octahedron) {
  9208. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9209. }
  9210. }
  9211. return dracoAttributes;
  9212. }
  9213. _getMeshData(dracoGeometry, loaderData, options) {
  9214. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9215. const positionAttribute = attributes.POSITION;
  9216. if (!positionAttribute) {
  9217. throw new Error('DRACO: No position attribute found.');
  9218. }
  9219. if (dracoGeometry instanceof this.draco.Mesh) {
  9220. switch (options.topology) {
  9221. case 'triangle-strip':
  9222. return {
  9223. topology: 'triangle-strip',
  9224. mode: 4,
  9225. attributes,
  9226. indices: {
  9227. value: this._getTriangleStripIndices(dracoGeometry),
  9228. size: 1
  9229. }
  9230. };
  9231. case 'triangle-list':
  9232. default:
  9233. return {
  9234. topology: 'triangle-list',
  9235. mode: 5,
  9236. attributes,
  9237. indices: {
  9238. value: this._getTriangleListIndices(dracoGeometry),
  9239. size: 1
  9240. }
  9241. };
  9242. }
  9243. }
  9244. return {
  9245. topology: 'point-list',
  9246. mode: 0,
  9247. attributes
  9248. };
  9249. }
  9250. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9251. const attributes = {};
  9252. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9253. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9254. loaderAttribute.name = attributeName;
  9255. const {
  9256. value,
  9257. size
  9258. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9259. attributes[attributeName] = {
  9260. value,
  9261. size,
  9262. byteOffset: loaderAttribute.byte_offset,
  9263. byteStride: loaderAttribute.byte_stride,
  9264. normalized: loaderAttribute.normalized
  9265. };
  9266. }
  9267. return attributes;
  9268. }
  9269. _getTriangleListIndices(dracoGeometry) {
  9270. const numFaces = dracoGeometry.num_faces();
  9271. const numIndices = numFaces * 3;
  9272. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9273. const ptr = this.draco._malloc(byteLength);
  9274. try {
  9275. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9276. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9277. } finally {
  9278. this.draco._free(ptr);
  9279. }
  9280. }
  9281. _getTriangleStripIndices(dracoGeometry) {
  9282. const dracoArray = new this.draco.DracoInt32Array();
  9283. try {
  9284. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9285. return getUint32Array(dracoArray);
  9286. } finally {
  9287. this.draco.destroy(dracoArray);
  9288. }
  9289. }
  9290. _getAttributeValues(dracoGeometry, attribute) {
  9291. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9292. const numComponents = attribute.num_components;
  9293. const numPoints = dracoGeometry.num_points();
  9294. const numValues = numPoints * numComponents;
  9295. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9296. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9297. let value;
  9298. const ptr = this.draco._malloc(byteLength);
  9299. try {
  9300. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9301. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9302. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9303. } finally {
  9304. this.draco._free(ptr);
  9305. }
  9306. return {
  9307. value,
  9308. size: numComponents
  9309. };
  9310. }
  9311. _deduceAttributeName(attribute, options) {
  9312. const uniqueId = attribute.unique_id;
  9313. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9314. if (attributeUniqueId === uniqueId) {
  9315. return attributeName;
  9316. }
  9317. }
  9318. const thisAttributeType = attribute.attribute_type;
  9319. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9320. const attributeType = this.draco[dracoAttributeConstant];
  9321. if (attributeType === thisAttributeType) {
  9322. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9323. }
  9324. }
  9325. const entryName = options.attributeNameEntry || 'name';
  9326. if (attribute.metadata[entryName]) {
  9327. return attribute.metadata[entryName].string;
  9328. }
  9329. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9330. }
  9331. _getTopLevelMetadata(dracoGeometry) {
  9332. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9333. return this._getDracoMetadata(dracoMetadata);
  9334. }
  9335. _getAttributeMetadata(dracoGeometry, attributeId) {
  9336. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9337. return this._getDracoMetadata(dracoMetadata);
  9338. }
  9339. _getDracoMetadata(dracoMetadata) {
  9340. if (!dracoMetadata || !dracoMetadata.ptr) {
  9341. return {};
  9342. }
  9343. const result = {};
  9344. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9345. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9346. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9347. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9348. }
  9349. return result;
  9350. }
  9351. _getDracoMetadataField(dracoMetadata, entryName) {
  9352. const dracoArray = new this.draco.DracoInt32Array();
  9353. try {
  9354. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9355. const intArray = getInt32Array(dracoArray);
  9356. return {
  9357. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9358. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9359. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9360. intArray
  9361. };
  9362. } finally {
  9363. this.draco.destroy(dracoArray);
  9364. }
  9365. }
  9366. _disableAttributeTransforms(options) {
  9367. const {
  9368. quantizedAttributes = [],
  9369. octahedronAttributes = []
  9370. } = options;
  9371. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9372. for (const dracoAttributeName of skipAttributes) {
  9373. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9374. }
  9375. }
  9376. _getQuantizationTransform(dracoAttribute, options) {
  9377. const {
  9378. quantizedAttributes = []
  9379. } = options;
  9380. const attribute_type = dracoAttribute.attribute_type();
  9381. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9382. if (skip) {
  9383. const transform = new this.draco.AttributeQuantizationTransform();
  9384. try {
  9385. if (transform.InitFromAttribute(dracoAttribute)) {
  9386. return {
  9387. quantization_bits: transform.quantization_bits(),
  9388. range: transform.range(),
  9389. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9390. };
  9391. }
  9392. } finally {
  9393. this.draco.destroy(transform);
  9394. }
  9395. }
  9396. return null;
  9397. }
  9398. _getOctahedronTransform(dracoAttribute, options) {
  9399. const {
  9400. octahedronAttributes = []
  9401. } = options;
  9402. const attribute_type = dracoAttribute.attribute_type();
  9403. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9404. if (octahedron) {
  9405. const transform = new this.draco.AttributeQuantizationTransform();
  9406. try {
  9407. if (transform.InitFromAttribute(dracoAttribute)) {
  9408. return {
  9409. quantization_bits: transform.quantization_bits()
  9410. };
  9411. }
  9412. } finally {
  9413. this.draco.destroy(transform);
  9414. }
  9415. }
  9416. return null;
  9417. }
  9418. }
  9419. function getDracoDataType(draco, attributeType) {
  9420. switch (attributeType) {
  9421. case Float32Array:
  9422. return draco.DT_FLOAT32;
  9423. case Int8Array:
  9424. return draco.DT_INT8;
  9425. case Int16Array:
  9426. return draco.DT_INT16;
  9427. case Int32Array:
  9428. return draco.DT_INT32;
  9429. case Uint8Array:
  9430. return draco.DT_UINT8;
  9431. case Uint16Array:
  9432. return draco.DT_UINT16;
  9433. case Uint32Array:
  9434. return draco.DT_UINT32;
  9435. default:
  9436. return draco.DT_INVALID;
  9437. }
  9438. }
  9439. function getInt32Array(dracoArray) {
  9440. const numValues = dracoArray.size();
  9441. const intArray = new Int32Array(numValues);
  9442. for (let i = 0; i < numValues; i++) {
  9443. intArray[i] = dracoArray.GetValue(i);
  9444. }
  9445. return intArray;
  9446. }
  9447. function getUint32Array(dracoArray) {
  9448. const numValues = dracoArray.size();
  9449. const intArray = new Int32Array(numValues);
  9450. for (let i = 0; i < numValues; i++) {
  9451. intArray[i] = dracoArray.GetValue(i);
  9452. }
  9453. return intArray;
  9454. }
  9455. const DRACO_VERSION = '1.4.1';
  9456. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9457. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9458. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9459. let loadDecoderPromise;
  9460. async function loadDracoDecoderModule(options) {
  9461. const modules = options.modules || {};
  9462. if (modules.draco3d) {
  9463. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9464. return {
  9465. draco
  9466. };
  9467. });
  9468. } else {
  9469. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9470. }
  9471. return await loadDecoderPromise;
  9472. }
  9473. async function loadDracoDecoder(options) {
  9474. let DracoDecoderModule;
  9475. let wasmBinary;
  9476. switch (options.draco && options.draco.decoderType) {
  9477. case 'js':
  9478. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9479. break;
  9480. case 'wasm':
  9481. default:
  9482. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9483. }
  9484. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9485. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9486. }
  9487. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9488. const options = {};
  9489. if (wasmBinary) {
  9490. options.wasmBinary = wasmBinary;
  9491. }
  9492. return new Promise(resolve => {
  9493. DracoDecoderModule({ ...options,
  9494. onModuleLoaded: draco => resolve({
  9495. draco
  9496. })
  9497. });
  9498. });
  9499. }
  9500. const DracoLoader = { ...DracoLoader$1,
  9501. parse: parse$2
  9502. };
  9503. async function parse$2(arrayBuffer, options) {
  9504. const {
  9505. draco
  9506. } = await loadDracoDecoderModule(options);
  9507. const dracoParser = new DracoParser(draco);
  9508. try {
  9509. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9510. } finally {
  9511. dracoParser.destroy();
  9512. }
  9513. }
  9514. const GL_PRIMITIVE_MODE = {
  9515. POINTS: 0x0000,
  9516. LINES: 0x0001,
  9517. LINE_LOOP: 0x0002,
  9518. LINE_STRIP: 0x0003,
  9519. TRIANGLES: 0x0004,
  9520. TRIANGLE_STRIP: 0x0005,
  9521. TRIANGLE_FAN: 0x0006
  9522. };
  9523. const GL_TYPE = {
  9524. BYTE: 5120,
  9525. UNSIGNED_BYTE: 5121,
  9526. SHORT: 5122,
  9527. UNSIGNED_SHORT: 5123,
  9528. INT: 5124,
  9529. UNSIGNED_INT: 5125,
  9530. FLOAT: 5126,
  9531. DOUBLE: 5130
  9532. };
  9533. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9534. ...GL_TYPE
  9535. };
  9536. const GL_TYPE_TO_ARRAY_TYPE = {
  9537. [GL_TYPE.DOUBLE]: Float64Array,
  9538. [GL_TYPE.FLOAT]: Float32Array,
  9539. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9540. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9541. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9542. [GL_TYPE.BYTE]: Int8Array,
  9543. [GL_TYPE.SHORT]: Int16Array,
  9544. [GL_TYPE.INT]: Int32Array
  9545. };
  9546. const NAME_TO_GL_TYPE = {
  9547. DOUBLE: GL_TYPE.DOUBLE,
  9548. FLOAT: GL_TYPE.FLOAT,
  9549. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9550. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9551. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9552. BYTE: GL_TYPE.BYTE,
  9553. SHORT: GL_TYPE.SHORT,
  9554. INT: GL_TYPE.INT
  9555. };
  9556. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9557. class GLType {
  9558. static fromTypedArray(arrayOrType) {
  9559. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9560. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9561. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9562. if (ArrayType === arrayOrType) {
  9563. return glType;
  9564. }
  9565. }
  9566. throw new Error(ERR_TYPE_CONVERSION);
  9567. }
  9568. static fromName(name) {
  9569. const glType = NAME_TO_GL_TYPE[name];
  9570. if (!glType) {
  9571. throw new Error(ERR_TYPE_CONVERSION);
  9572. }
  9573. return glType;
  9574. }
  9575. static getArrayType(glType) {
  9576. switch (glType) {
  9577. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9578. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9579. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9580. return Uint16Array;
  9581. default:
  9582. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9583. if (!ArrayType) {
  9584. throw new Error(ERR_TYPE_CONVERSION);
  9585. }
  9586. return ArrayType;
  9587. }
  9588. }
  9589. static getByteSize(glType) {
  9590. const ArrayType = GLType.getArrayType(glType);
  9591. return ArrayType.BYTES_PER_ELEMENT;
  9592. }
  9593. static validate(glType) {
  9594. return Boolean(GLType.getArrayType(glType));
  9595. }
  9596. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9597. if (length === undefined) {
  9598. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9599. }
  9600. const ArrayType = GLType.getArrayType(glType);
  9601. return new ArrayType(buffer, byteOffset, length);
  9602. }
  9603. }
  9604. function assert$2(condition, message) {
  9605. if (!condition) {
  9606. throw new Error("math.gl assertion failed. ".concat(message));
  9607. }
  9608. }
  9609. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9610. const r5 = rgb565 >> 11 & 31;
  9611. const g6 = rgb565 >> 5 & 63;
  9612. const b5 = rgb565 & 31;
  9613. target[0] = r5 << 3;
  9614. target[1] = g6 << 2;
  9615. target[2] = b5 << 3;
  9616. return target;
  9617. }
  9618. new Vector2();
  9619. new Vector3();
  9620. new Vector2();
  9621. new Vector2();
  9622. function fromSNorm(value, rangeMaximum = 255) {
  9623. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9624. }
  9625. function signNotZero(value) {
  9626. return value < 0.0 ? -1.0 : 1.0;
  9627. }
  9628. function octDecodeInRange(x, y, rangeMax, result) {
  9629. assert$2(result);
  9630. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9631. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9632. }
  9633. result.x = fromSNorm(x, rangeMax);
  9634. result.y = fromSNorm(y, rangeMax);
  9635. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9636. if (result.z < 0.0) {
  9637. const oldVX = result.x;
  9638. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9639. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9640. }
  9641. return result.normalize();
  9642. }
  9643. function octDecode(x, y, result) {
  9644. return octDecodeInRange(x, y, 255, result);
  9645. }
  9646. class Tile3DFeatureTable {
  9647. constructor(featureTableJson, featureTableBinary) {
  9648. _defineProperty(this, "json", void 0);
  9649. _defineProperty(this, "buffer", void 0);
  9650. _defineProperty(this, "featuresLength", 0);
  9651. _defineProperty(this, "_cachedTypedArrays", {});
  9652. this.json = featureTableJson;
  9653. this.buffer = featureTableBinary;
  9654. }
  9655. getExtension(extensionName) {
  9656. return this.json.extensions && this.json.extensions[extensionName];
  9657. }
  9658. hasProperty(propertyName) {
  9659. return Boolean(this.json[propertyName]);
  9660. }
  9661. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9662. const jsonValue = this.json[propertyName];
  9663. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9664. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9665. }
  9666. return jsonValue;
  9667. }
  9668. getPropertyArray(propertyName, componentType, componentLength) {
  9669. const jsonValue = this.json[propertyName];
  9670. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9671. if ('componentType' in jsonValue) {
  9672. componentType = GLType.fromName(jsonValue.componentType);
  9673. }
  9674. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9675. }
  9676. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9677. }
  9678. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9679. const jsonValue = this.json[propertyName];
  9680. if (!jsonValue) {
  9681. return jsonValue;
  9682. }
  9683. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9684. if (componentLength === 1) {
  9685. return typedArray[featureId];
  9686. }
  9687. for (let i = 0; i < componentLength; ++i) {
  9688. result[i] = typedArray[componentLength * featureId + i];
  9689. }
  9690. return result;
  9691. }
  9692. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9693. const cachedTypedArrays = this._cachedTypedArrays;
  9694. let typedArray = cachedTypedArrays[propertyName];
  9695. if (!typedArray) {
  9696. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9697. cachedTypedArrays[propertyName] = typedArray;
  9698. }
  9699. return typedArray;
  9700. }
  9701. _getTypedArrayFromArray(propertyName, componentType, array) {
  9702. const cachedTypedArrays = this._cachedTypedArrays;
  9703. let typedArray = cachedTypedArrays[propertyName];
  9704. if (!typedArray) {
  9705. typedArray = GLType.createTypedArray(componentType, array);
  9706. cachedTypedArrays[propertyName] = typedArray;
  9707. }
  9708. return typedArray;
  9709. }
  9710. }
  9711. const COMPONENTS_PER_ATTRIBUTE = {
  9712. SCALAR: 1,
  9713. VEC2: 2,
  9714. VEC3: 3,
  9715. VEC4: 4,
  9716. MAT2: 4,
  9717. MAT3: 9,
  9718. MAT4: 16
  9719. };
  9720. const UNPACKER = {
  9721. SCALAR: (values, i) => values[i],
  9722. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9723. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9724. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9725. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9726. 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]],
  9727. 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]]
  9728. };
  9729. const PACKER = {
  9730. SCALAR: (x, values, i) => {
  9731. values[i] = x;
  9732. },
  9733. VEC2: (x, values, i) => {
  9734. values[2 * i + 0] = x[0];
  9735. values[2 * i + 1] = x[1];
  9736. },
  9737. VEC3: (x, values, i) => {
  9738. values[3 * i + 0] = x[0];
  9739. values[3 * i + 1] = x[1];
  9740. values[3 * i + 2] = x[2];
  9741. },
  9742. VEC4: (x, values, i) => {
  9743. values[4 * i + 0] = x[0];
  9744. values[4 * i + 1] = x[1];
  9745. values[4 * i + 2] = x[2];
  9746. values[4 * i + 3] = x[3];
  9747. },
  9748. MAT2: (x, values, i) => {
  9749. values[4 * i + 0] = x[0];
  9750. values[4 * i + 1] = x[1];
  9751. values[4 * i + 2] = x[2];
  9752. values[4 * i + 3] = x[3];
  9753. },
  9754. MAT3: (x, values, i) => {
  9755. values[9 * i + 0] = x[0];
  9756. values[9 * i + 1] = x[1];
  9757. values[9 * i + 2] = x[2];
  9758. values[9 * i + 3] = x[3];
  9759. values[9 * i + 4] = x[4];
  9760. values[9 * i + 5] = x[5];
  9761. values[9 * i + 6] = x[6];
  9762. values[9 * i + 7] = x[7];
  9763. values[9 * i + 8] = x[8];
  9764. values[9 * i + 9] = x[9];
  9765. },
  9766. MAT4: (x, values, i) => {
  9767. values[16 * i + 0] = x[0];
  9768. values[16 * i + 1] = x[1];
  9769. values[16 * i + 2] = x[2];
  9770. values[16 * i + 3] = x[3];
  9771. values[16 * i + 4] = x[4];
  9772. values[16 * i + 5] = x[5];
  9773. values[16 * i + 6] = x[6];
  9774. values[16 * i + 7] = x[7];
  9775. values[16 * i + 8] = x[8];
  9776. values[16 * i + 9] = x[9];
  9777. values[16 * i + 10] = x[10];
  9778. values[16 * i + 11] = x[11];
  9779. values[16 * i + 12] = x[12];
  9780. values[16 * i + 13] = x[13];
  9781. values[16 * i + 14] = x[14];
  9782. values[16 * i + 15] = x[15];
  9783. }
  9784. };
  9785. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9786. const {
  9787. componentType
  9788. } = tile3DAccessor;
  9789. assert$7(tile3DAccessor.componentType);
  9790. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9791. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9792. const unpacker = UNPACKER[tile3DAccessor.type];
  9793. const packer = PACKER[tile3DAccessor.type];
  9794. byteOffset += tile3DAccessor.byteOffset;
  9795. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9796. return {
  9797. values,
  9798. type,
  9799. size,
  9800. unpacker,
  9801. packer
  9802. };
  9803. }
  9804. const defined$1 = x => x !== undefined;
  9805. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9806. if (!jsonHeader) {
  9807. return null;
  9808. }
  9809. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9810. const legacyHierarchy = jsonHeader.HIERARCHY;
  9811. if (legacyHierarchy) {
  9812. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9813. jsonHeader.extensions = jsonHeader.extensions || {};
  9814. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9815. hierarchy = legacyHierarchy;
  9816. }
  9817. if (!hierarchy) {
  9818. return null;
  9819. }
  9820. return initializeHierarchyValues(hierarchy, binaryBody);
  9821. }
  9822. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9823. let i;
  9824. let classId;
  9825. let binaryAccessor;
  9826. const instancesLength = hierarchyJson.instancesLength;
  9827. const classes = hierarchyJson.classes;
  9828. let classIds = hierarchyJson.classIds;
  9829. let parentCounts = hierarchyJson.parentCounts;
  9830. let parentIds = hierarchyJson.parentIds;
  9831. let parentIdsLength = instancesLength;
  9832. if (defined$1(classIds.byteOffset)) {
  9833. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9834. classIds.type = AttributeType.SCALAR;
  9835. binaryAccessor = getBinaryAccessor(classIds);
  9836. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9837. }
  9838. let parentIndexes;
  9839. if (defined$1(parentCounts)) {
  9840. if (defined$1(parentCounts.byteOffset)) {
  9841. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9842. parentCounts.type = AttributeType.SCALAR;
  9843. binaryAccessor = getBinaryAccessor(parentCounts);
  9844. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9845. }
  9846. parentIndexes = new Uint16Array(instancesLength);
  9847. parentIdsLength = 0;
  9848. for (i = 0; i < instancesLength; ++i) {
  9849. parentIndexes[i] = parentIdsLength;
  9850. parentIdsLength += parentCounts[i];
  9851. }
  9852. }
  9853. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  9854. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  9855. parentIds.type = AttributeType.SCALAR;
  9856. binaryAccessor = getBinaryAccessor(parentIds);
  9857. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  9858. }
  9859. const classesLength = classes.length;
  9860. for (i = 0; i < classesLength; ++i) {
  9861. const classInstancesLength = classes[i].length;
  9862. const properties = classes[i].instances;
  9863. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  9864. classes[i].instances = combine(binaryProperties, properties);
  9865. }
  9866. const classCounts = new Array(classesLength).fill(0);
  9867. const classIndexes = new Uint16Array(instancesLength);
  9868. for (i = 0; i < instancesLength; ++i) {
  9869. classId = classIds[i];
  9870. classIndexes[i] = classCounts[classId];
  9871. ++classCounts[classId];
  9872. }
  9873. const hierarchy = {
  9874. classes,
  9875. classIds,
  9876. classIndexes,
  9877. parentCounts,
  9878. parentIndexes,
  9879. parentIds
  9880. };
  9881. validateHierarchy(hierarchy);
  9882. return hierarchy;
  9883. }
  9884. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  9885. if (!hierarchy) {
  9886. return;
  9887. }
  9888. const parentCounts = hierarchy.parentCounts;
  9889. const parentIds = hierarchy.parentIds;
  9890. if (parentIds) {
  9891. return endConditionCallback(hierarchy, instanceIndex);
  9892. }
  9893. if (parentCounts > 0) {
  9894. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  9895. }
  9896. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  9897. }
  9898. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  9899. const classIds = hierarchy.classIds;
  9900. const parentCounts = hierarchy.parentCounts;
  9901. const parentIds = hierarchy.parentIds;
  9902. const parentIndexes = hierarchy.parentIndexes;
  9903. const instancesLength = classIds.length;
  9904. const visited = scratchVisited;
  9905. visited.length = Math.max(visited.length, instancesLength);
  9906. const visitedMarker = ++marker;
  9907. const stack = scratchStack;
  9908. stack.length = 0;
  9909. stack.push(instanceIndex);
  9910. while (stack.length > 0) {
  9911. instanceIndex = stack.pop();
  9912. if (visited[instanceIndex] === visitedMarker) {
  9913. continue;
  9914. }
  9915. visited[instanceIndex] = visitedMarker;
  9916. const result = endConditionCallback(hierarchy, instanceIndex);
  9917. if (defined$1(result)) {
  9918. return result;
  9919. }
  9920. const parentCount = parentCounts[instanceIndex];
  9921. const parentIndex = parentIndexes[instanceIndex];
  9922. for (let i = 0; i < parentCount; ++i) {
  9923. const parentId = parentIds[parentIndex + i];
  9924. if (parentId !== instanceIndex) {
  9925. stack.push(parentId);
  9926. }
  9927. }
  9928. }
  9929. return null;
  9930. }
  9931. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  9932. let hasParent = true;
  9933. while (hasParent) {
  9934. const result = endConditionCallback(hierarchy, instanceIndex);
  9935. if (defined$1(result)) {
  9936. return result;
  9937. }
  9938. const parentId = hierarchy.parentIds[instanceIndex];
  9939. hasParent = parentId !== instanceIndex;
  9940. instanceIndex = parentId;
  9941. }
  9942. throw new Error('traverseHierarchySingleParent');
  9943. }
  9944. function validateHierarchy(hierarchy) {
  9945. const classIds = hierarchy.classIds;
  9946. const instancesLength = classIds.length;
  9947. for (let i = 0; i < instancesLength; ++i) {
  9948. validateInstance(hierarchy, i, stack);
  9949. }
  9950. }
  9951. function validateInstance(hierarchy, instanceIndex, stack) {
  9952. const parentCounts = hierarchy.parentCounts;
  9953. const parentIds = hierarchy.parentIds;
  9954. const parentIndexes = hierarchy.parentIndexes;
  9955. const classIds = hierarchy.classIds;
  9956. const instancesLength = classIds.length;
  9957. if (!defined$1(parentIds)) {
  9958. return;
  9959. }
  9960. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  9961. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  9962. stack.push(instanceIndex);
  9963. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  9964. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  9965. for (let i = 0; i < parentCount; ++i) {
  9966. const parentId = parentIds[parentIndex + i];
  9967. if (parentId !== instanceIndex) {
  9968. validateInstance(hierarchy, parentId, stack);
  9969. }
  9970. }
  9971. stack.pop(instanceIndex);
  9972. }
  9973. function defined(x) {
  9974. return x !== undefined && x !== null;
  9975. }
  9976. const clone = (x, y) => x;
  9977. const IGNORED_PROPERTY_FIELDS = {
  9978. HIERARCHY: true,
  9979. extensions: true,
  9980. extras: true
  9981. };
  9982. class Tile3DBatchTableParser {
  9983. constructor(json, binary, featureCount, options = {}) {
  9984. var _this$json;
  9985. _defineProperty(this, "json", void 0);
  9986. _defineProperty(this, "binary", void 0);
  9987. _defineProperty(this, "featureCount", void 0);
  9988. _defineProperty(this, "_extensions", void 0);
  9989. _defineProperty(this, "_properties", void 0);
  9990. _defineProperty(this, "_binaryProperties", void 0);
  9991. _defineProperty(this, "_hierarchy", void 0);
  9992. assert$7(featureCount >= 0);
  9993. this.json = json || {};
  9994. this.binary = binary;
  9995. this.featureCount = featureCount;
  9996. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  9997. this._properties = {};
  9998. for (const propertyName in this.json) {
  9999. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10000. this._properties[propertyName] = this.json[propertyName];
  10001. }
  10002. }
  10003. this._binaryProperties = this._initializeBinaryProperties();
  10004. if (options['3DTILES_batch_table_hierarchy']) {
  10005. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10006. }
  10007. }
  10008. getExtension(extensionName) {
  10009. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10010. }
  10011. memorySizeInBytes() {
  10012. return 0;
  10013. }
  10014. isClass(batchId, className) {
  10015. this._checkBatchId(batchId);
  10016. assert$7(typeof className === 'string', className);
  10017. if (this._hierarchy) {
  10018. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10019. const classId = hierarchy.classIds[instanceIndex];
  10020. const instanceClass = hierarchy.classes[classId];
  10021. return instanceClass.name === className;
  10022. });
  10023. return defined(result);
  10024. }
  10025. return false;
  10026. }
  10027. isExactClass(batchId, className) {
  10028. assert$7(typeof className === 'string', className);
  10029. return this.getExactClassName(batchId) === className;
  10030. }
  10031. getExactClassName(batchId) {
  10032. this._checkBatchId(batchId);
  10033. if (this._hierarchy) {
  10034. const classId = this._hierarchy.classIds[batchId];
  10035. const instanceClass = this._hierarchy.classes[classId];
  10036. return instanceClass.name;
  10037. }
  10038. return undefined;
  10039. }
  10040. hasProperty(batchId, name) {
  10041. this._checkBatchId(batchId);
  10042. assert$7(typeof name === 'string', name);
  10043. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10044. }
  10045. getPropertyNames(batchId, results) {
  10046. this._checkBatchId(batchId);
  10047. results = defined(results) ? results : [];
  10048. results.length = 0;
  10049. const propertyNames = Object.keys(this._properties);
  10050. results.push(...propertyNames);
  10051. if (this._hierarchy) {
  10052. this._getPropertyNamesInHierarchy(batchId, results);
  10053. }
  10054. return results;
  10055. }
  10056. getProperty(batchId, name) {
  10057. this._checkBatchId(batchId);
  10058. assert$7(typeof name === 'string', name);
  10059. if (this._binaryProperties) {
  10060. const binaryProperty = this._binaryProperties[name];
  10061. if (defined(binaryProperty)) {
  10062. return this._getBinaryProperty(binaryProperty, batchId);
  10063. }
  10064. }
  10065. const propertyValues = this._properties[name];
  10066. if (defined(propertyValues)) {
  10067. return clone(propertyValues[batchId]);
  10068. }
  10069. if (this._hierarchy) {
  10070. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10071. if (defined(hierarchyProperty)) {
  10072. return hierarchyProperty;
  10073. }
  10074. }
  10075. return undefined;
  10076. }
  10077. setProperty(batchId, name, value) {
  10078. const featureCount = this.featureCount;
  10079. this._checkBatchId(batchId);
  10080. assert$7(typeof name === 'string', name);
  10081. if (this._binaryProperties) {
  10082. const binaryProperty = this._binaryProperties[name];
  10083. if (binaryProperty) {
  10084. this._setBinaryProperty(binaryProperty, batchId, value);
  10085. return;
  10086. }
  10087. }
  10088. if (this._hierarchy) {
  10089. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10090. return;
  10091. }
  10092. }
  10093. let propertyValues = this._properties[name];
  10094. if (!defined(propertyValues)) {
  10095. this._properties[name] = new Array(featureCount);
  10096. propertyValues = this._properties[name];
  10097. }
  10098. propertyValues[batchId] = clone(value);
  10099. }
  10100. _checkBatchId(batchId) {
  10101. const valid = batchId >= 0 && batchId < this.featureCount;
  10102. if (!valid) {
  10103. throw new Error('batchId not in range [0, featureCount - 1].');
  10104. }
  10105. }
  10106. _getBinaryProperty(binaryProperty, index) {
  10107. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10108. }
  10109. _setBinaryProperty(binaryProperty, index, value) {
  10110. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10111. }
  10112. _initializeBinaryProperties() {
  10113. let binaryProperties = null;
  10114. for (const name in this._properties) {
  10115. const property = this._properties[name];
  10116. const binaryProperty = this._initializeBinaryProperty(name, property);
  10117. if (binaryProperty) {
  10118. binaryProperties = binaryProperties || {};
  10119. binaryProperties[name] = binaryProperty;
  10120. }
  10121. }
  10122. return binaryProperties;
  10123. }
  10124. _initializeBinaryProperty(name, property) {
  10125. if ('byteOffset' in property) {
  10126. const tile3DAccessor = property;
  10127. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10128. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10129. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10130. return {
  10131. typedArray: accessor.values,
  10132. componentCount: accessor.size,
  10133. unpack: accessor.unpacker,
  10134. pack: accessor.packer
  10135. };
  10136. }
  10137. return null;
  10138. }
  10139. _hasPropertyInHierarchy(batchId, name) {
  10140. if (!this._hierarchy) {
  10141. return false;
  10142. }
  10143. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10144. const classId = hierarchy.classIds[instanceIndex];
  10145. const instances = hierarchy.classes[classId].instances;
  10146. return defined(instances[name]);
  10147. });
  10148. return defined(result);
  10149. }
  10150. _getPropertyNamesInHierarchy(batchId, results) {
  10151. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10152. const classId = hierarchy.classIds[instanceIndex];
  10153. const instances = hierarchy.classes[classId].instances;
  10154. for (const name in instances) {
  10155. if (instances.hasOwnProperty(name)) {
  10156. if (results.indexOf(name) === -1) {
  10157. results.push(name);
  10158. }
  10159. }
  10160. }
  10161. });
  10162. }
  10163. _getHierarchyProperty(batchId, name) {
  10164. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10165. const classId = hierarchy.classIds[instanceIndex];
  10166. const instanceClass = hierarchy.classes[classId];
  10167. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10168. const propertyValues = instanceClass.instances[name];
  10169. if (defined(propertyValues)) {
  10170. if (defined(propertyValues.typedArray)) {
  10171. return this._getBinaryProperty(propertyValues, indexInClass);
  10172. }
  10173. return clone(propertyValues[indexInClass]);
  10174. }
  10175. return null;
  10176. });
  10177. }
  10178. _setHierarchyProperty(batchTable, batchId, name, value) {
  10179. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10180. const classId = hierarchy.classIds[instanceIndex];
  10181. const instanceClass = hierarchy.classes[classId];
  10182. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10183. const propertyValues = instanceClass.instances[name];
  10184. if (defined(propertyValues)) {
  10185. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10186. if (defined(propertyValues.typedArray)) {
  10187. this._setBinaryProperty(propertyValues, indexInClass, value);
  10188. } else {
  10189. propertyValues[indexInClass] = clone(value);
  10190. }
  10191. return true;
  10192. }
  10193. return false;
  10194. });
  10195. return defined(result);
  10196. }
  10197. }
  10198. const SIZEOF_UINT32$1 = 4;
  10199. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10200. const view = new DataView(arrayBuffer);
  10201. tile.magic = view.getUint32(byteOffset, true);
  10202. byteOffset += SIZEOF_UINT32$1;
  10203. tile.version = view.getUint32(byteOffset, true);
  10204. byteOffset += SIZEOF_UINT32$1;
  10205. tile.byteLength = view.getUint32(byteOffset, true);
  10206. byteOffset += SIZEOF_UINT32$1;
  10207. if (tile.version !== 1) {
  10208. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10209. }
  10210. return byteOffset;
  10211. }
  10212. const SIZEOF_UINT32 = 4;
  10213. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10214. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10215. const view = new DataView(arrayBuffer);
  10216. let batchLength;
  10217. tile.header = tile.header || {};
  10218. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10219. byteOffset += SIZEOF_UINT32;
  10220. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10221. byteOffset += SIZEOF_UINT32;
  10222. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10223. byteOffset += SIZEOF_UINT32;
  10224. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10225. byteOffset += SIZEOF_UINT32;
  10226. if (batchTableJsonByteLength >= 570425344) {
  10227. byteOffset -= SIZEOF_UINT32 * 2;
  10228. batchLength = featureTableJsonByteLength;
  10229. batchTableJsonByteLength = featureTableBinaryByteLength;
  10230. batchTableBinaryByteLength = 0;
  10231. featureTableJsonByteLength = 0;
  10232. featureTableBinaryByteLength = 0;
  10233. console.warn(DEPRECATION_WARNING);
  10234. } else if (batchTableBinaryByteLength >= 570425344) {
  10235. byteOffset -= SIZEOF_UINT32;
  10236. batchLength = batchTableJsonByteLength;
  10237. batchTableJsonByteLength = featureTableJsonByteLength;
  10238. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10239. featureTableJsonByteLength = 0;
  10240. featureTableBinaryByteLength = 0;
  10241. console.warn(DEPRECATION_WARNING);
  10242. }
  10243. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10244. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10245. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10246. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10247. tile.header.batchLength = batchLength;
  10248. return byteOffset;
  10249. }
  10250. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10251. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10252. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10253. return byteOffset;
  10254. }
  10255. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10256. const {
  10257. featureTableJsonByteLength,
  10258. featureTableBinaryByteLength,
  10259. batchLength
  10260. } = tile.header;
  10261. tile.featureTableJson = {
  10262. BATCH_LENGTH: batchLength || 0
  10263. };
  10264. if (featureTableJsonByteLength > 0) {
  10265. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10266. tile.featureTableJson = JSON.parse(featureTableString);
  10267. }
  10268. byteOffset += featureTableJsonByteLength;
  10269. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10270. byteOffset += featureTableBinaryByteLength;
  10271. return byteOffset;
  10272. }
  10273. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10274. const {
  10275. batchTableJsonByteLength,
  10276. batchTableBinaryByteLength
  10277. } = tile.header;
  10278. if (batchTableJsonByteLength > 0) {
  10279. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10280. tile.batchTableJson = JSON.parse(batchTableString);
  10281. byteOffset += batchTableJsonByteLength;
  10282. if (batchTableBinaryByteLength > 0) {
  10283. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10284. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10285. byteOffset += batchTableBinaryByteLength;
  10286. }
  10287. }
  10288. return byteOffset;
  10289. }
  10290. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10291. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10292. return null;
  10293. }
  10294. const {
  10295. batchIds,
  10296. isRGB565,
  10297. pointCount
  10298. } = tile;
  10299. if (batchIds && batchTable) {
  10300. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10301. for (let i = 0; i < pointCount; i++) {
  10302. const batchId = batchIds[i];
  10303. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10304. const color = dimensions.map(d => d * 255);
  10305. colorArray[i * 3] = color[0];
  10306. colorArray[i * 3 + 1] = color[1];
  10307. colorArray[i * 3 + 2] = color[2];
  10308. }
  10309. return {
  10310. type: GL$1.UNSIGNED_BYTE,
  10311. value: colorArray,
  10312. size: 3,
  10313. normalized: true
  10314. };
  10315. }
  10316. if (isRGB565) {
  10317. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10318. for (let i = 0; i < pointCount; i++) {
  10319. const color = decodeRGB565(colors[i]);
  10320. colorArray[i * 3] = color[0];
  10321. colorArray[i * 3 + 1] = color[1];
  10322. colorArray[i * 3 + 2] = color[2];
  10323. }
  10324. return {
  10325. type: GL$1.UNSIGNED_BYTE,
  10326. value: colorArray,
  10327. size: 3,
  10328. normalized: true
  10329. };
  10330. }
  10331. if (colors && colors.length === pointCount * 3) {
  10332. return {
  10333. type: GL$1.UNSIGNED_BYTE,
  10334. value: colors,
  10335. size: 3,
  10336. normalized: true
  10337. };
  10338. }
  10339. return {
  10340. type: GL$1.UNSIGNED_BYTE,
  10341. value: colors,
  10342. size: 4,
  10343. normalized: true
  10344. };
  10345. }
  10346. const scratchNormal = new Vector3();
  10347. function normalize3DTileNormalAttribute(tile, normals) {
  10348. if (!normals) {
  10349. return null;
  10350. }
  10351. if (tile.isOctEncoded16P) {
  10352. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10353. for (let i = 0; i < tile.pointsLength; i++) {
  10354. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10355. scratchNormal.toArray(decodedArray, i * 3);
  10356. }
  10357. return {
  10358. type: GL$1.FLOAT,
  10359. size: 2,
  10360. value: decodedArray
  10361. };
  10362. }
  10363. return {
  10364. type: GL$1.FLOAT,
  10365. size: 2,
  10366. value: normals
  10367. };
  10368. }
  10369. function normalize3DTilePositionAttribute(tile, positions, options) {
  10370. if (!tile.isQuantized) {
  10371. return positions;
  10372. }
  10373. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10374. tile.isQuantized = false;
  10375. return decodeQuantizedPositions(tile, positions);
  10376. }
  10377. return {
  10378. type: GL$1.UNSIGNED_SHORT,
  10379. value: positions,
  10380. size: 3,
  10381. normalized: true
  10382. };
  10383. }
  10384. function decodeQuantizedPositions(tile, positions) {
  10385. const scratchPosition = new Vector3();
  10386. const decodedArray = new Float32Array(tile.pointCount * 3);
  10387. for (let i = 0; i < tile.pointCount; i++) {
  10388. 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);
  10389. }
  10390. return decodedArray;
  10391. }
  10392. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10393. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10394. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10395. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10396. initializeTile(tile);
  10397. const {
  10398. featureTable,
  10399. batchTable
  10400. } = parsePointCloudTables(tile);
  10401. await parseDraco(tile, featureTable, batchTable, options, context);
  10402. parsePositions(tile, featureTable, options);
  10403. parseColors(tile, featureTable, batchTable);
  10404. parseNormals(tile, featureTable);
  10405. return byteOffset;
  10406. }
  10407. function initializeTile(tile) {
  10408. tile.attributes = {
  10409. positions: null,
  10410. colors: null,
  10411. normals: null,
  10412. batchIds: null
  10413. };
  10414. tile.isQuantized = false;
  10415. tile.isTranslucent = false;
  10416. tile.isRGB565 = false;
  10417. tile.isOctEncoded16P = false;
  10418. }
  10419. function parsePointCloudTables(tile) {
  10420. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10421. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10422. if (!Number.isFinite(pointsLength)) {
  10423. throw new Error('POINTS_LENGTH must be defined');
  10424. }
  10425. featureTable.featuresLength = pointsLength;
  10426. tile.featuresLength = pointsLength;
  10427. tile.pointsLength = pointsLength;
  10428. tile.pointCount = pointsLength;
  10429. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10430. const batchTable = parseBatchIds(tile, featureTable);
  10431. return {
  10432. featureTable,
  10433. batchTable
  10434. };
  10435. }
  10436. function parsePositions(tile, featureTable, options) {
  10437. if (!tile.attributes.positions) {
  10438. if (featureTable.hasProperty('POSITION')) {
  10439. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10440. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10441. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10442. tile.isQuantized = true;
  10443. tile.quantizedRange = (1 << 16) - 1;
  10444. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10445. if (!tile.quantizedVolumeScale) {
  10446. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10447. }
  10448. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10449. if (!tile.quantizedVolumeOffset) {
  10450. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10451. }
  10452. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10453. }
  10454. }
  10455. if (!tile.attributes.positions) {
  10456. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10457. }
  10458. }
  10459. function parseColors(tile, featureTable, batchTable) {
  10460. if (!tile.attributes.colors) {
  10461. let colors = null;
  10462. if (featureTable.hasProperty('RGBA')) {
  10463. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10464. tile.isTranslucent = true;
  10465. } else if (featureTable.hasProperty('RGB')) {
  10466. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10467. } else if (featureTable.hasProperty('RGB565')) {
  10468. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10469. tile.isRGB565 = true;
  10470. }
  10471. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10472. }
  10473. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10474. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10475. }
  10476. }
  10477. function parseNormals(tile, featureTable) {
  10478. if (!tile.attributes.normals) {
  10479. let normals = null;
  10480. if (featureTable.hasProperty('NORMAL')) {
  10481. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10482. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10483. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10484. tile.isOctEncoded16P = true;
  10485. }
  10486. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10487. }
  10488. }
  10489. function parseBatchIds(tile, featureTable) {
  10490. let batchTable = null;
  10491. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10492. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10493. if (tile.batchIds) {
  10494. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10495. if (!batchFeatureLength) {
  10496. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10497. }
  10498. const {
  10499. batchTableJson,
  10500. batchTableBinary
  10501. } = tile;
  10502. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10503. }
  10504. }
  10505. return batchTable;
  10506. }
  10507. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10508. let dracoBuffer;
  10509. let dracoFeatureTableProperties;
  10510. let dracoBatchTableProperties;
  10511. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10512. if (batchTableDraco) {
  10513. dracoBatchTableProperties = batchTableDraco.properties;
  10514. }
  10515. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10516. if (featureTableDraco) {
  10517. dracoFeatureTableProperties = featureTableDraco.properties;
  10518. const dracoByteOffset = featureTableDraco.byteOffset;
  10519. const dracoByteLength = featureTableDraco.byteLength;
  10520. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10521. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10522. }
  10523. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10524. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10525. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10526. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10527. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10528. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10529. }
  10530. if (!dracoBuffer) {
  10531. return true;
  10532. }
  10533. const dracoData = {
  10534. buffer: dracoBuffer,
  10535. properties: { ...dracoFeatureTableProperties,
  10536. ...dracoBatchTableProperties
  10537. },
  10538. featureTableProperties: dracoFeatureTableProperties,
  10539. batchTableProperties: dracoBatchTableProperties,
  10540. dequantizeInShader: false
  10541. };
  10542. return await loadDraco(tile, dracoData, options, context);
  10543. }
  10544. async function loadDraco(tile, dracoData, options, context) {
  10545. const {
  10546. parse
  10547. } = context;
  10548. const dracoOptions = { ...options,
  10549. draco: { ...options.draco,
  10550. extraAttributes: dracoData.batchTableProperties || {}
  10551. }
  10552. };
  10553. delete dracoOptions['3d-tiles'];
  10554. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10555. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10556. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10557. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10558. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10559. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10560. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10561. if (isQuantizedDraco) {
  10562. const quantization = data.POSITION.data.quantization;
  10563. const range = quantization.range;
  10564. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10565. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10566. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10567. tile.isQuantizedDraco = true;
  10568. }
  10569. if (isOctEncodedDraco) {
  10570. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10571. tile.isOctEncodedDraco = true;
  10572. }
  10573. const batchTableAttributes = {};
  10574. if (dracoData.batchTableProperties) {
  10575. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10576. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10577. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10578. }
  10579. }
  10580. }
  10581. tile.attributes = {
  10582. positions: decodedPositions,
  10583. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10584. normals: decodedNormals,
  10585. batchIds: decodedBatchIds,
  10586. ...batchTableAttributes
  10587. };
  10588. }
  10589. const VERSION$3 = "3.1.4" ;
  10590. const VERSION$2 = "3.1.4" ;
  10591. const VERSION$1 = "3.1.4" ;
  10592. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10593. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10594. let loadBasisTranscoderPromise;
  10595. async function loadBasisTrascoderModule(options) {
  10596. const modules = options.modules || {};
  10597. if (modules.basis) {
  10598. return modules.basis;
  10599. }
  10600. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10601. return await loadBasisTranscoderPromise;
  10602. }
  10603. async function loadBasisTrascoder(options) {
  10604. let BASIS = null;
  10605. let wasmBinary = null;
  10606. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10607. BASIS = BASIS || globalThis.BASIS;
  10608. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10609. }
  10610. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10611. const options = {};
  10612. if (wasmBinary) {
  10613. options.wasmBinary = wasmBinary;
  10614. }
  10615. return new Promise(resolve => {
  10616. BasisModule(options).then(module => {
  10617. const {
  10618. BasisFile,
  10619. initializeBasis
  10620. } = module;
  10621. initializeBasis();
  10622. resolve({
  10623. BasisFile
  10624. });
  10625. });
  10626. });
  10627. }
  10628. let loadBasisEncoderPromise;
  10629. async function loadBasisEncoderModule(options) {
  10630. const modules = options.modules || {};
  10631. if (modules.basisEncoder) {
  10632. return modules.basisEncoder;
  10633. }
  10634. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10635. return await loadBasisEncoderPromise;
  10636. }
  10637. async function loadBasisEncoder(options) {
  10638. let BASIS_ENCODER = null;
  10639. let wasmBinary = null;
  10640. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10641. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10642. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10643. }
  10644. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10645. const options = {};
  10646. if (wasmBinary) {
  10647. options.wasmBinary = wasmBinary;
  10648. }
  10649. return new Promise(resolve => {
  10650. BasisEncoderModule(options).then(module => {
  10651. const {
  10652. BasisFile,
  10653. KTX2File,
  10654. initializeBasis,
  10655. BasisEncoder
  10656. } = module;
  10657. initializeBasis();
  10658. resolve({
  10659. BasisFile,
  10660. KTX2File,
  10661. BasisEncoder
  10662. });
  10663. });
  10664. });
  10665. }
  10666. const GL_EXTENSIONS_CONSTANTS = {
  10667. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10668. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10669. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10670. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10671. COMPRESSED_R11_EAC: 0x9270,
  10672. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10673. COMPRESSED_RG11_EAC: 0x9272,
  10674. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10675. COMPRESSED_RGB8_ETC2: 0x9274,
  10676. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10677. COMPRESSED_SRGB8_ETC2: 0x9276,
  10678. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10679. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10680. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10681. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10682. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10683. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10684. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10685. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10686. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10687. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10688. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10689. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10690. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10691. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10692. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10693. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10694. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10695. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10696. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10697. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10698. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10699. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10700. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10701. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10702. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10703. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10704. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10705. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10706. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10707. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10708. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10709. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10710. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10711. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10712. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10713. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10714. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10715. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10716. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10717. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10718. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10719. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10720. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10721. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10722. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10723. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10724. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10725. };
  10726. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10727. const WEBGL_EXTENSIONS = {
  10728. WEBGL_compressed_texture_s3tc: 'dxt',
  10729. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10730. WEBGL_compressed_texture_etc1: 'etc1',
  10731. WEBGL_compressed_texture_etc: 'etc2',
  10732. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10733. WEBGL_compressed_texture_atc: 'atc',
  10734. WEBGL_compressed_texture_astc: 'astc',
  10735. EXT_texture_compression_rgtc: 'rgtc'
  10736. };
  10737. let formats = null;
  10738. function getSupportedGPUTextureFormats(gl) {
  10739. if (!formats) {
  10740. gl = gl || getWebGLContext() || undefined;
  10741. formats = new Set();
  10742. for (const prefix of BROWSER_PREFIXES) {
  10743. for (const extension in WEBGL_EXTENSIONS) {
  10744. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10745. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10746. formats.add(gpuTextureFormat);
  10747. }
  10748. }
  10749. }
  10750. }
  10751. return formats;
  10752. }
  10753. function getWebGLContext() {
  10754. try {
  10755. const canvas = document.createElement('canvas');
  10756. return canvas.getContext('webgl');
  10757. } catch (error) {
  10758. return null;
  10759. }
  10760. }
  10761. 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={}));
  10762. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10763. function isKTX(data) {
  10764. const id = new Uint8Array(data);
  10765. 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];
  10766. return !notKTX;
  10767. }
  10768. const OutputFormat = {
  10769. etc1: {
  10770. basisFormat: 0,
  10771. compressed: true,
  10772. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10773. },
  10774. etc2: {
  10775. basisFormat: 1,
  10776. compressed: true
  10777. },
  10778. bc1: {
  10779. basisFormat: 2,
  10780. compressed: true,
  10781. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10782. },
  10783. bc3: {
  10784. basisFormat: 3,
  10785. compressed: true,
  10786. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10787. },
  10788. bc4: {
  10789. basisFormat: 4,
  10790. compressed: true
  10791. },
  10792. bc5: {
  10793. basisFormat: 5,
  10794. compressed: true
  10795. },
  10796. 'bc7-m6-opaque-only': {
  10797. basisFormat: 6,
  10798. compressed: true
  10799. },
  10800. 'bc7-m5': {
  10801. basisFormat: 7,
  10802. compressed: true
  10803. },
  10804. 'pvrtc1-4-rgb': {
  10805. basisFormat: 8,
  10806. compressed: true,
  10807. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10808. },
  10809. 'pvrtc1-4-rgba': {
  10810. basisFormat: 9,
  10811. compressed: true,
  10812. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10813. },
  10814. 'astc-4x4': {
  10815. basisFormat: 10,
  10816. compressed: true,
  10817. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10818. },
  10819. 'atc-rgb': {
  10820. basisFormat: 11,
  10821. compressed: true
  10822. },
  10823. 'atc-rgba-interpolated-alpha': {
  10824. basisFormat: 12,
  10825. compressed: true
  10826. },
  10827. rgba32: {
  10828. basisFormat: 13,
  10829. compressed: false
  10830. },
  10831. rgb565: {
  10832. basisFormat: 14,
  10833. compressed: false
  10834. },
  10835. bgr565: {
  10836. basisFormat: 15,
  10837. compressed: false
  10838. },
  10839. rgba4444: {
  10840. basisFormat: 16,
  10841. compressed: false
  10842. }
  10843. };
  10844. async function parseBasis(data, options) {
  10845. if (options.basis.containerFormat === 'auto') {
  10846. if (isKTX(data)) {
  10847. const fileConstructors = await loadBasisEncoderModule(options);
  10848. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10849. }
  10850. const {
  10851. BasisFile
  10852. } = await loadBasisTrascoderModule(options);
  10853. return parseBasisFile(BasisFile, data, options);
  10854. }
  10855. switch (options.basis.module) {
  10856. case 'encoder':
  10857. const fileConstructors = await loadBasisEncoderModule(options);
  10858. switch (options.basis.containerFormat) {
  10859. case 'ktx2':
  10860. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10861. case 'basis':
  10862. default:
  10863. return parseBasisFile(fileConstructors.BasisFile, data, options);
  10864. }
  10865. case 'transcoder':
  10866. default:
  10867. const {
  10868. BasisFile
  10869. } = await loadBasisTrascoderModule(options);
  10870. return parseBasisFile(BasisFile, data, options);
  10871. }
  10872. }
  10873. function parseBasisFile(BasisFile, data, options) {
  10874. const basisFile = new BasisFile(new Uint8Array(data));
  10875. try {
  10876. if (!basisFile.startTranscoding()) {
  10877. return null;
  10878. }
  10879. const imageCount = basisFile.getNumImages();
  10880. const images = [];
  10881. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  10882. const levelsCount = basisFile.getNumLevels(imageIndex);
  10883. const levels = [];
  10884. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10885. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  10886. }
  10887. images.push(levels);
  10888. }
  10889. return images;
  10890. } finally {
  10891. basisFile.close();
  10892. basisFile.delete();
  10893. }
  10894. }
  10895. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  10896. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  10897. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  10898. const hasAlpha = basisFile.getHasAlpha();
  10899. const {
  10900. compressed,
  10901. format,
  10902. basisFormat
  10903. } = getBasisOptions(options, hasAlpha);
  10904. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  10905. const decodedData = new Uint8Array(decodedSize);
  10906. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  10907. return null;
  10908. }
  10909. return {
  10910. width,
  10911. height,
  10912. data: decodedData,
  10913. compressed,
  10914. hasAlpha,
  10915. format
  10916. };
  10917. }
  10918. function parseKTX2File(KTX2File, data, options) {
  10919. const ktx2File = new KTX2File(new Uint8Array(data));
  10920. try {
  10921. if (!ktx2File.startTranscoding()) {
  10922. return null;
  10923. }
  10924. const levelsCount = ktx2File.getLevels();
  10925. const levels = [];
  10926. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10927. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  10928. break;
  10929. }
  10930. return levels;
  10931. } finally {
  10932. ktx2File.close();
  10933. ktx2File.delete();
  10934. }
  10935. }
  10936. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  10937. const {
  10938. alphaFlag,
  10939. height,
  10940. width
  10941. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  10942. const {
  10943. compressed,
  10944. format,
  10945. basisFormat
  10946. } = getBasisOptions(options, alphaFlag);
  10947. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  10948. const decodedData = new Uint8Array(decodedSize);
  10949. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  10950. return null;
  10951. }
  10952. return {
  10953. width,
  10954. height,
  10955. data: decodedData,
  10956. compressed,
  10957. alphaFlag,
  10958. format
  10959. };
  10960. }
  10961. function getBasisOptions(options, hasAlpha) {
  10962. let format = options && options.basis && options.basis.format;
  10963. if (format === 'auto') {
  10964. format = selectSupportedBasisFormat();
  10965. }
  10966. if (typeof format === 'object') {
  10967. format = hasAlpha ? format.alpha : format.noAlpha;
  10968. }
  10969. format = format.toLowerCase();
  10970. return OutputFormat[format];
  10971. }
  10972. function selectSupportedBasisFormat() {
  10973. const supportedFormats = getSupportedGPUTextureFormats();
  10974. if (supportedFormats.has('astc')) {
  10975. return 'astc-4x4';
  10976. } else if (supportedFormats.has('dxt')) {
  10977. return {
  10978. alpha: 'bc3',
  10979. noAlpha: 'bc1'
  10980. };
  10981. } else if (supportedFormats.has('pvrtc')) {
  10982. return {
  10983. alpha: 'pvrtc1-4-rgba',
  10984. noAlpha: 'pvrtc1-4-rgb'
  10985. };
  10986. } else if (supportedFormats.has('etc1')) {
  10987. return 'etc1';
  10988. } else if (supportedFormats.has('etc2')) {
  10989. return 'etc2';
  10990. }
  10991. return 'rgb565';
  10992. }
  10993. const BasisWorkerLoader = {
  10994. name: 'Basis',
  10995. id: 'basis',
  10996. module: 'textures',
  10997. version: VERSION$2,
  10998. worker: true,
  10999. extensions: ['basis', 'ktx2'],
  11000. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11001. tests: ['sB'],
  11002. binary: true,
  11003. options: {
  11004. basis: {
  11005. format: 'auto',
  11006. libraryPath: 'libs/',
  11007. containerFormat: 'auto',
  11008. module: 'transcoder'
  11009. }
  11010. }
  11011. };
  11012. const BasisLoader = { ...BasisWorkerLoader,
  11013. parse: parseBasis
  11014. };
  11015. const VERSION = "3.1.4" ;
  11016. const {
  11017. _parseImageNode
  11018. } = globalThis;
  11019. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11020. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11021. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11022. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11023. function isImageTypeSupported(type) {
  11024. switch (type) {
  11025. case 'auto':
  11026. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11027. case 'imagebitmap':
  11028. return IMAGE_BITMAP_SUPPORTED;
  11029. case 'image':
  11030. return IMAGE_SUPPORTED;
  11031. case 'data':
  11032. return DATA_SUPPORTED;
  11033. default:
  11034. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11035. }
  11036. }
  11037. function getDefaultImageType() {
  11038. if (IMAGE_BITMAP_SUPPORTED) {
  11039. return 'imagebitmap';
  11040. }
  11041. if (IMAGE_SUPPORTED) {
  11042. return 'image';
  11043. }
  11044. if (DATA_SUPPORTED) {
  11045. return 'data';
  11046. }
  11047. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11048. }
  11049. function getImageType(image) {
  11050. const format = getImageTypeOrNull(image);
  11051. if (!format) {
  11052. throw new Error('Not an image');
  11053. }
  11054. return format;
  11055. }
  11056. function getImageData(image) {
  11057. switch (getImageType(image)) {
  11058. case 'data':
  11059. return image;
  11060. case 'image':
  11061. case 'imagebitmap':
  11062. const canvas = document.createElement('canvas');
  11063. const context = canvas.getContext('2d');
  11064. if (!context) {
  11065. throw new Error('getImageData');
  11066. }
  11067. canvas.width = image.width;
  11068. canvas.height = image.height;
  11069. context.drawImage(image, 0, 0);
  11070. return context.getImageData(0, 0, image.width, image.height);
  11071. default:
  11072. throw new Error('getImageData');
  11073. }
  11074. }
  11075. function getImageTypeOrNull(image) {
  11076. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11077. return 'imagebitmap';
  11078. }
  11079. if (typeof Image !== 'undefined' && image instanceof Image) {
  11080. return 'image';
  11081. }
  11082. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11083. return 'data';
  11084. }
  11085. return null;
  11086. }
  11087. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11088. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11089. function isSVG(url) {
  11090. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11091. }
  11092. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11093. if (isSVG(url)) {
  11094. const textDecoder = new TextDecoder();
  11095. let xmlText = textDecoder.decode(arrayBuffer);
  11096. try {
  11097. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11098. xmlText = unescape(encodeURIComponent(xmlText));
  11099. }
  11100. } catch (error) {
  11101. throw new Error(error.message);
  11102. }
  11103. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11104. return src;
  11105. }
  11106. return getBlob(arrayBuffer, url);
  11107. }
  11108. function getBlob(arrayBuffer, url) {
  11109. if (isSVG(url)) {
  11110. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11111. }
  11112. return new Blob([new Uint8Array(arrayBuffer)]);
  11113. }
  11114. async function parseToImage(arrayBuffer, options, url) {
  11115. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11116. const URL = self.URL || self.webkitURL;
  11117. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11118. try {
  11119. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11120. } finally {
  11121. if (objectUrl) {
  11122. URL.revokeObjectURL(objectUrl);
  11123. }
  11124. }
  11125. }
  11126. async function loadToImage(url, options) {
  11127. const image = new Image();
  11128. image.src = url;
  11129. if (options.image && options.image.decode && image.decode) {
  11130. await image.decode();
  11131. return image;
  11132. }
  11133. return await new Promise((resolve, reject) => {
  11134. try {
  11135. image.onload = () => resolve(image);
  11136. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11137. } catch (error) {
  11138. reject(error);
  11139. }
  11140. });
  11141. }
  11142. const EMPTY_OBJECT = {};
  11143. let imagebitmapOptionsSupported = true;
  11144. async function parseToImageBitmap(arrayBuffer, options, url) {
  11145. let blob;
  11146. if (isSVG(url)) {
  11147. const image = await parseToImage(arrayBuffer, options, url);
  11148. blob = image;
  11149. } else {
  11150. blob = getBlob(arrayBuffer, url);
  11151. }
  11152. const imagebitmapOptions = options && options.imagebitmap;
  11153. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11154. }
  11155. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11156. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11157. imagebitmapOptions = null;
  11158. }
  11159. if (imagebitmapOptions) {
  11160. try {
  11161. return await createImageBitmap(blob, imagebitmapOptions);
  11162. } catch (error) {
  11163. console.warn(error);
  11164. imagebitmapOptionsSupported = false;
  11165. }
  11166. }
  11167. return await createImageBitmap(blob);
  11168. }
  11169. function isEmptyObject(object) {
  11170. for (const key in object || EMPTY_OBJECT) {
  11171. return false;
  11172. }
  11173. return true;
  11174. }
  11175. const BIG_ENDIAN = false;
  11176. const LITTLE_ENDIAN = true;
  11177. function getBinaryImageMetadata(binaryData) {
  11178. const dataView = toDataView(binaryData);
  11179. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11180. }
  11181. function getPngMetadata(binaryData) {
  11182. const dataView = toDataView(binaryData);
  11183. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11184. if (!isPng) {
  11185. return null;
  11186. }
  11187. return {
  11188. mimeType: 'image/png',
  11189. width: dataView.getUint32(16, BIG_ENDIAN),
  11190. height: dataView.getUint32(20, BIG_ENDIAN)
  11191. };
  11192. }
  11193. function getGifMetadata(binaryData) {
  11194. const dataView = toDataView(binaryData);
  11195. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11196. if (!isGif) {
  11197. return null;
  11198. }
  11199. return {
  11200. mimeType: 'image/gif',
  11201. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11202. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11203. };
  11204. }
  11205. function getBmpMetadata(binaryData) {
  11206. const dataView = toDataView(binaryData);
  11207. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11208. if (!isBmp) {
  11209. return null;
  11210. }
  11211. return {
  11212. mimeType: 'image/bmp',
  11213. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11214. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11215. };
  11216. }
  11217. function getJpegMetadata(binaryData) {
  11218. const dataView = toDataView(binaryData);
  11219. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11220. if (!isJpeg) {
  11221. return null;
  11222. }
  11223. const {
  11224. tableMarkers,
  11225. sofMarkers
  11226. } = getJpegMarkers();
  11227. let i = 2;
  11228. while (i + 9 < dataView.byteLength) {
  11229. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11230. if (sofMarkers.has(marker)) {
  11231. return {
  11232. mimeType: 'image/jpeg',
  11233. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11234. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11235. };
  11236. }
  11237. if (!tableMarkers.has(marker)) {
  11238. return null;
  11239. }
  11240. i += 2;
  11241. i += dataView.getUint16(i, BIG_ENDIAN);
  11242. }
  11243. return null;
  11244. }
  11245. function getJpegMarkers() {
  11246. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11247. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11248. tableMarkers.add(i);
  11249. }
  11250. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11251. return {
  11252. tableMarkers,
  11253. sofMarkers
  11254. };
  11255. }
  11256. function toDataView(data) {
  11257. if (data instanceof DataView) {
  11258. return data;
  11259. }
  11260. if (ArrayBuffer.isView(data)) {
  11261. return new DataView(data.buffer);
  11262. }
  11263. if (data instanceof ArrayBuffer) {
  11264. return new DataView(data);
  11265. }
  11266. throw new Error('toDataView');
  11267. }
  11268. async function parseToNodeImage(arrayBuffer, options) {
  11269. const {
  11270. mimeType
  11271. } = getBinaryImageMetadata(arrayBuffer) || {};
  11272. const _parseImageNode = globalThis._parseImageNode;
  11273. assert$7(_parseImageNode);
  11274. return await _parseImageNode(arrayBuffer, mimeType);
  11275. }
  11276. async function parseImage(arrayBuffer, options, context) {
  11277. options = options || {};
  11278. const imageOptions = options.image || {};
  11279. const imageType = imageOptions.type || 'auto';
  11280. const {
  11281. url
  11282. } = context || {};
  11283. const loadType = getLoadableImageType(imageType);
  11284. let image;
  11285. switch (loadType) {
  11286. case 'imagebitmap':
  11287. image = await parseToImageBitmap(arrayBuffer, options, url);
  11288. break;
  11289. case 'image':
  11290. image = await parseToImage(arrayBuffer, options, url);
  11291. break;
  11292. case 'data':
  11293. image = await parseToNodeImage(arrayBuffer);
  11294. break;
  11295. default:
  11296. assert$7(false);
  11297. }
  11298. if (imageType === 'data') {
  11299. image = getImageData(image);
  11300. }
  11301. return image;
  11302. }
  11303. function getLoadableImageType(type) {
  11304. switch (type) {
  11305. case 'auto':
  11306. case 'data':
  11307. return getDefaultImageType();
  11308. default:
  11309. isImageTypeSupported(type);
  11310. return type;
  11311. }
  11312. }
  11313. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11314. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11315. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11316. image: {
  11317. type: 'auto',
  11318. decode: true
  11319. }
  11320. };
  11321. const ImageLoader = {
  11322. id: 'image',
  11323. module: 'images',
  11324. name: 'Images',
  11325. version: VERSION,
  11326. mimeTypes: MIME_TYPES,
  11327. extensions: EXTENSIONS$1,
  11328. parse: parseImage,
  11329. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11330. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11331. };
  11332. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11333. const mimeTypeSupported = {};
  11334. function _isImageFormatSupported(mimeType) {
  11335. if (mimeTypeSupported[mimeType] === undefined) {
  11336. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11337. }
  11338. return mimeTypeSupported[mimeType];
  11339. }
  11340. function checkFormatSupport(mimeType) {
  11341. switch (mimeType) {
  11342. case 'image/webp':
  11343. return checkWebPSupport();
  11344. case 'image/svg':
  11345. return isBrowser$2;
  11346. default:
  11347. if (!isBrowser$2) {
  11348. const {
  11349. _parseImageNode
  11350. } = globalThis;
  11351. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11352. }
  11353. return true;
  11354. }
  11355. }
  11356. function checkWebPSupport() {
  11357. if (!isBrowser$2) {
  11358. return false;
  11359. }
  11360. try {
  11361. const element = document.createElement('canvas');
  11362. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11363. } catch {
  11364. return false;
  11365. }
  11366. }
  11367. function assert$1(condition, message) {
  11368. if (!condition) {
  11369. throw new Error(message || 'assert failed: gltf');
  11370. }
  11371. }
  11372. function resolveUrl(url, options) {
  11373. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11374. if (absolute) {
  11375. return url;
  11376. }
  11377. const baseUrl = options.baseUri || options.uri;
  11378. if (!baseUrl) {
  11379. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11380. }
  11381. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11382. }
  11383. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11384. const bufferView = json.bufferViews[bufferViewIndex];
  11385. assert$1(bufferView);
  11386. const bufferIndex = bufferView.buffer;
  11387. const binChunk = buffers[bufferIndex];
  11388. assert$1(binChunk);
  11389. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11390. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11391. }
  11392. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11393. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11394. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11395. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11396. SCALAR: 1,
  11397. VEC2: 2,
  11398. VEC3: 3,
  11399. VEC4: 4,
  11400. MAT2: 4,
  11401. MAT3: 9,
  11402. MAT4: 16
  11403. };
  11404. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11405. 5120: 1,
  11406. 5121: 1,
  11407. 5122: 2,
  11408. 5123: 2,
  11409. 5125: 4,
  11410. 5126: 4
  11411. };
  11412. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11413. 5120: Int8Array,
  11414. 5121: Uint8Array,
  11415. 5122: Int16Array,
  11416. 5123: Uint16Array,
  11417. 5125: Uint32Array,
  11418. 5126: Float32Array
  11419. };
  11420. function getAccessorTypeFromSize(size) {
  11421. const type = TYPES[size - 1];
  11422. return type || TYPES[0];
  11423. }
  11424. function getComponentTypeFromArray(typedArray) {
  11425. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11426. if (!componentType) {
  11427. throw new Error('Illegal typed array');
  11428. }
  11429. return componentType;
  11430. }
  11431. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11432. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11433. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11434. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11435. const length = accessor.count * components;
  11436. const byteLength = accessor.count * components * bytesPerComponent;
  11437. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11438. return {
  11439. ArrayType,
  11440. length,
  11441. byteLength
  11442. };
  11443. }
  11444. const DEFAULT_GLTF_JSON = {
  11445. asset: {
  11446. version: '2.0',
  11447. generator: 'loaders.gl'
  11448. },
  11449. buffers: []
  11450. };
  11451. class GLTFScenegraph {
  11452. constructor(gltf) {
  11453. _defineProperty(this, "gltf", void 0);
  11454. _defineProperty(this, "sourceBuffers", void 0);
  11455. _defineProperty(this, "byteLength", void 0);
  11456. this.gltf = gltf || {
  11457. json: { ...DEFAULT_GLTF_JSON
  11458. },
  11459. buffers: []
  11460. };
  11461. this.sourceBuffers = [];
  11462. this.byteLength = 0;
  11463. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11464. this.byteLength = this.gltf.buffers[0].byteLength;
  11465. this.sourceBuffers = [this.gltf.buffers[0]];
  11466. }
  11467. }
  11468. get json() {
  11469. return this.gltf.json;
  11470. }
  11471. getApplicationData(key) {
  11472. const data = this.json[key];
  11473. return data;
  11474. }
  11475. getExtraData(key) {
  11476. const extras = this.json.extras || {};
  11477. return extras[key];
  11478. }
  11479. getExtension(extensionName) {
  11480. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11481. const extensions = this.json.extensions || {};
  11482. return isExtension ? extensions[extensionName] || true : null;
  11483. }
  11484. getRequiredExtension(extensionName) {
  11485. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11486. return isRequired ? this.getExtension(extensionName) : null;
  11487. }
  11488. getRequiredExtensions() {
  11489. return this.json.extensionsRequired || [];
  11490. }
  11491. getUsedExtensions() {
  11492. return this.json.extensionsUsed || [];
  11493. }
  11494. getObjectExtension(object, extensionName) {
  11495. const extensions = object.extensions || {};
  11496. return extensions[extensionName];
  11497. }
  11498. getScene(index) {
  11499. return this.getObject('scenes', index);
  11500. }
  11501. getNode(index) {
  11502. return this.getObject('nodes', index);
  11503. }
  11504. getSkin(index) {
  11505. return this.getObject('skins', index);
  11506. }
  11507. getMesh(index) {
  11508. return this.getObject('meshes', index);
  11509. }
  11510. getMaterial(index) {
  11511. return this.getObject('materials', index);
  11512. }
  11513. getAccessor(index) {
  11514. return this.getObject('accessors', index);
  11515. }
  11516. getTexture(index) {
  11517. return this.getObject('textures', index);
  11518. }
  11519. getSampler(index) {
  11520. return this.getObject('samplers', index);
  11521. }
  11522. getImage(index) {
  11523. return this.getObject('images', index);
  11524. }
  11525. getBufferView(index) {
  11526. return this.getObject('bufferViews', index);
  11527. }
  11528. getBuffer(index) {
  11529. return this.getObject('buffers', index);
  11530. }
  11531. getObject(array, index) {
  11532. if (typeof index === 'object') {
  11533. return index;
  11534. }
  11535. const object = this.json[array] && this.json[array][index];
  11536. if (!object) {
  11537. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11538. }
  11539. return object;
  11540. }
  11541. getTypedArrayForBufferView(bufferView) {
  11542. bufferView = this.getBufferView(bufferView);
  11543. const bufferIndex = bufferView.buffer;
  11544. const binChunk = this.gltf.buffers[bufferIndex];
  11545. assert$1(binChunk);
  11546. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11547. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11548. }
  11549. getTypedArrayForAccessor(accessor) {
  11550. accessor = this.getAccessor(accessor);
  11551. const bufferView = this.getBufferView(accessor.bufferView);
  11552. const buffer = this.getBuffer(bufferView.buffer);
  11553. const arrayBuffer = buffer.data;
  11554. const {
  11555. ArrayType,
  11556. length
  11557. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11558. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11559. return new ArrayType(arrayBuffer, byteOffset, length);
  11560. }
  11561. getTypedArrayForImageData(image) {
  11562. image = this.getAccessor(image);
  11563. const bufferView = this.getBufferView(image.bufferView);
  11564. const buffer = this.getBuffer(bufferView.buffer);
  11565. const arrayBuffer = buffer.data;
  11566. const byteOffset = bufferView.byteOffset || 0;
  11567. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11568. }
  11569. addApplicationData(key, data) {
  11570. this.json[key] = data;
  11571. return this;
  11572. }
  11573. addExtraData(key, data) {
  11574. this.json.extras = this.json.extras || {};
  11575. this.json.extras[key] = data;
  11576. return this;
  11577. }
  11578. addObjectExtension(object, extensionName, data) {
  11579. object.extensions = object.extensions || {};
  11580. object.extensions[extensionName] = data;
  11581. this.registerUsedExtension(extensionName);
  11582. return this;
  11583. }
  11584. setObjectExtension(object, extensionName, data) {
  11585. const extensions = object.extensions || {};
  11586. extensions[extensionName] = data;
  11587. }
  11588. removeObjectExtension(object, extensionName) {
  11589. const extensions = object.extensions || {};
  11590. const extension = extensions[extensionName];
  11591. delete extensions[extensionName];
  11592. return extension;
  11593. }
  11594. addExtension(extensionName, extensionData = {}) {
  11595. assert$1(extensionData);
  11596. this.json.extensions = this.json.extensions || {};
  11597. this.json.extensions[extensionName] = extensionData;
  11598. this.registerUsedExtension(extensionName);
  11599. return extensionData;
  11600. }
  11601. addRequiredExtension(extensionName, extensionData = {}) {
  11602. assert$1(extensionData);
  11603. this.addExtension(extensionName, extensionData);
  11604. this.registerRequiredExtension(extensionName);
  11605. return extensionData;
  11606. }
  11607. registerUsedExtension(extensionName) {
  11608. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11609. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11610. this.json.extensionsUsed.push(extensionName);
  11611. }
  11612. }
  11613. registerRequiredExtension(extensionName) {
  11614. this.registerUsedExtension(extensionName);
  11615. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11616. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11617. this.json.extensionsRequired.push(extensionName);
  11618. }
  11619. }
  11620. removeExtension(extensionName) {
  11621. if (this.json.extensionsRequired) {
  11622. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11623. }
  11624. if (this.json.extensionsUsed) {
  11625. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11626. }
  11627. if (this.json.extensions) {
  11628. delete this.json.extensions[extensionName];
  11629. }
  11630. }
  11631. setDefaultScene(sceneIndex) {
  11632. this.json.scene = sceneIndex;
  11633. }
  11634. addScene(scene) {
  11635. const {
  11636. nodeIndices
  11637. } = scene;
  11638. this.json.scenes = this.json.scenes || [];
  11639. this.json.scenes.push({
  11640. nodes: nodeIndices
  11641. });
  11642. return this.json.scenes.length - 1;
  11643. }
  11644. addNode(node) {
  11645. const {
  11646. meshIndex,
  11647. matrix
  11648. } = node;
  11649. this.json.nodes = this.json.nodes || [];
  11650. const nodeData = {
  11651. mesh: meshIndex
  11652. };
  11653. if (matrix) {
  11654. nodeData.matrix = matrix;
  11655. }
  11656. this.json.nodes.push(nodeData);
  11657. return this.json.nodes.length - 1;
  11658. }
  11659. addMesh(mesh) {
  11660. const {
  11661. attributes,
  11662. indices,
  11663. material,
  11664. mode = 4
  11665. } = mesh;
  11666. const accessors = this._addAttributes(attributes);
  11667. const glTFMesh = {
  11668. primitives: [{
  11669. attributes: accessors,
  11670. mode
  11671. }]
  11672. };
  11673. if (indices) {
  11674. const indicesAccessor = this._addIndices(indices);
  11675. glTFMesh.primitives[0].indices = indicesAccessor;
  11676. }
  11677. if (Number.isFinite(material)) {
  11678. glTFMesh.primitives[0].material = material;
  11679. }
  11680. this.json.meshes = this.json.meshes || [];
  11681. this.json.meshes.push(glTFMesh);
  11682. return this.json.meshes.length - 1;
  11683. }
  11684. addPointCloud(attributes) {
  11685. const accessorIndices = this._addAttributes(attributes);
  11686. const glTFMesh = {
  11687. primitives: [{
  11688. attributes: accessorIndices,
  11689. mode: 0
  11690. }]
  11691. };
  11692. this.json.meshes = this.json.meshes || [];
  11693. this.json.meshes.push(glTFMesh);
  11694. return this.json.meshes.length - 1;
  11695. }
  11696. addImage(imageData, mimeTypeOpt) {
  11697. const metadata = getBinaryImageMetadata(imageData);
  11698. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11699. const bufferViewIndex = this.addBufferView(imageData);
  11700. const glTFImage = {
  11701. bufferView: bufferViewIndex,
  11702. mimeType
  11703. };
  11704. this.json.images = this.json.images || [];
  11705. this.json.images.push(glTFImage);
  11706. return this.json.images.length - 1;
  11707. }
  11708. addBufferView(buffer) {
  11709. const byteLength = buffer.byteLength;
  11710. assert$1(Number.isFinite(byteLength));
  11711. this.sourceBuffers = this.sourceBuffers || [];
  11712. this.sourceBuffers.push(buffer);
  11713. const glTFBufferView = {
  11714. buffer: 0,
  11715. byteOffset: this.byteLength,
  11716. byteLength
  11717. };
  11718. this.byteLength += padToNBytes(byteLength, 4);
  11719. this.json.bufferViews = this.json.bufferViews || [];
  11720. this.json.bufferViews.push(glTFBufferView);
  11721. return this.json.bufferViews.length - 1;
  11722. }
  11723. addAccessor(bufferViewIndex, accessor) {
  11724. const glTFAccessor = {
  11725. bufferView: bufferViewIndex,
  11726. type: getAccessorTypeFromSize(accessor.size),
  11727. componentType: accessor.componentType,
  11728. count: accessor.count,
  11729. max: accessor.max,
  11730. min: accessor.min
  11731. };
  11732. this.json.accessors = this.json.accessors || [];
  11733. this.json.accessors.push(glTFAccessor);
  11734. return this.json.accessors.length - 1;
  11735. }
  11736. addBinaryBuffer(sourceBuffer, accessor = {
  11737. size: 3
  11738. }) {
  11739. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11740. let minMax = {
  11741. min: accessor.min,
  11742. max: accessor.max
  11743. };
  11744. if (!minMax.min || !minMax.max) {
  11745. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11746. }
  11747. const accessorDefaults = {
  11748. size: accessor.size,
  11749. componentType: getComponentTypeFromArray(sourceBuffer),
  11750. count: Math.round(sourceBuffer.length / accessor.size),
  11751. min: minMax.min,
  11752. max: minMax.max
  11753. };
  11754. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11755. }
  11756. addTexture(texture) {
  11757. const {
  11758. imageIndex
  11759. } = texture;
  11760. const glTFTexture = {
  11761. source: imageIndex
  11762. };
  11763. this.json.textures = this.json.textures || [];
  11764. this.json.textures.push(glTFTexture);
  11765. return this.json.textures.length - 1;
  11766. }
  11767. addMaterial(pbrMaterialInfo) {
  11768. this.json.materials = this.json.materials || [];
  11769. this.json.materials.push(pbrMaterialInfo);
  11770. return this.json.materials.length - 1;
  11771. }
  11772. createBinaryChunk() {
  11773. var _this$json, _this$json$buffers;
  11774. this.gltf.buffers = [];
  11775. const totalByteLength = this.byteLength;
  11776. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11777. const targetArray = new Uint8Array(arrayBuffer);
  11778. let dstByteOffset = 0;
  11779. for (const sourceBuffer of this.sourceBuffers || []) {
  11780. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11781. }
  11782. 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]) {
  11783. this.json.buffers[0].byteLength = totalByteLength;
  11784. } else {
  11785. this.json.buffers = [{
  11786. byteLength: totalByteLength
  11787. }];
  11788. }
  11789. this.gltf.binary = arrayBuffer;
  11790. this.sourceBuffers = [arrayBuffer];
  11791. }
  11792. _removeStringFromArray(array, string) {
  11793. let found = true;
  11794. while (found) {
  11795. const index = array.indexOf(string);
  11796. if (index > -1) {
  11797. array.splice(index, 1);
  11798. } else {
  11799. found = false;
  11800. }
  11801. }
  11802. }
  11803. _addAttributes(attributes = {}) {
  11804. const result = {};
  11805. for (const attributeKey in attributes) {
  11806. const attributeData = attributes[attributeKey];
  11807. const attrName = this._getGltfAttributeName(attributeKey);
  11808. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11809. result[attrName] = accessor;
  11810. }
  11811. return result;
  11812. }
  11813. _addIndices(indices) {
  11814. return this.addBinaryBuffer(indices, {
  11815. size: 1
  11816. });
  11817. }
  11818. _getGltfAttributeName(attributeName) {
  11819. switch (attributeName.toLowerCase()) {
  11820. case 'position':
  11821. case 'positions':
  11822. case 'vertices':
  11823. return 'POSITION';
  11824. case 'normal':
  11825. case 'normals':
  11826. return 'NORMAL';
  11827. case 'color':
  11828. case 'colors':
  11829. return 'COLOR_0';
  11830. case 'texcoord':
  11831. case 'texcoords':
  11832. return 'TEXCOORD_0';
  11833. default:
  11834. return attributeName;
  11835. }
  11836. }
  11837. _getAccessorMinMax(buffer, size) {
  11838. const result = {
  11839. min: null,
  11840. max: null
  11841. };
  11842. if (buffer.length < size) {
  11843. return result;
  11844. }
  11845. result.min = [];
  11846. result.max = [];
  11847. const initValues = buffer.subarray(0, size);
  11848. for (const value of initValues) {
  11849. result.min.push(value);
  11850. result.max.push(value);
  11851. }
  11852. for (let index = size; index < buffer.length; index += size) {
  11853. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  11854. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  11855. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  11856. }
  11857. }
  11858. return result;
  11859. }
  11860. }
  11861. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  11862. 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';
  11863. 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';
  11864. 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]);
  11865. 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]);
  11866. const FILTERS = {
  11867. 0: '',
  11868. 1: 'meshopt_decodeFilterOct',
  11869. 2: 'meshopt_decodeFilterQuat',
  11870. 3: 'meshopt_decodeFilterExp',
  11871. NONE: '',
  11872. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  11873. QUATERNION: 'meshopt_decodeFilterQuat',
  11874. EXPONENTIAL: 'meshopt_decodeFilterExp'
  11875. };
  11876. const DECODERS = {
  11877. 0: 'meshopt_decodeVertexBuffer',
  11878. 1: 'meshopt_decodeIndexBuffer',
  11879. 2: 'meshopt_decodeIndexSequence',
  11880. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  11881. TRIANGLES: 'meshopt_decodeIndexBuffer',
  11882. INDICES: 'meshopt_decodeIndexSequence'
  11883. };
  11884. function isMeshoptSupported() {
  11885. return isWebAssemblySupported;
  11886. }
  11887. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  11888. const instance = await loadWasmInstance();
  11889. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  11890. }
  11891. let wasmPromise;
  11892. async function loadWasmInstance() {
  11893. if (!wasmPromise) {
  11894. wasmPromise = loadWasmModule();
  11895. }
  11896. return wasmPromise;
  11897. }
  11898. async function loadWasmModule() {
  11899. let wasm = wasm_base;
  11900. if (WebAssembly.validate(detector)) {
  11901. wasm = wasm_simd;
  11902. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  11903. }
  11904. const result = await WebAssembly.instantiate(unpack(wasm), {});
  11905. await result.instance.exports.__wasm_call_ctors();
  11906. return result.instance;
  11907. }
  11908. function unpack(data) {
  11909. const result = new Uint8Array(data.length);
  11910. for (let i = 0; i < data.length; ++i) {
  11911. const ch = data.charCodeAt(i);
  11912. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  11913. }
  11914. let write = 0;
  11915. for (let i = 0; i < data.length; ++i) {
  11916. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  11917. }
  11918. return result.buffer.slice(0, write);
  11919. }
  11920. function decode$5(instance, fun, target, count, size, source, filter) {
  11921. const sbrk = instance.exports.sbrk;
  11922. const count4 = count + 3 & ~3;
  11923. const tp = sbrk(count4 * size);
  11924. const sp = sbrk(source.length);
  11925. const heap = new Uint8Array(instance.exports.memory.buffer);
  11926. heap.set(source, sp);
  11927. const res = fun(tp, count, size, sp, source.length);
  11928. if (res === 0 && filter) {
  11929. filter(tp, count4, size);
  11930. }
  11931. target.set(heap.subarray(tp, tp + count * size));
  11932. sbrk(tp - sbrk(0));
  11933. if (res !== 0) {
  11934. throw new Error("Malformed buffer data: ".concat(res));
  11935. }
  11936. }
  11937. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  11938. const name$6 = EXT_MESHOPT_COMPRESSION;
  11939. function preprocess$4(gltfData) {
  11940. const scenegraph = new GLTFScenegraph(gltfData);
  11941. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  11942. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  11943. }
  11944. }
  11945. async function decode$4(gltfData, options) {
  11946. var _options$gltf;
  11947. const scenegraph = new GLTFScenegraph(gltfData);
  11948. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  11949. return;
  11950. }
  11951. const promises = [];
  11952. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  11953. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  11954. }
  11955. await Promise.all(promises);
  11956. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  11957. }
  11958. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  11959. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  11960. if (meshoptExtension) {
  11961. const buffer = bufferView.buffer;
  11962. const {
  11963. byteOffset = 0,
  11964. byteLength = 0,
  11965. byteStride,
  11966. count,
  11967. mode,
  11968. filter = 'NONE'
  11969. } = meshoptExtension;
  11970. const source = new Uint8Array(buffer, byteOffset, byteLength);
  11971. const result = new ArrayBuffer(count * byteStride);
  11972. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  11973. return result;
  11974. }
  11975. return null;
  11976. }
  11977. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  11978. __proto__: null,
  11979. name: name$6,
  11980. preprocess: preprocess$4,
  11981. decode: decode$4
  11982. });
  11983. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  11984. const name$5 = EXT_TEXTURE_WEBP;
  11985. function preprocess$3(gltfData, options) {
  11986. const scenegraph = new GLTFScenegraph(gltfData);
  11987. if (!_isImageFormatSupported('image/webp')) {
  11988. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  11989. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  11990. }
  11991. return;
  11992. }
  11993. const {
  11994. json
  11995. } = scenegraph;
  11996. for (const texture of json.textures || []) {
  11997. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  11998. if (extension) {
  11999. texture.source = extension.source;
  12000. }
  12001. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12002. }
  12003. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12004. }
  12005. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12006. __proto__: null,
  12007. name: name$5,
  12008. preprocess: preprocess$3
  12009. });
  12010. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12011. const name$4 = KHR_TEXTURE_BASISU;
  12012. function preprocess$2(gltfData, options) {
  12013. const scene = new GLTFScenegraph(gltfData);
  12014. const {
  12015. json
  12016. } = scene;
  12017. for (const texture of json.textures || []) {
  12018. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12019. if (extension) {
  12020. texture.source = extension.source;
  12021. }
  12022. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12023. }
  12024. scene.removeExtension(KHR_TEXTURE_BASISU);
  12025. }
  12026. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12027. __proto__: null,
  12028. name: name$4,
  12029. preprocess: preprocess$2
  12030. });
  12031. function getGLTFAccessors(attributes) {
  12032. const accessors = {};
  12033. for (const name in attributes) {
  12034. const attribute = attributes[name];
  12035. if (name !== 'indices') {
  12036. const glTFAccessor = getGLTFAccessor(attribute);
  12037. accessors[name] = glTFAccessor;
  12038. }
  12039. }
  12040. return accessors;
  12041. }
  12042. function getGLTFAccessor(attribute) {
  12043. const {
  12044. buffer,
  12045. size,
  12046. count
  12047. } = getAccessorData(attribute);
  12048. const glTFAccessor = {
  12049. value: buffer,
  12050. size,
  12051. byteOffset: 0,
  12052. count,
  12053. type: getAccessorTypeFromSize(size),
  12054. componentType: getComponentTypeFromArray(buffer)
  12055. };
  12056. return glTFAccessor;
  12057. }
  12058. function getAccessorData(attribute) {
  12059. let buffer = attribute;
  12060. let size = 1;
  12061. let count = 0;
  12062. if (attribute && attribute.value) {
  12063. buffer = attribute.value;
  12064. size = attribute.size || 1;
  12065. }
  12066. if (buffer) {
  12067. if (!ArrayBuffer.isView(buffer)) {
  12068. buffer = toTypedArray(buffer, Float32Array);
  12069. }
  12070. count = buffer.length / size;
  12071. }
  12072. return {
  12073. buffer,
  12074. size,
  12075. count
  12076. };
  12077. }
  12078. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12079. if (!array) {
  12080. return null;
  12081. }
  12082. if (Array.isArray(array)) {
  12083. return new ArrayType(array);
  12084. }
  12085. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12086. return new ArrayType(array);
  12087. }
  12088. return array;
  12089. }
  12090. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12091. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12092. function preprocess$1(gltfData, options, context) {
  12093. const scenegraph = new GLTFScenegraph(gltfData);
  12094. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12095. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12096. }
  12097. }
  12098. async function decode$3(gltfData, options, context) {
  12099. var _options$gltf;
  12100. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12101. return;
  12102. }
  12103. const scenegraph = new GLTFScenegraph(gltfData);
  12104. const promises = [];
  12105. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12106. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12107. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12108. }
  12109. }
  12110. await Promise.all(promises);
  12111. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12112. }
  12113. function encode$3(gltfData, options = {}) {
  12114. const scenegraph = new GLTFScenegraph(gltfData);
  12115. for (const mesh of scenegraph.json.meshes || []) {
  12116. compressMesh(mesh);
  12117. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12118. }
  12119. }
  12120. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12121. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12122. if (!dracoExtension) {
  12123. return;
  12124. }
  12125. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12126. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12127. const {
  12128. parse
  12129. } = context;
  12130. const dracoOptions = { ...options
  12131. };
  12132. delete dracoOptions['3d-tiles'];
  12133. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12134. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12135. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12136. if (attributeName in primitive.attributes) {
  12137. const accessorIndex = primitive.attributes[attributeName];
  12138. const accessor = scenegraph.getAccessor(accessorIndex);
  12139. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12140. decodedAttribute.min = accessor.min;
  12141. decodedAttribute.max = accessor.max;
  12142. }
  12143. }
  12144. }
  12145. primitive.attributes = decodedAttributes;
  12146. if (decodedData.indices) {
  12147. primitive.indices = getGLTFAccessor(decodedData.indices);
  12148. }
  12149. checkPrimitive(primitive);
  12150. }
  12151. function compressMesh(attributes, indices, mode = 4, options, context) {
  12152. var _context$parseSync;
  12153. if (!options.DracoWriter) {
  12154. throw new Error('options.gltf.DracoWriter not provided');
  12155. }
  12156. const compressedData = options.DracoWriter.encodeSync({
  12157. attributes
  12158. });
  12159. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12160. attributes
  12161. });
  12162. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12163. const bufferViewIndex = options.addBufferView(compressedData);
  12164. const glTFMesh = {
  12165. primitives: [{
  12166. attributes: fauxAccessors,
  12167. mode,
  12168. extensions: {
  12169. [KHR_DRACO_MESH_COMPRESSION]: {
  12170. bufferView: bufferViewIndex,
  12171. attributes: fauxAccessors
  12172. }
  12173. }
  12174. }]
  12175. };
  12176. return glTFMesh;
  12177. }
  12178. function checkPrimitive(primitive) {
  12179. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12180. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12181. }
  12182. }
  12183. function* makeMeshPrimitiveIterator(scenegraph) {
  12184. for (const mesh of scenegraph.json.meshes || []) {
  12185. for (const primitive of mesh.primitives) {
  12186. yield primitive;
  12187. }
  12188. }
  12189. }
  12190. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12191. __proto__: null,
  12192. name: name$3,
  12193. preprocess: preprocess$1,
  12194. decode: decode$3,
  12195. encode: encode$3
  12196. });
  12197. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12198. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12199. async function decode$2(gltfData) {
  12200. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12201. const {
  12202. json
  12203. } = gltfScenegraph;
  12204. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12205. if (extension) {
  12206. gltfScenegraph.json.lights = extension.lights;
  12207. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12208. }
  12209. for (const node of json.nodes || []) {
  12210. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12211. if (nodeExtension) {
  12212. node.light = nodeExtension.light;
  12213. }
  12214. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12215. }
  12216. }
  12217. async function encode$2(gltfData) {
  12218. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12219. const {
  12220. json
  12221. } = gltfScenegraph;
  12222. if (json.lights) {
  12223. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12224. assert$1(!extension.lights);
  12225. extension.lights = json.lights;
  12226. delete json.lights;
  12227. }
  12228. if (gltfScenegraph.json.lights) {
  12229. for (const light of gltfScenegraph.json.lights) {
  12230. const node = light.node;
  12231. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12232. }
  12233. delete gltfScenegraph.json.lights;
  12234. }
  12235. }
  12236. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12237. __proto__: null,
  12238. name: name$2,
  12239. decode: decode$2,
  12240. encode: encode$2
  12241. });
  12242. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12243. const name$1 = KHR_MATERIALS_UNLIT;
  12244. async function decode$1(gltfData) {
  12245. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12246. const {
  12247. json
  12248. } = gltfScenegraph;
  12249. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12250. for (const material of json.materials || []) {
  12251. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12252. if (extension) {
  12253. material.unlit = true;
  12254. }
  12255. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12256. }
  12257. }
  12258. function encode$1(gltfData) {
  12259. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12260. const {
  12261. json
  12262. } = gltfScenegraph;
  12263. if (gltfScenegraph.materials) {
  12264. for (const material of json.materials || []) {
  12265. if (material.unlit) {
  12266. delete material.unlit;
  12267. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12268. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12269. }
  12270. }
  12271. }
  12272. }
  12273. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12274. __proto__: null,
  12275. name: name$1,
  12276. decode: decode$1,
  12277. encode: encode$1
  12278. });
  12279. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12280. const name = KHR_TECHNIQUES_WEBGL;
  12281. async function decode(gltfData) {
  12282. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12283. const {
  12284. json
  12285. } = gltfScenegraph;
  12286. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12287. if (extension) {
  12288. const techniques = resolveTechniques(extension, gltfScenegraph);
  12289. for (const material of json.materials || []) {
  12290. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12291. if (materialExtension) {
  12292. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12293. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12294. }
  12295. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12296. }
  12297. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12298. }
  12299. }
  12300. async function encode(gltfData, options) {}
  12301. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12302. const {
  12303. programs = [],
  12304. shaders = [],
  12305. techniques = []
  12306. } = techniquesExtension;
  12307. const textDecoder = new TextDecoder();
  12308. shaders.forEach(shader => {
  12309. if (Number.isFinite(shader.bufferView)) {
  12310. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12311. } else {
  12312. throw new Error('KHR_techniques_webgl: no shader code');
  12313. }
  12314. });
  12315. programs.forEach(program => {
  12316. program.fragmentShader = shaders[program.fragmentShader];
  12317. program.vertexShader = shaders[program.vertexShader];
  12318. });
  12319. techniques.forEach(technique => {
  12320. technique.program = programs[technique.program];
  12321. });
  12322. return techniques;
  12323. }
  12324. function resolveValues(technique, gltfScenegraph) {
  12325. const values = Object.assign({}, technique.values);
  12326. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12327. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12328. values[uniform] = technique.uniforms[uniform].value;
  12329. }
  12330. });
  12331. Object.keys(values).forEach(uniform => {
  12332. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12333. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12334. }
  12335. });
  12336. return values;
  12337. }
  12338. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12339. __proto__: null,
  12340. name: name,
  12341. decode: decode,
  12342. encode: encode
  12343. });
  12344. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12345. function preprocessExtensions(gltf, options = {}, context) {
  12346. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12347. for (const extension of extensions) {
  12348. var _extension$preprocess;
  12349. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12350. }
  12351. }
  12352. async function decodeExtensions(gltf, options = {}, context) {
  12353. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12354. for (const extension of extensions) {
  12355. var _extension$decode;
  12356. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12357. }
  12358. }
  12359. function useExtension(extensionName, options) {
  12360. var _options$gltf;
  12361. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12362. const exclude = extensionName in excludes && !excludes[extensionName];
  12363. return !exclude;
  12364. }
  12365. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12366. function preprocess(gltfData) {
  12367. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12368. const {
  12369. json
  12370. } = gltfScenegraph;
  12371. for (const image of json.images || []) {
  12372. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12373. if (extension) {
  12374. Object.assign(image, extension);
  12375. }
  12376. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12377. }
  12378. if (json.buffers && json.buffers[0]) {
  12379. delete json.buffers[0].uri;
  12380. }
  12381. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12382. }
  12383. const GLTF_ARRAYS = {
  12384. accessors: 'accessor',
  12385. animations: 'animation',
  12386. buffers: 'buffer',
  12387. bufferViews: 'bufferView',
  12388. images: 'image',
  12389. materials: 'material',
  12390. meshes: 'mesh',
  12391. nodes: 'node',
  12392. samplers: 'sampler',
  12393. scenes: 'scene',
  12394. skins: 'skin',
  12395. textures: 'texture'
  12396. };
  12397. const GLTF_KEYS = {
  12398. accessor: 'accessors',
  12399. animations: 'animation',
  12400. buffer: 'buffers',
  12401. bufferView: 'bufferViews',
  12402. image: 'images',
  12403. material: 'materials',
  12404. mesh: 'meshes',
  12405. node: 'nodes',
  12406. sampler: 'samplers',
  12407. scene: 'scenes',
  12408. skin: 'skins',
  12409. texture: 'textures'
  12410. };
  12411. class GLTFV1Normalizer {
  12412. constructor() {
  12413. _defineProperty(this, "idToIndexMap", {
  12414. animations: {},
  12415. accessors: {},
  12416. buffers: {},
  12417. bufferViews: {},
  12418. images: {},
  12419. materials: {},
  12420. meshes: {},
  12421. nodes: {},
  12422. samplers: {},
  12423. scenes: {},
  12424. skins: {},
  12425. textures: {}
  12426. });
  12427. _defineProperty(this, "json", void 0);
  12428. }
  12429. normalize(gltf, options) {
  12430. this.json = gltf.json;
  12431. const json = gltf.json;
  12432. switch (json.asset && json.asset.version) {
  12433. case '2.0':
  12434. return;
  12435. case undefined:
  12436. case '1.0':
  12437. break;
  12438. default:
  12439. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12440. return;
  12441. }
  12442. if (!options.normalize) {
  12443. throw new Error('glTF v1 is not supported.');
  12444. }
  12445. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12446. this._addAsset(json);
  12447. this._convertTopLevelObjectsToArrays(json);
  12448. preprocess(gltf);
  12449. this._convertObjectIdsToArrayIndices(json);
  12450. this._updateObjects(json);
  12451. this._updateMaterial(json);
  12452. }
  12453. _addAsset(json) {
  12454. json.asset = json.asset || {};
  12455. json.asset.version = '2.0';
  12456. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12457. }
  12458. _convertTopLevelObjectsToArrays(json) {
  12459. for (const arrayName in GLTF_ARRAYS) {
  12460. this._convertTopLevelObjectToArray(json, arrayName);
  12461. }
  12462. }
  12463. _convertTopLevelObjectToArray(json, mapName) {
  12464. const objectMap = json[mapName];
  12465. if (!objectMap || Array.isArray(objectMap)) {
  12466. return;
  12467. }
  12468. json[mapName] = [];
  12469. for (const id in objectMap) {
  12470. const object = objectMap[id];
  12471. object.id = object.id || id;
  12472. const index = json[mapName].length;
  12473. json[mapName].push(object);
  12474. this.idToIndexMap[mapName][id] = index;
  12475. }
  12476. }
  12477. _convertObjectIdsToArrayIndices(json) {
  12478. for (const arrayName in GLTF_ARRAYS) {
  12479. this._convertIdsToIndices(json, arrayName);
  12480. }
  12481. if ('scene' in json) {
  12482. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12483. }
  12484. for (const texture of json.textures) {
  12485. this._convertTextureIds(texture);
  12486. }
  12487. for (const mesh of json.meshes) {
  12488. this._convertMeshIds(mesh);
  12489. }
  12490. for (const node of json.nodes) {
  12491. this._convertNodeIds(node);
  12492. }
  12493. for (const node of json.scenes) {
  12494. this._convertSceneIds(node);
  12495. }
  12496. }
  12497. _convertTextureIds(texture) {
  12498. if (texture.source) {
  12499. texture.source = this._convertIdToIndex(texture.source, 'image');
  12500. }
  12501. }
  12502. _convertMeshIds(mesh) {
  12503. for (const primitive of mesh.primitives) {
  12504. const {
  12505. attributes,
  12506. indices,
  12507. material
  12508. } = primitive;
  12509. for (const attributeName in attributes) {
  12510. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12511. }
  12512. if (indices) {
  12513. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12514. }
  12515. if (material) {
  12516. primitive.material = this._convertIdToIndex(material, 'material');
  12517. }
  12518. }
  12519. }
  12520. _convertNodeIds(node) {
  12521. if (node.children) {
  12522. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12523. }
  12524. if (node.meshes) {
  12525. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12526. }
  12527. }
  12528. _convertSceneIds(scene) {
  12529. if (scene.nodes) {
  12530. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12531. }
  12532. }
  12533. _convertIdsToIndices(json, topLevelArrayName) {
  12534. if (!json[topLevelArrayName]) {
  12535. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12536. json[topLevelArrayName] = [];
  12537. }
  12538. for (const object of json[topLevelArrayName]) {
  12539. for (const key in object) {
  12540. const id = object[key];
  12541. const index = this._convertIdToIndex(id, key);
  12542. object[key] = index;
  12543. }
  12544. }
  12545. }
  12546. _convertIdToIndex(id, key) {
  12547. const arrayName = GLTF_KEYS[key];
  12548. if (arrayName in this.idToIndexMap) {
  12549. const index = this.idToIndexMap[arrayName][id];
  12550. if (!Number.isFinite(index)) {
  12551. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12552. }
  12553. return index;
  12554. }
  12555. return id;
  12556. }
  12557. _updateObjects(json) {
  12558. for (const buffer of this.json.buffers) {
  12559. delete buffer.type;
  12560. }
  12561. }
  12562. _updateMaterial(json) {
  12563. for (const material of json.materials) {
  12564. material.pbrMetallicRoughness = {
  12565. baseColorFactor: [1, 1, 1, 1],
  12566. metallicFactor: 1,
  12567. roughnessFactor: 1
  12568. };
  12569. const textureId = material.values && material.values.tex;
  12570. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12571. if (textureIndex !== -1) {
  12572. material.pbrMetallicRoughness.baseColorTexture = {
  12573. index: textureIndex
  12574. };
  12575. }
  12576. }
  12577. }
  12578. }
  12579. function normalizeGLTFV1(gltf, options = {}) {
  12580. return new GLTFV1Normalizer().normalize(gltf, options);
  12581. }
  12582. const COMPONENTS = {
  12583. SCALAR: 1,
  12584. VEC2: 2,
  12585. VEC3: 3,
  12586. VEC4: 4,
  12587. MAT2: 4,
  12588. MAT3: 9,
  12589. MAT4: 16
  12590. };
  12591. const BYTES = {
  12592. 5120: 1,
  12593. 5121: 1,
  12594. 5122: 2,
  12595. 5123: 2,
  12596. 5125: 4,
  12597. 5126: 4
  12598. };
  12599. const GL_SAMPLER = {
  12600. TEXTURE_MAG_FILTER: 0x2800,
  12601. TEXTURE_MIN_FILTER: 0x2801,
  12602. TEXTURE_WRAP_S: 0x2802,
  12603. TEXTURE_WRAP_T: 0x2803,
  12604. REPEAT: 0x2901,
  12605. LINEAR: 0x2601,
  12606. NEAREST_MIPMAP_LINEAR: 0x2702
  12607. };
  12608. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12609. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12610. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12611. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12612. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12613. };
  12614. const DEFAULT_SAMPLER = {
  12615. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12616. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12617. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12618. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12619. };
  12620. function getBytesFromComponentType(componentType) {
  12621. return BYTES[componentType];
  12622. }
  12623. function getSizeFromAccessorType(type) {
  12624. return COMPONENTS[type];
  12625. }
  12626. class GLTFPostProcessor {
  12627. constructor() {
  12628. _defineProperty(this, "baseUri", '');
  12629. _defineProperty(this, "json", {});
  12630. _defineProperty(this, "buffers", []);
  12631. _defineProperty(this, "images", []);
  12632. }
  12633. postProcess(gltf, options = {}) {
  12634. const {
  12635. json,
  12636. buffers = [],
  12637. images = [],
  12638. baseUri = ''
  12639. } = gltf;
  12640. assert$1(json);
  12641. this.baseUri = baseUri;
  12642. this.json = json;
  12643. this.buffers = buffers;
  12644. this.images = images;
  12645. this._resolveTree(this.json, options);
  12646. return this.json;
  12647. }
  12648. _resolveTree(json, options = {}) {
  12649. if (json.bufferViews) {
  12650. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12651. }
  12652. if (json.images) {
  12653. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12654. }
  12655. if (json.samplers) {
  12656. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12657. }
  12658. if (json.textures) {
  12659. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12660. }
  12661. if (json.accessors) {
  12662. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12663. }
  12664. if (json.materials) {
  12665. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12666. }
  12667. if (json.meshes) {
  12668. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12669. }
  12670. if (json.nodes) {
  12671. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12672. }
  12673. if (json.skins) {
  12674. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12675. }
  12676. if (json.scenes) {
  12677. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12678. }
  12679. if (json.scene !== undefined) {
  12680. json.scene = json.scenes[this.json.scene];
  12681. }
  12682. }
  12683. getScene(index) {
  12684. return this._get('scenes', index);
  12685. }
  12686. getNode(index) {
  12687. return this._get('nodes', index);
  12688. }
  12689. getSkin(index) {
  12690. return this._get('skins', index);
  12691. }
  12692. getMesh(index) {
  12693. return this._get('meshes', index);
  12694. }
  12695. getMaterial(index) {
  12696. return this._get('materials', index);
  12697. }
  12698. getAccessor(index) {
  12699. return this._get('accessors', index);
  12700. }
  12701. getCamera(index) {
  12702. return null;
  12703. }
  12704. getTexture(index) {
  12705. return this._get('textures', index);
  12706. }
  12707. getSampler(index) {
  12708. return this._get('samplers', index);
  12709. }
  12710. getImage(index) {
  12711. return this._get('images', index);
  12712. }
  12713. getBufferView(index) {
  12714. return this._get('bufferViews', index);
  12715. }
  12716. getBuffer(index) {
  12717. return this._get('buffers', index);
  12718. }
  12719. _get(array, index) {
  12720. if (typeof index === 'object') {
  12721. return index;
  12722. }
  12723. const object = this.json[array] && this.json[array][index];
  12724. if (!object) {
  12725. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12726. }
  12727. return object;
  12728. }
  12729. _resolveScene(scene, index) {
  12730. scene.id = scene.id || "scene-".concat(index);
  12731. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12732. return scene;
  12733. }
  12734. _resolveNode(node, index) {
  12735. node.id = node.id || "node-".concat(index);
  12736. if (node.children) {
  12737. node.children = node.children.map(child => this.getNode(child));
  12738. }
  12739. if (node.mesh !== undefined) {
  12740. node.mesh = this.getMesh(node.mesh);
  12741. } else if (node.meshes !== undefined && node.meshes.length) {
  12742. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12743. const mesh = this.getMesh(meshIndex);
  12744. accum.id = mesh.id;
  12745. accum.primitives = accum.primitives.concat(mesh.primitives);
  12746. return accum;
  12747. }, {
  12748. primitives: []
  12749. });
  12750. }
  12751. if (node.camera !== undefined) {
  12752. node.camera = this.getCamera(node.camera);
  12753. }
  12754. if (node.skin !== undefined) {
  12755. node.skin = this.getSkin(node.skin);
  12756. }
  12757. return node;
  12758. }
  12759. _resolveSkin(skin, index) {
  12760. skin.id = skin.id || "skin-".concat(index);
  12761. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12762. return skin;
  12763. }
  12764. _resolveMesh(mesh, index) {
  12765. mesh.id = mesh.id || "mesh-".concat(index);
  12766. if (mesh.primitives) {
  12767. mesh.primitives = mesh.primitives.map(primitive => {
  12768. primitive = { ...primitive
  12769. };
  12770. const attributes = primitive.attributes;
  12771. primitive.attributes = {};
  12772. for (const attribute in attributes) {
  12773. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12774. }
  12775. if (primitive.indices !== undefined) {
  12776. primitive.indices = this.getAccessor(primitive.indices);
  12777. }
  12778. if (primitive.material !== undefined) {
  12779. primitive.material = this.getMaterial(primitive.material);
  12780. }
  12781. return primitive;
  12782. });
  12783. }
  12784. return mesh;
  12785. }
  12786. _resolveMaterial(material, index) {
  12787. material.id = material.id || "material-".concat(index);
  12788. if (material.normalTexture) {
  12789. material.normalTexture = { ...material.normalTexture
  12790. };
  12791. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12792. }
  12793. if (material.occlusionTexture) {
  12794. material.occlustionTexture = { ...material.occlustionTexture
  12795. };
  12796. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12797. }
  12798. if (material.emissiveTexture) {
  12799. material.emmisiveTexture = { ...material.emmisiveTexture
  12800. };
  12801. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12802. }
  12803. if (!material.emissiveFactor) {
  12804. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12805. }
  12806. if (material.pbrMetallicRoughness) {
  12807. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12808. };
  12809. const mr = material.pbrMetallicRoughness;
  12810. if (mr.baseColorTexture) {
  12811. mr.baseColorTexture = { ...mr.baseColorTexture
  12812. };
  12813. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12814. }
  12815. if (mr.metallicRoughnessTexture) {
  12816. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12817. };
  12818. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12819. }
  12820. }
  12821. return material;
  12822. }
  12823. _resolveAccessor(accessor, index) {
  12824. accessor.id = accessor.id || "accessor-".concat(index);
  12825. if (accessor.bufferView !== undefined) {
  12826. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12827. }
  12828. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12829. accessor.components = getSizeFromAccessorType(accessor.type);
  12830. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12831. if (accessor.bufferView) {
  12832. const buffer = accessor.bufferView.buffer;
  12833. const {
  12834. ArrayType,
  12835. byteLength
  12836. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12837. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12838. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12839. if (accessor.bufferView.byteStride) {
  12840. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12841. }
  12842. accessor.value = new ArrayType(cutBuffer);
  12843. }
  12844. return accessor;
  12845. }
  12846. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12847. const result = new Uint8Array(count * bytesPerElement);
  12848. for (let i = 0; i < count; i++) {
  12849. const elementOffset = byteOffset + i * byteStride;
  12850. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12851. }
  12852. return result.buffer;
  12853. }
  12854. _resolveTexture(texture, index) {
  12855. texture.id = texture.id || "texture-".concat(index);
  12856. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  12857. texture.source = this.getImage(texture.source);
  12858. return texture;
  12859. }
  12860. _resolveSampler(sampler, index) {
  12861. sampler.id = sampler.id || "sampler-".concat(index);
  12862. sampler.parameters = {};
  12863. for (const key in sampler) {
  12864. const glEnum = this._enumSamplerParameter(key);
  12865. if (glEnum !== undefined) {
  12866. sampler.parameters[glEnum] = sampler[key];
  12867. }
  12868. }
  12869. return sampler;
  12870. }
  12871. _enumSamplerParameter(key) {
  12872. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  12873. }
  12874. _resolveImage(image, index) {
  12875. image.id = image.id || "image-".concat(index);
  12876. if (image.bufferView !== undefined) {
  12877. image.bufferView = this.getBufferView(image.bufferView);
  12878. }
  12879. const preloadedImage = this.images[index];
  12880. if (preloadedImage) {
  12881. image.image = preloadedImage;
  12882. }
  12883. return image;
  12884. }
  12885. _resolveBufferView(bufferView, index) {
  12886. const bufferIndex = bufferView.buffer;
  12887. const result = {
  12888. id: "bufferView-".concat(index),
  12889. ...bufferView,
  12890. buffer: this.buffers[bufferIndex]
  12891. };
  12892. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  12893. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  12894. if ('byteOffset' in bufferView) {
  12895. byteOffset += bufferView.byteOffset;
  12896. }
  12897. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  12898. return result;
  12899. }
  12900. _resolveCamera(camera, index) {
  12901. camera.id = camera.id || "camera-".concat(index);
  12902. if (camera.perspective) ;
  12903. if (camera.orthographic) ;
  12904. return camera;
  12905. }
  12906. }
  12907. function postProcessGLTF(gltf, options) {
  12908. return new GLTFPostProcessor().postProcess(gltf, options);
  12909. }
  12910. const MAGIC_glTF = 0x676c5446;
  12911. const GLB_FILE_HEADER_SIZE = 12;
  12912. const GLB_CHUNK_HEADER_SIZE = 8;
  12913. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  12914. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  12915. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  12916. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  12917. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  12918. const LE = true;
  12919. function getMagicString(dataView, byteOffset = 0) {
  12920. 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)));
  12921. }
  12922. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  12923. const dataView = new DataView(arrayBuffer);
  12924. const {
  12925. magic = MAGIC_glTF
  12926. } = options;
  12927. const magic1 = dataView.getUint32(byteOffset, false);
  12928. return magic1 === magic || magic1 === MAGIC_glTF;
  12929. }
  12930. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  12931. const dataView = new DataView(arrayBuffer);
  12932. const type = getMagicString(dataView, byteOffset + 0);
  12933. const version = dataView.getUint32(byteOffset + 4, LE);
  12934. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  12935. Object.assign(glb, {
  12936. header: {
  12937. byteOffset,
  12938. byteLength,
  12939. hasBinChunk: false
  12940. },
  12941. type,
  12942. version,
  12943. json: {},
  12944. binChunks: []
  12945. });
  12946. byteOffset += GLB_FILE_HEADER_SIZE;
  12947. switch (glb.version) {
  12948. case 1:
  12949. return parseGLBV1(glb, dataView, byteOffset);
  12950. case 2:
  12951. return parseGLBV2(glb, dataView, byteOffset, options = {});
  12952. default:
  12953. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  12954. }
  12955. }
  12956. function parseGLBV1(glb, dataView, byteOffset) {
  12957. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  12958. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  12959. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  12960. byteOffset += GLB_CHUNK_HEADER_SIZE;
  12961. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  12962. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  12963. byteOffset += contentLength;
  12964. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  12965. return byteOffset;
  12966. }
  12967. function parseGLBV2(glb, dataView, byteOffset, options) {
  12968. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  12969. parseGLBChunksSync(glb, dataView, byteOffset, options);
  12970. return byteOffset + glb.header.byteLength;
  12971. }
  12972. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  12973. while (byteOffset + 8 <= glb.header.byteLength) {
  12974. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  12975. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  12976. byteOffset += GLB_CHUNK_HEADER_SIZE;
  12977. switch (chunkFormat) {
  12978. case GLB_CHUNK_TYPE_JSON:
  12979. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  12980. break;
  12981. case GLB_CHUNK_TYPE_BIN:
  12982. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  12983. break;
  12984. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  12985. if (!options.strict) {
  12986. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  12987. }
  12988. break;
  12989. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  12990. if (!options.strict) {
  12991. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  12992. }
  12993. break;
  12994. }
  12995. byteOffset += padToNBytes(chunkLength, 4);
  12996. }
  12997. return byteOffset;
  12998. }
  12999. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13000. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13001. const textDecoder = new TextDecoder('utf8');
  13002. const jsonText = textDecoder.decode(jsonChunk);
  13003. glb.json = JSON.parse(jsonText);
  13004. return padToNBytes(chunkLength, 4);
  13005. }
  13006. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13007. glb.header.hasBinChunk = true;
  13008. glb.binChunks.push({
  13009. byteOffset,
  13010. byteLength: chunkLength,
  13011. arrayBuffer: dataView.buffer
  13012. });
  13013. return padToNBytes(chunkLength, 4);
  13014. }
  13015. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13016. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13017. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13018. normalizeGLTFV1(gltf, {
  13019. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13020. });
  13021. preprocessExtensions(gltf, options, context);
  13022. const promises = [];
  13023. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13024. await loadBuffers(gltf, options, context);
  13025. }
  13026. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13027. const promise = loadImages(gltf, options, context);
  13028. promises.push(promise);
  13029. }
  13030. const promise = decodeExtensions(gltf, options, context);
  13031. promises.push(promise);
  13032. await Promise.all(promises);
  13033. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13034. }
  13035. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13036. if (options.uri) {
  13037. gltf.baseUri = options.uri;
  13038. }
  13039. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13040. const textDecoder = new TextDecoder();
  13041. data = textDecoder.decode(data);
  13042. }
  13043. if (typeof data === 'string') {
  13044. gltf.json = parseJSON(data);
  13045. } else if (data instanceof ArrayBuffer) {
  13046. const glb = {};
  13047. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13048. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13049. gltf._glb = glb;
  13050. gltf.json = glb.json;
  13051. } else {
  13052. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13053. }
  13054. const buffers = gltf.json.buffers || [];
  13055. gltf.buffers = new Array(buffers.length).fill(null);
  13056. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13057. const {
  13058. binChunks
  13059. } = gltf._glb;
  13060. gltf.buffers[0] = {
  13061. arrayBuffer: binChunks[0].arrayBuffer,
  13062. byteOffset: binChunks[0].byteOffset,
  13063. byteLength: binChunks[0].byteLength
  13064. };
  13065. }
  13066. const images = gltf.json.images || [];
  13067. gltf.images = new Array(images.length).fill({});
  13068. }
  13069. async function loadBuffers(gltf, options, context) {
  13070. const buffers = gltf.json.buffers || [];
  13071. for (let i = 0; i < buffers.length; ++i) {
  13072. const buffer = buffers[i];
  13073. if (buffer.uri) {
  13074. var _context$fetch, _response$arrayBuffer;
  13075. const {
  13076. fetch
  13077. } = context;
  13078. assert$1(fetch);
  13079. const uri = resolveUrl(buffer.uri, options);
  13080. 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));
  13081. 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));
  13082. gltf.buffers[i] = {
  13083. arrayBuffer,
  13084. byteOffset: 0,
  13085. byteLength: arrayBuffer.byteLength
  13086. };
  13087. delete buffer.uri;
  13088. }
  13089. }
  13090. }
  13091. async function loadImages(gltf, options, context) {
  13092. const imageIndices = getReferencesImageIndices(gltf);
  13093. const images = gltf.json.images || [];
  13094. const promises = [];
  13095. for (const imageIndex of imageIndices) {
  13096. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13097. }
  13098. return await Promise.all(promises);
  13099. }
  13100. function getReferencesImageIndices(gltf) {
  13101. const imageIndices = new Set();
  13102. const textures = gltf.json.textures || [];
  13103. for (const texture of textures) {
  13104. if (texture.source !== undefined) {
  13105. imageIndices.add(texture.source);
  13106. }
  13107. }
  13108. return Array.from(imageIndices).sort();
  13109. }
  13110. async function loadImage(gltf, image, index, options, context) {
  13111. const {
  13112. fetch,
  13113. parse
  13114. } = context;
  13115. let arrayBuffer;
  13116. if (image.uri) {
  13117. const uri = resolveUrl(image.uri, options);
  13118. const response = await fetch(uri);
  13119. arrayBuffer = await response.arrayBuffer();
  13120. }
  13121. if (Number.isFinite(image.bufferView)) {
  13122. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13123. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13124. }
  13125. assert$1(arrayBuffer, 'glTF image has no data');
  13126. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13127. mimeType: image.mimeType,
  13128. basis: options.basis || {
  13129. format: selectSupportedBasisFormat()
  13130. }
  13131. }, context);
  13132. if (parsedImage && parsedImage[0]) {
  13133. parsedImage = {
  13134. compressed: true,
  13135. mipmaps: false,
  13136. width: parsedImage[0].width,
  13137. height: parsedImage[0].height,
  13138. data: parsedImage
  13139. };
  13140. }
  13141. gltf.images = gltf.images || [];
  13142. gltf.images[index] = parsedImage;
  13143. }
  13144. const GLTFLoader = {
  13145. name: 'glTF',
  13146. id: 'gltf',
  13147. module: 'gltf',
  13148. version: VERSION$3,
  13149. extensions: ['gltf', 'glb'],
  13150. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13151. text: true,
  13152. binary: true,
  13153. tests: ['glTF'],
  13154. parse: parse$1,
  13155. options: {
  13156. gltf: {
  13157. normalize: true,
  13158. loadBuffers: true,
  13159. loadImages: true,
  13160. decompressMeshes: true,
  13161. postProcess: true
  13162. },
  13163. log: console
  13164. },
  13165. deprecatedOptions: {
  13166. fetchImages: 'gltf.loadImages',
  13167. createImages: 'gltf.loadImages',
  13168. decompress: 'gltf.decompressMeshes',
  13169. postProcess: 'gltf.postProcess',
  13170. gltf: {
  13171. decompress: 'gltf.decompressMeshes'
  13172. }
  13173. }
  13174. };
  13175. async function parse$1(arrayBuffer, options = {}, context) {
  13176. options = { ...GLTFLoader.options,
  13177. ...options
  13178. };
  13179. options.gltf = { ...GLTFLoader.options.gltf,
  13180. ...options.gltf
  13181. };
  13182. const {
  13183. byteOffset = 0
  13184. } = options;
  13185. const gltf = {};
  13186. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13187. }
  13188. const GLTF_FORMAT = {
  13189. URI: 0,
  13190. EMBEDDED: 1
  13191. };
  13192. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13193. tile.rotateYtoZ = true;
  13194. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13195. if (gltfByteLength === 0) {
  13196. throw new Error('glTF byte length must be greater than 0.');
  13197. }
  13198. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13199. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13200. tile.gltfByteOffset = 0;
  13201. tile.gltfByteLength = gltfByteLength;
  13202. if (byteOffset % 4 === 0) ; else {
  13203. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13204. }
  13205. return tile.byteOffset + tile.byteLength;
  13206. }
  13207. async function extractGLTF(tile, gltfFormat, options, context) {
  13208. const tile3DOptions = options['3d-tiles'] || {};
  13209. extractGLTFBufferOrURL(tile, gltfFormat);
  13210. if (tile3DOptions.loadGLTF) {
  13211. const {
  13212. parse,
  13213. fetch
  13214. } = context;
  13215. if (tile.gltfUrl) {
  13216. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13217. tile.gltfByteOffset = 0;
  13218. }
  13219. if (tile.gltfArrayBuffer) {
  13220. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13221. delete tile.gltfArrayBuffer;
  13222. delete tile.gltfByteOffset;
  13223. delete tile.gltfByteLength;
  13224. }
  13225. }
  13226. }
  13227. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13228. switch (gltfFormat) {
  13229. case GLTF_FORMAT.URI:
  13230. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13231. const textDecoder = new TextDecoder();
  13232. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13233. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13234. delete tile.gltfArrayBuffer;
  13235. delete tile.gltfByteOffset;
  13236. delete tile.gltfByteLength;
  13237. break;
  13238. case GLTF_FORMAT.EMBEDDED:
  13239. break;
  13240. default:
  13241. throw new Error('b3dm: Illegal glTF format field');
  13242. }
  13243. }
  13244. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13245. var _tile$gltf;
  13246. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13247. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13248. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13249. if (extensions && extensions.CESIUM_RTC) {
  13250. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13251. }
  13252. return byteOffset;
  13253. }
  13254. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13255. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13256. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13257. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13258. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13259. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13260. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13261. return byteOffset;
  13262. }
  13263. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13264. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13265. await extractGLTF(tile, tile.gltfFormat, options, context);
  13266. return byteOffset;
  13267. }
  13268. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13269. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13270. if (tile.version !== 1) {
  13271. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13272. }
  13273. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13274. const view = new DataView(arrayBuffer);
  13275. tile.gltfFormat = view.getUint32(byteOffset, true);
  13276. byteOffset += 4;
  13277. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13278. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13279. if (tile.featureTableJsonByteLength === 0) {
  13280. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13281. }
  13282. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13283. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13284. featureTable.featuresLength = instancesLength;
  13285. if (!Number.isFinite(instancesLength)) {
  13286. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13287. }
  13288. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13289. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13290. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13291. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13292. return byteOffset;
  13293. }
  13294. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13295. const collectionOptions = {
  13296. instances: new Array(instancesLength),
  13297. batchTable: tile._batchTable,
  13298. cull: false,
  13299. url: undefined,
  13300. gltf: undefined,
  13301. basePath: undefined,
  13302. incrementallyLoadTextures: false,
  13303. forwardAxis: [1, 0, 0]
  13304. };
  13305. const instances = collectionOptions.instances;
  13306. const instancePosition = new Vector3();
  13307. new Vector3();
  13308. new Vector3();
  13309. new Vector3();
  13310. const instanceRotation = new Matrix3();
  13311. const instanceQuaternion = new Quaternion();
  13312. const instanceScale = new Vector3();
  13313. const instanceTranslationRotationScale = {};
  13314. const instanceTransform = new Matrix4();
  13315. const scratch1 = [];
  13316. const scratch2 = [];
  13317. const scratchVector1 = new Vector3();
  13318. const scratchVector2 = new Vector3();
  13319. for (let i = 0; i < instancesLength; i++) {
  13320. let position;
  13321. if (featureTable.hasProperty('POSITION')) {
  13322. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13323. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13324. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13325. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13326. if (!quantizedVolumeOffset) {
  13327. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13328. }
  13329. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13330. if (!quantizedVolumeScale) {
  13331. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13332. }
  13333. const MAX_UNSIGNED_SHORT = 65535.0;
  13334. for (let j = 0; j < 3; j++) {
  13335. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13336. }
  13337. }
  13338. if (!position) {
  13339. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13340. }
  13341. instancePosition.copy(position);
  13342. instanceTranslationRotationScale.translation = instancePosition;
  13343. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13344. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13345. if (tile.normalUp) {
  13346. if (!tile.normalRight) {
  13347. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13348. }
  13349. tile.hasCustomOrientation = true;
  13350. } else {
  13351. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13352. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13353. if (tile.octNormalUp) {
  13354. if (!tile.octNormalRight) {
  13355. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13356. }
  13357. throw new Error('i3dm: oct-encoded orientation not implemented');
  13358. } else if (tile.eastNorthUp) {
  13359. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13360. instanceTransform.getRotationMatrix3(instanceRotation);
  13361. } else {
  13362. instanceRotation.identity();
  13363. }
  13364. }
  13365. instanceQuaternion.fromMatrix3(instanceRotation);
  13366. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13367. instanceScale.set(1.0, 1.0, 1.0);
  13368. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13369. if (Number.isFinite(scale)) {
  13370. instanceScale.multiplyByScalar(scale);
  13371. }
  13372. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13373. if (nonUniformScale) {
  13374. instanceScale.scale(nonUniformScale);
  13375. }
  13376. instanceTranslationRotationScale.scale = instanceScale;
  13377. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13378. if (batchId === undefined) {
  13379. batchId = i;
  13380. }
  13381. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13382. instanceTransform.identity();
  13383. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13384. instanceTransform.multiplyRight(rotationMatrix);
  13385. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13386. const modelMatrix = instanceTransform.clone();
  13387. instances[i] = {
  13388. modelMatrix,
  13389. batchId
  13390. };
  13391. }
  13392. tile.instances = instances;
  13393. }
  13394. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13395. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13396. const view = new DataView(arrayBuffer);
  13397. tile.tilesLength = view.getUint32(byteOffset, true);
  13398. byteOffset += 4;
  13399. tile.tiles = [];
  13400. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13401. const subtile = {};
  13402. tile.tiles.push(subtile);
  13403. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13404. }
  13405. return byteOffset;
  13406. }
  13407. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13408. tile.rotateYtoZ = true;
  13409. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13410. const {
  13411. parse
  13412. } = context;
  13413. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13414. }
  13415. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13416. tile.byteOffset = byteOffset;
  13417. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13418. switch (tile.type) {
  13419. case TILE3D_TYPE.COMPOSITE:
  13420. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13421. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13422. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13423. case TILE3D_TYPE.GLTF:
  13424. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13425. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13426. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13427. case TILE3D_TYPE.POINT_CLOUD:
  13428. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13429. default:
  13430. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13431. }
  13432. }
  13433. const SUBTREE_FILE_MAGIC = 0x74627573;
  13434. const SUBTREE_FILE_VERSION = 1;
  13435. async function parse3DTilesSubtree(data) {
  13436. const magic = new Uint32Array(data.slice(0, 4));
  13437. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13438. throw new Error('Wrong subtree file magic number');
  13439. }
  13440. const version = new Uint32Array(data.slice(4, 8));
  13441. if (version[0] !== SUBTREE_FILE_VERSION) {
  13442. throw new Error('Wrong subtree file verson, must be 1');
  13443. }
  13444. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13445. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13446. const textDecoder = new TextDecoder('utf8');
  13447. const string = textDecoder.decode(stringAttribute);
  13448. const subtree = JSON.parse(string);
  13449. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13450. let internalBinaryBuffer = new ArrayBuffer(0);
  13451. if (binaryByteLength) {
  13452. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13453. }
  13454. if ('bufferView' in subtree.tileAvailability) {
  13455. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13456. }
  13457. if ('bufferView' in subtree.contentAvailability) {
  13458. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13459. }
  13460. if ('bufferView' in subtree.childSubtreeAvailability) {
  13461. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13462. }
  13463. return subtree;
  13464. }
  13465. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13466. const bufferViewIndex = subtree[name].bufferView;
  13467. const bufferView = subtree.bufferViews[bufferViewIndex];
  13468. const buffer = subtree.buffers[bufferView.buffer];
  13469. if (buffer.uri) {
  13470. const response = await fetchFile(buffer.uri);
  13471. const data = await response.arrayBuffer();
  13472. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13473. }
  13474. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13475. }
  13476. function parseUint64Value(buffer) {
  13477. const dataView = new DataView(buffer);
  13478. const left = dataView.getUint32(0, true);
  13479. const right = dataView.getUint32(4, true);
  13480. return left + 2 ** 32 * right;
  13481. }
  13482. const Tile3DSubtreeLoader = {
  13483. id: '3d-tiles-subtree',
  13484. name: '3D Tiles Subtree',
  13485. module: '3d-tiles',
  13486. version: VERSION$5,
  13487. extensions: ['subtree'],
  13488. mimeTypes: ['application/octet-stream'],
  13489. tests: ['subtree'],
  13490. parse: parse3DTilesSubtree,
  13491. options: {}
  13492. };
  13493. const QUADTREE_DEVISION_COUNT = 4;
  13494. const OCTREE_DEVISION_COUNT = 8;
  13495. const SUBDIVISION_COUNT_MAP = {
  13496. QUADTREE: QUADTREE_DEVISION_COUNT,
  13497. OCTREE: OCTREE_DEVISION_COUNT
  13498. };
  13499. async function parseImplicitTiles(subtree, options, parentData = {
  13500. mortonIndex: 0,
  13501. x: 0,
  13502. y: 0,
  13503. z: 0
  13504. }, childIndex = 0, level = 0, globalData = {
  13505. level: 0,
  13506. mortonIndex: 0,
  13507. x: 0,
  13508. y: 0,
  13509. z: 0
  13510. }) {
  13511. const {
  13512. subdivisionScheme,
  13513. subtreeLevels,
  13514. maximumLevel,
  13515. contentUrlTemplate,
  13516. subtreesUriTemplate,
  13517. basePath
  13518. } = options;
  13519. const tile = {
  13520. children: [],
  13521. lodMetricValue: 0,
  13522. contentUrl: ''
  13523. };
  13524. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13525. const childX = childIndex & 0b01;
  13526. const childY = childIndex >> 1 & 0b01;
  13527. const childZ = childIndex >> 2 & 0b01;
  13528. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13529. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13530. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13531. let childTileX = concatBits(parentData.x, childX);
  13532. let childTileY = concatBits(parentData.y, childY);
  13533. let childTileZ = concatBits(parentData.z, childZ);
  13534. let isChildSubtreeAvailable = false;
  13535. if (level + 1 > subtreeLevels) {
  13536. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13537. }
  13538. const x = concatBits(globalData.x, childTileX);
  13539. const y = concatBits(globalData.y, childTileY);
  13540. const z = concatBits(globalData.z, childTileZ);
  13541. const lev = level + globalData.level;
  13542. if (isChildSubtreeAvailable) {
  13543. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13544. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13545. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13546. subtree = childSubtree;
  13547. globalData.mortonIndex = childTileMortonIndex;
  13548. globalData.x = childTileX;
  13549. globalData.y = childTileY;
  13550. globalData.z = childTileZ;
  13551. globalData.level = level;
  13552. childTileMortonIndex = 0;
  13553. tileAvailabilityIndex = 0;
  13554. childTileX = 0;
  13555. childTileY = 0;
  13556. childTileZ = 0;
  13557. level = 0;
  13558. }
  13559. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13560. if (!isTileAvailable || level > maximumLevel) {
  13561. return tile;
  13562. }
  13563. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13564. if (isContentAvailable) {
  13565. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13566. }
  13567. const childTileLevel = level + 1;
  13568. const pData = {
  13569. mortonIndex: childTileMortonIndex,
  13570. x: childTileX,
  13571. y: childTileY,
  13572. z: childTileZ
  13573. };
  13574. for (let index = 0; index < childrenPerTile; index++) {
  13575. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13576. if (currentTile.contentUrl || currentTile.children.length) {
  13577. const globalLevel = lev + 1;
  13578. const childCoordinates = {
  13579. childTileX,
  13580. childTileY,
  13581. childTileZ
  13582. };
  13583. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13584. tile.children.push(formattedTile);
  13585. }
  13586. }
  13587. return tile;
  13588. }
  13589. function getAvailabilityResult(availabilityData, index) {
  13590. if ('constant' in availabilityData) {
  13591. return Boolean(availabilityData.constant);
  13592. }
  13593. if (availabilityData.explicitBitstream) {
  13594. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13595. }
  13596. return false;
  13597. }
  13598. function formatTileData(tile, level, childCoordinates, options) {
  13599. const {
  13600. basePath,
  13601. refine,
  13602. getRefine,
  13603. lodMetricType,
  13604. getTileType,
  13605. rootLodMetricValue,
  13606. rootBoundingVolume
  13607. } = options;
  13608. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13609. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13610. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13611. return {
  13612. children: tile.children,
  13613. contentUrl: tile.contentUrl,
  13614. content: {
  13615. uri
  13616. },
  13617. id: tile.contentUrl,
  13618. refine: getRefine(refine),
  13619. type: getTileType(tile),
  13620. lodMetricType,
  13621. lodMetricValue,
  13622. boundingVolume
  13623. };
  13624. }
  13625. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13626. if (rootBoundingVolume.region) {
  13627. const {
  13628. childTileX,
  13629. childTileY,
  13630. childTileZ
  13631. } = childCoordinates;
  13632. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13633. const boundingVolumesCount = 2 ** level;
  13634. const sizeX = (east - west) / boundingVolumesCount;
  13635. const sizeY = (north - south) / boundingVolumesCount;
  13636. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13637. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13638. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13639. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13640. return {
  13641. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13642. };
  13643. }
  13644. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13645. return null;
  13646. }
  13647. function concatBits(first, second) {
  13648. return parseInt(first.toString(2) + second.toString(2), 2);
  13649. }
  13650. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13651. const mapUrl = generateMapUrl({
  13652. level,
  13653. x,
  13654. y,
  13655. z
  13656. });
  13657. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13658. }
  13659. function generateMapUrl(items) {
  13660. const mapUrl = {};
  13661. for (const key in items) {
  13662. mapUrl["{".concat(key, "}")] = items[key];
  13663. }
  13664. return mapUrl;
  13665. }
  13666. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13667. const byteIndex = Math.floor(availabilityIndex / 8);
  13668. const bitIndex = availabilityIndex % 8;
  13669. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13670. return bitValue === 1;
  13671. }
  13672. function getTileType(tile) {
  13673. if (!tile.contentUrl) {
  13674. return TILE_TYPE.EMPTY;
  13675. }
  13676. const contentUrl = tile.contentUrl;
  13677. const fileExtension = contentUrl.split('.').pop();
  13678. switch (fileExtension) {
  13679. case 'pnts':
  13680. return TILE_TYPE.POINTCLOUD;
  13681. case 'i3dm':
  13682. case 'b3dm':
  13683. case 'glb':
  13684. case 'gltf':
  13685. return TILE_TYPE.SCENEGRAPH;
  13686. default:
  13687. return fileExtension;
  13688. }
  13689. }
  13690. function getRefine(refine) {
  13691. switch (refine) {
  13692. case 'REPLACE':
  13693. case 'replace':
  13694. return TILE_REFINEMENT.REPLACE;
  13695. case 'ADD':
  13696. case 'add':
  13697. return TILE_REFINEMENT.ADD;
  13698. default:
  13699. return refine;
  13700. }
  13701. }
  13702. function normalizeTileData(tile, options) {
  13703. if (!tile) {
  13704. return null;
  13705. }
  13706. if (tile.content) {
  13707. const contentUri = tile.content.uri || tile.content.url;
  13708. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13709. }
  13710. tile.id = tile.contentUrl;
  13711. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13712. tile.lodMetricValue = tile.geometricError;
  13713. tile.transformMatrix = tile.transform;
  13714. tile.type = getTileType(tile);
  13715. tile.refine = getRefine(tile.refine);
  13716. return tile;
  13717. }
  13718. function normalizeTileHeaders(tileset) {
  13719. const basePath = tileset.basePath;
  13720. const root = normalizeTileData(tileset.root, tileset);
  13721. const stack = [];
  13722. stack.push(root);
  13723. while (stack.length > 0) {
  13724. const tile = stack.pop() || {};
  13725. const children = tile.children || [];
  13726. for (const childHeader of children) {
  13727. normalizeTileData(childHeader, {
  13728. basePath
  13729. });
  13730. stack.push(childHeader);
  13731. }
  13732. }
  13733. return root;
  13734. }
  13735. async function normalizeImplicitTileHeaders(tileset) {
  13736. if (!tileset.root) {
  13737. return null;
  13738. }
  13739. const basePath = tileset.basePath;
  13740. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13741. const {
  13742. subdivisionScheme,
  13743. maximumLevel,
  13744. subtreeLevels,
  13745. subtrees: {
  13746. uri: subtreesUriTemplate
  13747. }
  13748. } = implicitTilingExtension;
  13749. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13750. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13751. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13752. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13753. const refine = tileset.root.refine;
  13754. const rootLodMetricValue = tileset.root.geometricError;
  13755. const rootBoundingVolume = tileset.root.boundingVolume;
  13756. const options = {
  13757. contentUrlTemplate,
  13758. subtreesUriTemplate,
  13759. subdivisionScheme,
  13760. subtreeLevels,
  13761. maximumLevel,
  13762. refine,
  13763. basePath,
  13764. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13765. rootLodMetricValue,
  13766. rootBoundingVolume,
  13767. getTileType,
  13768. getRefine
  13769. };
  13770. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13771. }
  13772. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13773. if (!tile) {
  13774. return null;
  13775. }
  13776. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13777. tile.lodMetricValue = tile.geometricError;
  13778. tile.transformMatrix = tile.transform;
  13779. const {
  13780. children,
  13781. contentUrl
  13782. } = await parseImplicitTiles(rootSubtree, options);
  13783. if (contentUrl) {
  13784. tile.contentUrl = contentUrl;
  13785. tile.content = {
  13786. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13787. };
  13788. }
  13789. tile.refine = getRefine(tile.refine);
  13790. tile.type = getTileType(tile);
  13791. tile.children = children;
  13792. tile.id = tile.contentUrl;
  13793. return tile;
  13794. }
  13795. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13796. const Tiles3DLoader = {
  13797. id: '3d-tiles',
  13798. name: '3D Tiles',
  13799. module: '3d-tiles',
  13800. version: VERSION$5,
  13801. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13802. mimeTypes: ['application/octet-stream'],
  13803. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13804. parse,
  13805. options: {
  13806. '3d-tiles': {
  13807. loadGLTF: true,
  13808. decodeQuantizedPositions: false,
  13809. isTileset: 'auto',
  13810. assetGltfUpAxis: null
  13811. }
  13812. }
  13813. };
  13814. function getBaseUri(tileset) {
  13815. return dirname(tileset.url);
  13816. }
  13817. async function parseTile(arrayBuffer, options, context) {
  13818. const tile = {
  13819. content: {
  13820. featureIds: null
  13821. }
  13822. };
  13823. const byteOffset = 0;
  13824. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13825. return tile.content;
  13826. }
  13827. async function parseTileset(data, options, context) {
  13828. var _tilesetJson$root;
  13829. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13830. tilesetJson.loader = options.loader || Tiles3DLoader;
  13831. tilesetJson.url = context.url;
  13832. tilesetJson.basePath = getBaseUri(tilesetJson);
  13833. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13834. tilesetJson.type = TILESET_TYPE.TILES3D;
  13835. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13836. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13837. return tilesetJson;
  13838. }
  13839. async function parse(data, options, context) {
  13840. const loaderOptions = options['3d-tiles'] || {};
  13841. let isTileset;
  13842. if (loaderOptions.isTileset === 'auto') {
  13843. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13844. } else {
  13845. isTileset = loaderOptions.isTileset;
  13846. }
  13847. if (isTileset) {
  13848. data = await parseTileset(data, options, context);
  13849. } else {
  13850. data = await parseTile(data, options, context);
  13851. }
  13852. return data;
  13853. }
  13854. function hasImplicitTilingExtension(tilesetJson) {
  13855. var _tilesetJson$extensio, _tilesetJson$extensio2;
  13856. 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));
  13857. }
  13858. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  13859. async function getIonTilesetMetadata(accessToken, assetId) {
  13860. if (!assetId) {
  13861. const assets = await getIonAssets(accessToken);
  13862. for (const item of assets.items) {
  13863. if (item.type === '3DTILES') {
  13864. assetId = item.id;
  13865. }
  13866. }
  13867. }
  13868. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  13869. const {
  13870. type,
  13871. url
  13872. } = ionAssetMetadata;
  13873. assert$7(type === '3DTILES' && url);
  13874. ionAssetMetadata.headers = {
  13875. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  13876. };
  13877. return ionAssetMetadata;
  13878. }
  13879. async function getIonAssets(accessToken) {
  13880. assert$7(accessToken);
  13881. const url = CESIUM_ION_URL;
  13882. const headers = {
  13883. Authorization: "Bearer ".concat(accessToken)
  13884. };
  13885. const response = await fetchFile(url, {
  13886. fetch: {
  13887. headers
  13888. }
  13889. });
  13890. if (!response.ok) {
  13891. throw new Error(response.statusText);
  13892. }
  13893. return await response.json();
  13894. }
  13895. async function getIonAssetMetadata(accessToken, assetId) {
  13896. assert$7(accessToken, assetId);
  13897. const headers = {
  13898. Authorization: "Bearer ".concat(accessToken)
  13899. };
  13900. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  13901. let response = await fetchFile("".concat(url), {
  13902. fetch: {
  13903. headers
  13904. }
  13905. });
  13906. if (!response.ok) {
  13907. throw new Error(response.statusText);
  13908. }
  13909. let metadata = await response.json();
  13910. response = await fetchFile("".concat(url, "/endpoint"), {
  13911. fetch: {
  13912. headers
  13913. }
  13914. });
  13915. if (!response.ok) {
  13916. throw new Error(response.statusText);
  13917. }
  13918. const tilesetInfo = await response.json();
  13919. metadata = { ...metadata,
  13920. ...tilesetInfo
  13921. };
  13922. return metadata;
  13923. }
  13924. async function preload(url, options = {}) {
  13925. options = options['cesium-ion'] || {};
  13926. const {
  13927. accessToken
  13928. } = options;
  13929. let assetId = options.assetId;
  13930. if (!Number.isFinite(assetId)) {
  13931. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  13932. assetId = matched && matched[1];
  13933. }
  13934. return getIonTilesetMetadata(accessToken, assetId);
  13935. }
  13936. const CesiumIonLoader = { ...Tiles3DLoader,
  13937. id: 'cesium-ion',
  13938. name: 'Cesium Ion',
  13939. preload,
  13940. parse: async (data, options, context) => {
  13941. options = { ...options
  13942. };
  13943. options['3d-tiles'] = options['cesium-ion'];
  13944. options.loader = CesiumIonLoader;
  13945. return Tiles3DLoader.parse(data, options, context);
  13946. },
  13947. options: {
  13948. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  13949. accessToken: null
  13950. }
  13951. }
  13952. };
  13953. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  13954. function generateGradientTexture(gradient) {
  13955. const size = 64;
  13956. // create canvas
  13957. const canvas = document.createElement('canvas');
  13958. canvas.width = size;
  13959. canvas.height = size;
  13960. // get context
  13961. const context = canvas.getContext('2d');
  13962. // draw gradient
  13963. context.rect(0, 0, size, size);
  13964. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  13965. for (let i = 0; i < gradient.length; i++) {
  13966. const step = gradient[i];
  13967. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  13968. }
  13969. context.fillStyle = ctxGradient;
  13970. context.fill();
  13971. //let texture = new THREE.Texture(canvas);
  13972. const texture = new CanvasTexture(canvas);
  13973. texture.needsUpdate = true;
  13974. texture.minFilter = LinearFilter;
  13975. texture.wrapS = RepeatWrapping;
  13976. texture.wrapT = RepeatWrapping;
  13977. texture.repeat.set(2, 2);
  13978. // textureImage = texture.image;
  13979. return texture;
  13980. }
  13981. function getCameraFrustum(camera) {
  13982. camera.updateMatrix(); // make sure camera's local matrix is updated
  13983. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  13984. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13985. const frustum = new Frustum();
  13986. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  13987. return frustum;
  13988. }
  13989. function loadersPlaneToMesh(plane) {
  13990. const group = new Group();
  13991. // Create a basic rectangle geometry from math.gl plane
  13992. const planeGeometry = new PlaneGeometry(10, 5);
  13993. // Align the geometry to the plane
  13994. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  13995. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  13996. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  13997. planeGeometry.lookAt(focalPoint);
  13998. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  13999. // Edges
  14000. /*
  14001. const edges = new EdgesGeometry(planeGeometry)
  14002. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14003. //plane
  14004. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14005. const mesh = new Mesh(planeGeometry, material);
  14006. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14007. group.add(arrowHelper);
  14008. group.add(mesh);
  14009. return group;
  14010. }
  14011. function loadersBoundingBoxToMesh(tile) {
  14012. // Create a basic rectangle geometry from math.gl half-axes
  14013. const { boundingVolume } = tile;
  14014. let redColor = 0;
  14015. if (tile.content) {
  14016. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14017. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14018. }
  14019. const boxColor = new Color(redColor, 1.0, 0.0);
  14020. const boxGeometry = new BoxGeometry(1, 1, 1);
  14021. const boxTransform = new Matrix4$1();
  14022. if (boundingVolume.halfAxes) {
  14023. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  14024. }
  14025. else if (boundingVolume.radius) {
  14026. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  14027. }
  14028. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundingVolume.center)) //add
  14029. boxGeometry.applyMatrix4(boxTransform);
  14030. const edges = new EdgesGeometry(boxGeometry);
  14031. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14032. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14033. dispPlane.matrixAutoUpdate = false //add
  14034. /* if(tile.content.byteLength == void 0){
  14035. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14036. dispPlane.updateMatrixWorld = (a,b)=>{
  14037. oldUpdate(a,b)
  14038. }
  14039. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14040. dispPlane.updateMatrix = (a,b)=>{
  14041. oldU(a,b)
  14042. }
  14043. } */
  14044. return dispPlane;
  14045. }
  14046. function getMatrix4FromHalfAxes(halfAxes) {
  14047. const m = halfAxes;
  14048. const rotateMatrix = new Matrix4$1().fromArray([
  14049. m[0] * 2,
  14050. m[1] * 2,
  14051. m[2] * 2,
  14052. 0,
  14053. m[3] * 2,
  14054. m[4] * 2,
  14055. m[5] * 2,
  14056. 0,
  14057. m[6] * 2,
  14058. m[7] * 2,
  14059. m[8] * 2,
  14060. 0,
  14061. 0,
  14062. 0,
  14063. 0,
  14064. 1,
  14065. ]);
  14066. return rotateMatrix;
  14067. }
  14068. /*
  14069. * from https://github.com/tentone/geo-three
  14070. * Tree-shaking did not work, probably due to static class methods
  14071. */
  14072. function datumsToSpherical(latitude, longitude) {
  14073. const EARTH_RADIUS = 6378137;
  14074. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14075. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14076. const x = longitude * EARTH_ORIGIN / 180.0;
  14077. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14078. y = y * EARTH_ORIGIN / 180.0;
  14079. return new Vector2$1(x, y);
  14080. }
  14081. const Gradients = {
  14082. // From chroma spectral http://gka.github.io/chroma.js/
  14083. SPECTRAL: [
  14084. [0, new Color(0.3686, 0.3098, 0.6353)],
  14085. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14086. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14087. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14088. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14089. [0.5, new Color(1.0, 1.0, 0.749)],
  14090. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14091. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14092. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14093. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14094. [1, new Color(0.6196, 0.0039, 0.2588)],
  14095. ],
  14096. PLASMA: [
  14097. [0.0, new Color(0.241, 0.015, 0.61)],
  14098. [0.1, new Color(0.387, 0.001, 0.654)],
  14099. [0.2, new Color(0.524, 0.025, 0.653)],
  14100. [0.3, new Color(0.651, 0.125, 0.596)],
  14101. [0.4, new Color(0.752, 0.227, 0.513)],
  14102. [0.5, new Color(0.837, 0.329, 0.431)],
  14103. [0.6, new Color(0.907, 0.435, 0.353)],
  14104. [0.7, new Color(0.963, 0.554, 0.272)],
  14105. [0.8, new Color(0.992, 0.681, 0.195)],
  14106. [0.9, new Color(0.987, 0.822, 0.144)],
  14107. [1.0, new Color(0.94, 0.975, 0.131)],
  14108. ],
  14109. YELLOW_GREEN: [
  14110. [0, new Color(0.1647, 0.2824, 0.3451)],
  14111. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14112. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14113. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14114. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14115. [0.5, new Color(0.137, 0.665, 0.5614)],
  14116. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14117. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14118. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14119. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14120. [1, new Color(0.9804, 0.9804, 0.4314)],
  14121. ],
  14122. VIRIDIS: [
  14123. [0.0, new Color(0.267, 0.005, 0.329)],
  14124. [0.1, new Color(0.283, 0.141, 0.458)],
  14125. [0.2, new Color(0.254, 0.265, 0.53)],
  14126. [0.3, new Color(0.207, 0.372, 0.553)],
  14127. [0.4, new Color(0.164, 0.471, 0.558)],
  14128. [0.5, new Color(0.128, 0.567, 0.551)],
  14129. [0.6, new Color(0.135, 0.659, 0.518)],
  14130. [0.7, new Color(0.267, 0.749, 0.441)],
  14131. [0.8, new Color(0.478, 0.821, 0.318)],
  14132. [0.9, new Color(0.741, 0.873, 0.15)],
  14133. [1.0, new Color(0.993, 0.906, 0.144)],
  14134. ],
  14135. INFERNO: [
  14136. [0.0, new Color(0.077, 0.042, 0.206)],
  14137. [0.1, new Color(0.225, 0.036, 0.388)],
  14138. [0.2, new Color(0.373, 0.074, 0.432)],
  14139. [0.3, new Color(0.522, 0.128, 0.42)],
  14140. [0.4, new Color(0.665, 0.182, 0.37)],
  14141. [0.5, new Color(0.797, 0.255, 0.287)],
  14142. [0.6, new Color(0.902, 0.364, 0.184)],
  14143. [0.7, new Color(0.969, 0.516, 0.063)],
  14144. [0.8, new Color(0.988, 0.683, 0.072)],
  14145. [0.9, new Color(0.961, 0.859, 0.298)],
  14146. [1.0, new Color(0.988, 0.998, 0.645)],
  14147. ],
  14148. GRAYSCALE: [
  14149. [0, new Color(0, 0, 0)],
  14150. [1, new Color(1, 1, 1)],
  14151. ],
  14152. // 16 samples of the TURBU color scheme
  14153. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14154. // original file licensed under Apache-2.0
  14155. TURBO: [
  14156. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14157. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14158. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14159. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14160. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14161. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14162. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14163. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14164. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14165. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14166. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14167. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14168. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14169. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14170. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14171. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14172. ],
  14173. RAINBOW: [
  14174. [0, new Color(0.278, 0, 0.714)],
  14175. [1 / 6, new Color(0, 0, 1)],
  14176. [2 / 6, new Color(0, 1, 1)],
  14177. [3 / 6, new Color(0, 1, 0)],
  14178. [4 / 6, new Color(1, 1, 0)],
  14179. [5 / 6, new Color(1, 0.64, 0)],
  14180. [1, new Color(1, 0, 0)],
  14181. ],
  14182. CONTOUR: [
  14183. [0.0, new Color(0, 0, 0)],
  14184. [0.03, new Color(0, 0, 0)],
  14185. [0.04, new Color(1, 1, 1)],
  14186. [1.0, new Color(1, 1, 1)],
  14187. ],
  14188. };
  14189. const PointCloudFS = `
  14190. varying vec3 vColor;
  14191. uniform float alpha;
  14192. void main() {
  14193. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14194. discard;
  14195. } else {
  14196. gl_FragColor = vec4( vColor, alpha);
  14197. }
  14198. }
  14199. `;
  14200. const PointCloudVS = `
  14201. varying vec3 vColor;
  14202. uniform sampler2D gradient;
  14203. uniform sampler2D grayscale;
  14204. attribute float intensity;
  14205. attribute float classification;
  14206. uniform vec3 rootCenter;
  14207. uniform vec3 rootNormal;
  14208. uniform vec2 elevationRange;
  14209. uniform int coloring;
  14210. uniform bool hideGround;
  14211. uniform float maxIntensity;
  14212. uniform float intensityContrast;
  14213. uniform float pointSize;
  14214. #ifdef USE_COLOR
  14215. vec3 getRGB() {
  14216. vec3 rgb = color;
  14217. return rgb;
  14218. }
  14219. #endif
  14220. vec3 getElevation(){
  14221. vec4 world = modelMatrix * vec4( position, 1.0 );
  14222. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14223. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14224. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14225. return cElevation;
  14226. }
  14227. vec3 getIntensity(){
  14228. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14229. float intmod = pow(intensity, intensityContrast);
  14230. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14231. return cIntensity;
  14232. }
  14233. vec3 getClassification(){
  14234. float classNormalized = classification / 255.0;
  14235. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14236. return cClassification;
  14237. }
  14238. vec3 getColor(){
  14239. vec3 color;
  14240. if (hideGround && classification == 2.0) {
  14241. return vec3(0.0, 0.0, 0.0);
  14242. }
  14243. if (coloring == 1) {
  14244. color = getIntensity();
  14245. }
  14246. else if (coloring == 2) {
  14247. color = getClassification();
  14248. } else if (coloring == 3) {
  14249. color = getElevation();
  14250. }
  14251. #ifdef USE_COLOR
  14252. else if (coloring == 4) {
  14253. color = getRGB();
  14254. }
  14255. #endif
  14256. else {
  14257. color = vec3(1.0, 1.0, 1.0);
  14258. }
  14259. return color;
  14260. }
  14261. void main() {
  14262. vColor = getColor();
  14263. gl_PointSize = pointSize;
  14264. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14265. }
  14266. `;
  14267. /** Types of coloring used when viewing point cloud tiles */
  14268. var PointCloudColoring;
  14269. (function (PointCloudColoring) {
  14270. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14271. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14272. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14273. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14274. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14275. })(PointCloudColoring || (PointCloudColoring = {}));
  14276. /** Types of shading used when viewing b3dm (mesh) tiles */
  14277. var Shading;
  14278. (function (Shading) {
  14279. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14280. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14281. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14282. })(Shading || (Shading = {}));
  14283. var GeoTransform;
  14284. (function (GeoTransform) {
  14285. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14286. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14287. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14288. })(GeoTransform || (GeoTransform = {}));
  14289. const gradient = Gradients.RAINBOW;
  14290. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14291. const grayscale = Gradients.GRAYSCALE;
  14292. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14293. const defaultOptions = {
  14294. throttleRequests: true,
  14295. maxRequests: 64,
  14296. updateInterval: 0.1,
  14297. maxConcurrency: 1,
  14298. maximumScreenSpaceError: 16,
  14299. maximumMemoryUsage: 32,
  14300. viewDistanceScale: 1.0,
  14301. skipLevelOfDetail: false,
  14302. updateTransforms: true,
  14303. shading: Shading.FlatTexture,
  14304. transparent: false,
  14305. pointCloudColoring: PointCloudColoring.White,
  14306. pointSize: 1.0,
  14307. worker: true,
  14308. wireframe: false,
  14309. debug: false,
  14310. basisTranscoderPath: null,
  14311. dracoDecoderPath: null,
  14312. material: null,
  14313. computeNormals: false,
  14314. shaderCallback: null,
  14315. geoTransform: GeoTransform.Reset,
  14316. preloadTilesCount: null
  14317. };
  14318. /** 3D Tiles Loader */
  14319. class Loader3DTiles {
  14320. /**
  14321. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14322. * @public
  14323. *
  14324. * @param props - Properties for this load call {@link LoaderProps}.
  14325. * @returns An object containing the 3D Model to be added to the scene
  14326. * and a runtime engine to be updated every frame.
  14327. */
  14328. static load(props) {
  14329. return __awaiter(this, void 0, void 0, function* () {
  14330. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14331. const { url } = props;
  14332. const UPDATE_INTERVAL = options.updateInterval;
  14333. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14334. const loadersGLOptions = {};
  14335. if (options.cesiumIONToken) {
  14336. loadersGLOptions['cesium-ion'] = {
  14337. accessToken: options.cesiumIONToken,
  14338. };
  14339. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14340. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14341. }
  14342. if (props.loadingManager) {
  14343. props.loadingManager.itemStart(url);
  14344. }
  14345. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14346. const renderMap = {};
  14347. const boxMap = {};
  14348. const unloadQueue = [];
  14349. const root = new Group();
  14350. const tileBoxes = new Group();
  14351. tileBoxes.matrixAutoUpdate = false//add
  14352. if (!options.debug) {
  14353. tileBoxes.visible = false;
  14354. }else{
  14355. options.parent.add(tileBoxes) //add
  14356. }
  14357. const pointcloudUniforms = {
  14358. pointSize: { type: 'f', value: options.pointSize },
  14359. gradient: { type: 't', value: gradientTexture },
  14360. grayscale: { type: 't', value: grayscaleTexture },
  14361. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14362. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14363. coloring: { type: 'i', value: options.pointCloudColoring },
  14364. hideGround: { type: 'b', value: true },
  14365. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14366. maxIntensity: { type: 'f', value: 1.0 },
  14367. intensityContrast: { type: 'f', value: 1.0 },
  14368. alpha: { type: 'f', value: 1.0 },
  14369. };
  14370. const pointcloudMaterial = new ShaderMaterial({
  14371. uniforms: pointcloudUniforms,
  14372. vertexShader: PointCloudVS,
  14373. fragmentShader: PointCloudFS,
  14374. transparent: options.transparent,
  14375. vertexColors: true
  14376. });
  14377. let cameraReference = null;
  14378. let rendererReference = null;
  14379. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14380. let ktx2Loader = undefined;
  14381. let dracoLoader = undefined;
  14382. if (options.basisTranscoderPath) {
  14383. ktx2Loader = new KTX2Loader();
  14384. ktx2Loader.detectSupport(props.renderer);
  14385. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14386. ktx2Loader.setWorkerLimit(1);
  14387. gltfLoader.setKTX2Loader(ktx2Loader);
  14388. }
  14389. if (options.dracoDecoderPath) {
  14390. dracoLoader = new DRACOLoader();
  14391. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14392. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14393. gltfLoader.setDRACOLoader(dracoLoader);
  14394. }
  14395. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14396. const tileOptions = {
  14397. maximumMemoryUsage: options.maximumMemoryUsage,
  14398. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14399. viewDistanceScale: options.viewDistanceScale,
  14400. skipLevelOfDetail: options.skipLevelOfDetail,
  14401. updateTransforms: options.updateTransforms,
  14402. throttleRequests: options.throttleRequests,
  14403. maxRequests: options.maxRequests,
  14404. maxDepth: options.maxDepth || 50, // !zeg改
  14405. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14406. let tileContent = null;
  14407. switch (tile.type) {
  14408. case TILE_TYPE.POINTCLOUD: {
  14409. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14410. break;
  14411. }
  14412. case TILE_TYPE.SCENEGRAPH:
  14413. case TILE_TYPE.MESH: {
  14414. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14415. break;
  14416. }
  14417. }
  14418. if (tileContent) {
  14419. tileContent.visible = false;
  14420. renderMap[tile.id] = tileContent;
  14421. root.add(renderMap[tile.id]);
  14422. if (options.debug) {
  14423. const box = loadersBoundingBoxToMesh(tile);
  14424. tileBoxes.add(box);
  14425. boxMap[tile.id] = box;
  14426. }
  14427. //xzw :
  14428. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14429. }
  14430. }),
  14431. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14432. if (tileset) {
  14433. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14434. detectOrientation(tile);
  14435. }
  14436. tileset._frameNumber++;
  14437. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14438. }
  14439. }),
  14440. onTileUnload: (tile) => {
  14441. unloadQueue.push(tile);
  14442. },
  14443. onTileError: (tile, message) => {
  14444. console.error('Tile error', tile.id, message);
  14445. },
  14446. };
  14447. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14448. loadImages: false,
  14449. }, '3d-tiles': {
  14450. loadGLTF: false
  14451. } }) }));
  14452. //
  14453. // transformations
  14454. const threeMat = new Matrix4$1();
  14455. const tileTrasnform = new Matrix4$1();
  14456. const rootCenter = new Vector3$1();
  14457. let orientationDetected = false;
  14458. if (tileset.root.boundingVolume) {
  14459. if (tileset.root.header.boundingVolume.region) {
  14460. // TODO: Handle region type bounding volumes
  14461. // https://github.com/visgl/loaders.gl/issues/1994
  14462. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14463. options.geoTransform = GeoTransform.WGS84Cartesian;
  14464. }
  14465. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14466. }
  14467. else {
  14468. console.warn("Bounding volume not found, no transformations applied");
  14469. }
  14470. if (options.debug) {
  14471. const box = loadersBoundingBoxToMesh(tileset.root);
  14472. tileBoxes.add(box);
  14473. boxMap[tileset.root.id] = box;
  14474. }
  14475. let disposeFlag = false;
  14476. let loadingEnded = false;
  14477. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14478. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14479. // Extra stats
  14480. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14481. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14482. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14483. let timer = 0;
  14484. let lastCameraTransform = null;
  14485. let lastCameraAspect = null;
  14486. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14487. let sseDenominator = null;
  14488. root.updateMatrixWorld(true);
  14489. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14490. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14491. detectOrientation(tileset.root);
  14492. updateResetTransform();
  14493. if (options.debug) {
  14494. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14495. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14496. }
  14497. if (options.geoTransform == GeoTransform.Mercator) {
  14498. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14499. rootCenter.set(coords.x, 0, -coords.y);
  14500. root.position.copy(rootCenter);
  14501. root.rotation.set(-Math.PI / 2, 0, 0);
  14502. root.updateMatrixWorld(true);
  14503. }
  14504. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14505. root.applyMatrix4(tileTrasnform);
  14506. root.updateMatrixWorld(true);
  14507. rootCenter.copy(root.position);
  14508. }
  14509. function detectOrientation(tile) {
  14510. if (!tile.boundingVolume.halfAxes) {
  14511. return;
  14512. }
  14513. const halfAxes = tile.boundingVolume.halfAxes;
  14514. const orientationMatrix = new Matrix4$1()
  14515. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14516. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14517. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14518. if (!rotation.equals(new Euler())) {
  14519. orientationDetected = true;
  14520. const pos = new Vector3$1(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  14521. tileTrasnform.extractRotation(orientationMatrix);
  14522. tileTrasnform.setPosition(pos);
  14523. updateResetTransform();
  14524. }
  14525. }
  14526. function updateResetTransform() {
  14527. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14528. // Reset the current model matrix and apply our own transformation
  14529. threeMat.copy(tileTrasnform).invert();
  14530. threeMat.premultiply(lastRootTransform);
  14531. threeMat.copy(lastRootTransform).multiply(new Matrix4$1().copy(tileTrasnform).invert());
  14532. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14533. }
  14534. }
  14535. // 更新瓦片显隐和瓦片迭代更新
  14536. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14537. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14538. return
  14539. }
  14540. // Assumes camera fov, near and far are not changing
  14541. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14542. const loadersFrustum = new PerspectiveFrustum({
  14543. fov: (camera.fov / 180) * Math.PI,
  14544. aspectRatio: camera.aspect,
  14545. near: camera.near,
  14546. far: camera.far,
  14547. });
  14548. sseDenominator = loadersFrustum.sseDenominator;
  14549. lastCameraAspect = camera.aspect;
  14550. if (options.debug) {
  14551. console.log('Updated sse denonimator:', sseDenominator);
  14552. }
  14553. }
  14554. const frustum = getCameraFrustum(camera);
  14555. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14556. const cullingVolume = new CullingVolume(planes);
  14557. const rendererSize = new Vector2$1();
  14558. renderer.getSize(rendererSize);
  14559. const frameState = {
  14560. camera: {
  14561. position: lastCameraPosition.toArray(),
  14562. },
  14563. height: rendererSize.y,
  14564. frameNumber: tileset._frameNumber,
  14565. sseDenominator: sseDenominator,
  14566. cullingVolume: cullingVolume,
  14567. viewport: {
  14568. id: 0,
  14569. },
  14570. };
  14571. tileset._cache.reset();
  14572. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14573. for (const tile of tileset.tiles) {
  14574. if (tile.selected) {
  14575. if (!renderMap[tile.id]) {
  14576. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14577. }
  14578. else {
  14579. // Make sure it's visible
  14580. if(!renderMap[tile.id].visible){
  14581. if(visiVertexCount<maxVertexVisi){
  14582. renderMap[tile.id].visible = true;
  14583. visiVertexCount += renderMap[tile.id].vertexCount //xzw add
  14584. options.debug && (boxMap[tile.id].material.opacity = 1)
  14585. }else{
  14586. console.log('超出', visiVertexCount)
  14587. }
  14588. }
  14589. /* if(!renderMap[tile.id].realVisible()){
  14590. console.error('!realVisible')
  14591. } */
  14592. }
  14593. }
  14594. else {
  14595. if (renderMap[tile.id]) {
  14596. if(renderMap[tile.id].visible){
  14597. renderMap[tile.id].visible = false;
  14598. options.debug && (boxMap[tile.id].material.opacity = 0.1)
  14599. visiVertexCount -= renderMap[tile.id].vertexCount //xzw add
  14600. }
  14601. }
  14602. }
  14603. }
  14604. while (unloadQueue.length > 0) {
  14605. const tile = unloadQueue.pop();
  14606. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14607. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14608. root.remove(renderMap[tile.id]);
  14609. disposeNode(renderMap[tile.id]);
  14610. delete renderMap[tile.id];
  14611. }
  14612. if (boxMap[tile.id]) {
  14613. disposeNode(boxMap[tile.id]);
  14614. tileBoxes.remove(boxMap[tile.id]);
  14615. delete boxMap[tile.id];
  14616. }
  14617. }
  14618. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14619. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14620. if (props.onProgress) {
  14621. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14622. }
  14623. if (props.loadingManager && !loadingEnded) {
  14624. if (tilesLoading == 0 &&
  14625. (options.preloadTilesCount == null ||
  14626. tilesLoaded >= options.preloadTilesCount)) {
  14627. loadingEnded = true;
  14628. props.loadingManager.itemEnd(props.url);
  14629. }
  14630. }
  14631. return frameState;
  14632. }
  14633. return {
  14634. model: root,
  14635. runtime: {
  14636. getTileset: () => {
  14637. return tileset;
  14638. },
  14639. getStats: () => {
  14640. return tileset.stats;
  14641. },
  14642. showTiles: (visible) => {
  14643. tileBoxes.visible = visible;
  14644. },
  14645. setWireframe: (wireframe) => {
  14646. options.wireframe = wireframe;
  14647. root.traverse((object) => {
  14648. if (object instanceof Mesh) {
  14649. object.material.wireframe = wireframe;
  14650. }
  14651. });
  14652. },
  14653. setDebug: (debug) => {
  14654. options.debug = debug;
  14655. tileBoxes.visible = debug;
  14656. },
  14657. setShading: (shading) => {
  14658. options.shading = shading;
  14659. },
  14660. getTileBoxes: () => {
  14661. return tileBoxes;
  14662. },
  14663. setViewDistanceScale: (scale) => {
  14664. tileset.options.viewDistanceScale = scale;
  14665. tileset._frameNumber++;
  14666. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14667. },
  14668. setHideGround: (enabled) => {
  14669. pointcloudUniforms.hideGround.value = enabled;
  14670. },
  14671. setPointCloudColoring: (selection) => {
  14672. pointcloudUniforms.coloring.value = selection;
  14673. },
  14674. setElevationRange: (range) => {
  14675. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14676. },
  14677. setMaxIntensity: (intensity) => {
  14678. pointcloudUniforms.maxIntensity.value = intensity;
  14679. },
  14680. setIntensityContrast: (contrast) => {
  14681. pointcloudUniforms.intensityContrast.value = contrast;
  14682. },
  14683. setPointAlpha: (alpha) => {
  14684. pointcloudUniforms.alpha.value = alpha;
  14685. },
  14686. getLatLongHeightFromPosition: (position) => {
  14687. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14688. return {
  14689. lat: cartographicPosition[1],
  14690. long: cartographicPosition[0],
  14691. height: cartographicPosition[2],
  14692. };
  14693. },
  14694. getPositionFromLatLongHeight: (coord) => {
  14695. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14696. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14697. },
  14698. getCameraFrustum: (camera) => {
  14699. const frustum = getCameraFrustum(camera);
  14700. const meshes = frustum.planes
  14701. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14702. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14703. const model = new Group();
  14704. for (const mesh of meshes)
  14705. model.add(mesh);
  14706. return model;
  14707. },
  14708. update: function (dt, renderer, camera) {
  14709. cameraReference = camera;
  14710. rendererReference = renderer;
  14711. timer += dt;
  14712. if (tileset && timer >= UPDATE_INTERVAL) {
  14713. if (!lastRootTransform.equals(root.matrixWorld)) {
  14714. timer = 0;
  14715. lastRootTransform.copy(root.matrixWorld);
  14716. updateResetTransform();
  14717. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14718. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14719. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14720. rootTransformInverse.copy(lastRootTransform).invert();
  14721. if (options.debug) {
  14722. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14723. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14724. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14725. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14726. tileBoxes.matrix.copy(root.matrixWorld);
  14727. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14728. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14729. //boxMap[tileset.root.id].updateWorldMatrix()
  14730. }
  14731. }
  14732. if (this.lastCameraTransform == null) {
  14733. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14734. }
  14735. else {
  14736. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14737. !(camera.aspect == lastCameraAspect);
  14738. if (cameraChanged) {
  14739. timer = 0;
  14740. tileset._frameNumber++;
  14741. camera.getWorldPosition(lastCameraPosition);
  14742. this.lastCameraTransform.copy(camera.matrixWorld);
  14743. tilesetUpdate(tileset, renderMap, renderer, camera);
  14744. }
  14745. }
  14746. }/* else{
  14747. console.log('11')
  14748. } */
  14749. },
  14750. dispose: function () {
  14751. disposeFlag = true;
  14752. tileset._destroy();
  14753. while (root.children.length > 0) {
  14754. const obj = root.children[0];
  14755. disposeNode(obj);
  14756. root.remove(obj);
  14757. }
  14758. while (tileBoxes.children.length > 0) {
  14759. const obj = tileBoxes.children[0];
  14760. tileBoxes.remove(obj);
  14761. obj.geometry.dispose();
  14762. obj.material.dispose();
  14763. }
  14764. if (ktx2Loader) {
  14765. ktx2Loader.dispose();
  14766. }
  14767. if (dracoLoader) {
  14768. dracoLoader.dispose();
  14769. }
  14770. },
  14771. },
  14772. };
  14773. });
  14774. }
  14775. }
  14776. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14777. return __awaiter(this, void 0, void 0, function* () {
  14778. return new Promise((resolve, reject) => {
  14779. var _a;
  14780. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14781. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14782. // The computed trasnform already contains the root's transform, so we have to invert it
  14783. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14784. //不知为何在刚开始加载时迅速移动模型,tiles位置会参差不齐。应该和contentTransform有关,也就是tile.computedTransform 和rootTransformInverse的问题。但即使每次_updateTransform后重新计算也不对
  14785. if (shouldRotate) {
  14786. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  14787. }
  14788. gltfLoader.parse(
  14789. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14790. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14791. (gltf) => {
  14792. const tileContent = gltf.scenes[0];
  14793. //tileContent.applyMatrix4(contentTransform);
  14794. tileContent.vertexCount = 0 //xzw add
  14795. tileContent.traverse((object) => {
  14796. if (object.type == "Mesh") {
  14797. const mesh = object;
  14798. //mesh.tileId = tile.id//add
  14799. const originalMaterial = mesh.material;
  14800. const originalMap = originalMaterial.map;
  14801. if (options.material) {
  14802. mesh.material = options.material.clone();
  14803. originalMaterial.dispose();
  14804. }
  14805. else if (options.shading == Shading.FlatTexture) {
  14806. mesh.material = unlitMaterial.clone();
  14807. originalMaterial.dispose();
  14808. }
  14809. if (options.shading != Shading.ShadedNoTexture) {
  14810. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  14811. mesh.material.uniforms.map = { value: originalMap };
  14812. }
  14813. else {
  14814. mesh.material.map = originalMap;
  14815. }
  14816. }
  14817. else {
  14818. if (originalMap) {
  14819. originalMap.dispose();
  14820. }
  14821. mesh.material.map = null;
  14822. }
  14823. if (options.shaderCallback) {
  14824. mesh.onBeforeRender = options.shaderCallback;
  14825. }
  14826. mesh.material.wireframe = options.wireframe;
  14827. if (options.computeNormals) {
  14828. mesh.geometry.computeVertexNormals();
  14829. }
  14830. //xzw add:
  14831. tileContent.vertexCount += mesh.geometry.attributes.position.count
  14832. //------------------add on 2023.1.16----zeg
  14833. mesh.geometry.applyMatrix4(contentTransform)
  14834. if (tile.content.rtcCenter) {
  14835. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  14836. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  14837. } else {
  14838. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  14839. }
  14840. //---------------------
  14841. }
  14842. });
  14843. resolve(tileContent);
  14844. },
  14845. (e) => {
  14846. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  14847. }
  14848. );
  14849. });
  14850. });
  14851. }
  14852. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  14853. const d = {
  14854. rtc_center: tile.content.rtcCenter,
  14855. points: tile.content.attributes.positions,
  14856. intensities: tile.content.attributes.intensity,
  14857. classifications: tile.content.attributes.classification,
  14858. rgb: null,
  14859. rgba: null,
  14860. };
  14861. const { colors } = tile.content.attributes;
  14862. if (colors && colors.size === 3) {
  14863. d.rgb = colors.value;
  14864. }
  14865. if (colors && colors.size === 4) {
  14866. d.rgba = colors.value;
  14867. }
  14868. const geometry = new BufferGeometry();
  14869. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  14870. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  14871. if (d.rgba) {
  14872. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  14873. }
  14874. else if (d.rgb) {
  14875. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  14876. }
  14877. if (d.intensities) {
  14878. geometry.setAttribute('intensity',
  14879. // Handles both 16bit or 8bit intensity values
  14880. new BufferAttribute(d.intensities, 1, true));
  14881. }
  14882. if (d.classifications) {
  14883. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  14884. }
  14885. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  14886. if (d.rtc_center) {
  14887. const c = d.rtc_center;
  14888. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  14889. }
  14890. tileContent.applyMatrix4(contentTransform);
  14891. return tileContent;
  14892. }
  14893. function disposeMaterial(material) {
  14894. var _a, _b, _c, _d;
  14895. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  14896. (_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();
  14897. }
  14898. else if (material.map) {
  14899. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  14900. }
  14901. material.dispose();
  14902. }
  14903. function disposeNode(node) {
  14904. node.traverse((object) => {
  14905. if (object.isMesh) {
  14906. object.geometry.dispose();
  14907. if (object.material.isMaterial) {
  14908. disposeMaterial(object.material);
  14909. }
  14910. else {
  14911. // an array of materials
  14912. for (const material of object.material) {
  14913. disposeMaterial(material);
  14914. }
  14915. }
  14916. }
  14917. });
  14918. for (let i = node.children.length - 1; i >= 0; i--) {
  14919. const obj = node.children[i];
  14920. node.remove(obj);
  14921. }
  14922. }
  14923. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  14924. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  14925. /*
  14926. 关键搜寻:
  14927. Loader3DTiles : const tileset = new Tileset3D
  14928. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  14929. createGLTFNodes : gltfLoader.parse
  14930. */