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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334
  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. let rtcCenterGlobal = false//默认false,也就是scale.z要乘以-1
  8. /*! *****************************************************************************
  9. github: https://github.com/nytimes/three-loader-3dtiles
  10. Copyright (c) Microsoft Corporation.
  11. Permission to use, copy, modify, and/or distribute this software for any
  12. purpose with or without fee is hereby granted.
  13. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  14. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  15. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  16. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  17. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  18. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  19. PERFORMANCE OF THIS SOFTWARE.
  20. ***************************************************************************** */
  21. let visiGeoCount = 0
  22. const maxVertexVisi = 5e6
  23. const maxTexVisi = 500
  24. let maxDepth = 100
  25. function getGpuMemoryUsage(win = window){//总的
  26. let c = 0
  27. viewer.setAllTilesets(model=>{
  28. let tileset3D = model.runtime.getTileset()
  29. c += tileset3D.gpuMemoryUsageInBytes //不会因为tileset或tile隐藏而降低,除非释放了资源
  30. })
  31. if(win.parent != win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  32. c += getGpuMemoryUsage(win.parent)
  33. }
  34. viewer.tiles3dMemoryUsage = c
  35. return c
  36. }
  37. function updateQuality(){
  38. const maximumMemory = Potree.settings.tiles3DMaxMemory * 1024 * 1024;
  39. let memory = getGpuMemoryUsage()
  40. let r = memory / maximumMemory
  41. viewer.setAllTilesets(model=>{
  42. let tileset = model.runtime.getTileset()
  43. let e = tileset.options.maximumScreenSpaceError * THREE.Math.clamp(r, 0.9, 1.1)
  44. e = THREE.Math.clamp(e, tileset.options.initialMaxSSE, 1000)
  45. tileset.options.maximumScreenSpaceError = e
  46. })
  47. }
  48. function changeModelPointCount(tile, type){
  49. let posCount , texArea
  50. if(type == 'add'){
  51. let o = viewer.getObjectPointCount(tile.tileContent)
  52. posCount = o.posCount, texArea = o.texArea
  53. tile.posCount = posCount, tile.texArea = texArea
  54. }else{
  55. posCount = -tile.posCount, texArea = -tile.texArea
  56. }
  57. viewer.memoryModelCountInfo.tilePosCount += posCount
  58. viewer.memoryModelCountInfo.tileTexArea += texArea
  59. }
  60. function __awaiter(thisArg, _arguments, P, generator) {
  61. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  62. return new (P || (P = Promise))(function (resolve, reject) {
  63. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  64. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  65. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  66. step((generator = generator.apply(thisArg, _arguments || [])).next());
  67. });
  68. }
  69. function assert$7(condition, message) {
  70. if (!condition) {
  71. throw new Error(message || 'loader assertion failed.');
  72. }
  73. }
  74. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  75. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  76. matches$1 && parseFloat(matches$1[1]) || 0;
  77. const VERSION$8 = "3.1.4" ;
  78. function assert$6(condition, message) {
  79. if (!condition) {
  80. throw new Error(message || 'loaders.gl assertion failed.');
  81. }
  82. }
  83. const globals$1 = {
  84. self: typeof self !== 'undefined' && self,
  85. window: typeof window !== 'undefined' && window,
  86. global: typeof global !== 'undefined' && global,
  87. document: typeof document !== 'undefined' && document
  88. };
  89. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  90. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  91. const isWorker = typeof importScripts === 'function';
  92. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  93. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  94. matches && parseFloat(matches[1]) || 0;
  95. function _defineProperty(obj, key, value) {
  96. if (key in obj) {
  97. Object.defineProperty(obj, key, {
  98. value: value,
  99. enumerable: true,
  100. configurable: true,
  101. writable: true
  102. });
  103. } else {
  104. obj[key] = value;
  105. }
  106. return obj;
  107. }
  108. class WorkerJob {
  109. constructor(jobName, workerThread) {
  110. _defineProperty(this, "name", void 0);
  111. _defineProperty(this, "workerThread", void 0);
  112. _defineProperty(this, "isRunning", void 0);
  113. _defineProperty(this, "result", void 0);
  114. _defineProperty(this, "_resolve", void 0);
  115. _defineProperty(this, "_reject", void 0);
  116. this.name = jobName;
  117. this.workerThread = workerThread;
  118. this.isRunning = true;
  119. this._resolve = () => {};
  120. this._reject = () => {};
  121. this.result = new Promise((resolve, reject) => {
  122. this._resolve = resolve;
  123. this._reject = reject;
  124. });
  125. }
  126. postMessage(type, payload) {
  127. this.workerThread.postMessage({
  128. source: 'loaders.gl',
  129. type,
  130. payload
  131. });
  132. }
  133. done(value) {
  134. assert$6(this.isRunning);
  135. this.isRunning = false;
  136. this._resolve(value);
  137. }
  138. error(error) {
  139. assert$6(this.isRunning);
  140. this.isRunning = false;
  141. this._reject(error);
  142. }
  143. }
  144. const workerURLCache = new Map();
  145. function getLoadableWorkerURL(props) {
  146. assert$6(props.source && !props.url || !props.source && props.url);
  147. let workerURL = workerURLCache.get(props.source || props.url);
  148. if (!workerURL) {
  149. if (props.url) {
  150. workerURL = getLoadableWorkerURLFromURL(props.url);
  151. workerURLCache.set(props.url, workerURL);
  152. }
  153. if (props.source) {
  154. workerURL = getLoadableWorkerURLFromSource(props.source);
  155. workerURLCache.set(props.source, workerURL);
  156. }
  157. }
  158. assert$6(workerURL);
  159. return workerURL;
  160. }
  161. function getLoadableWorkerURLFromURL(url) {
  162. if (!url.startsWith('http')) {
  163. return url;
  164. }
  165. const workerSource = buildScriptSource(url);
  166. return getLoadableWorkerURLFromSource(workerSource);
  167. }
  168. function getLoadableWorkerURLFromSource(workerSource) {
  169. const blob = new Blob([workerSource], {
  170. type: 'application/javascript'
  171. });
  172. return URL.createObjectURL(blob);
  173. }
  174. function buildScriptSource(workerUrl) {
  175. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  176. }
  177. function getTransferList(object, recursive = true, transfers) {
  178. const transfersSet = transfers || new Set();
  179. if (!object) ; else if (isTransferable(object)) {
  180. transfersSet.add(object);
  181. } else if (isTransferable(object.buffer)) {
  182. transfersSet.add(object.buffer);
  183. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  184. for (const key in object) {
  185. getTransferList(object[key], recursive, transfersSet);
  186. }
  187. }
  188. return transfers === undefined ? Array.from(transfersSet) : [];
  189. }
  190. function isTransferable(object) {
  191. if (!object) {
  192. return false;
  193. }
  194. if (object instanceof ArrayBuffer) {
  195. return true;
  196. }
  197. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  198. return true;
  199. }
  200. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  201. return true;
  202. }
  203. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  204. return true;
  205. }
  206. return false;
  207. }
  208. const NOOP = () => {};
  209. class WorkerThread {
  210. static isSupported() {
  211. return typeof Worker !== 'undefined';
  212. }
  213. constructor(props) {
  214. _defineProperty(this, "name", void 0);
  215. _defineProperty(this, "source", void 0);
  216. _defineProperty(this, "url", void 0);
  217. _defineProperty(this, "terminated", false);
  218. _defineProperty(this, "worker", void 0);
  219. _defineProperty(this, "onMessage", void 0);
  220. _defineProperty(this, "onError", void 0);
  221. _defineProperty(this, "_loadableURL", '');
  222. const {
  223. name,
  224. source,
  225. url
  226. } = props;
  227. assert$6(source || url);
  228. this.name = name;
  229. this.source = source;
  230. this.url = url;
  231. this.onMessage = NOOP;
  232. this.onError = error => console.log(error);
  233. this.worker = this._createBrowserWorker();
  234. }
  235. destroy() {
  236. this.onMessage = NOOP;
  237. this.onError = NOOP;
  238. this.worker.terminate();
  239. this.terminated = true;
  240. }
  241. get isRunning() {
  242. return Boolean(this.onMessage);
  243. }
  244. postMessage(data, transferList) {
  245. transferList = transferList || getTransferList(data);
  246. this.worker.postMessage(data, transferList);
  247. }
  248. _getErrorFromErrorEvent(event) {
  249. let message = 'Failed to load ';
  250. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  251. if (event.message) {
  252. message += "".concat(event.message, " in ");
  253. }
  254. if (event.lineno) {
  255. message += ":".concat(event.lineno, ":").concat(event.colno);
  256. }
  257. return new Error(message);
  258. }
  259. _createBrowserWorker() {
  260. this._loadableURL = getLoadableWorkerURL({
  261. source: this.source,
  262. url: this.url
  263. });
  264. const worker = new Worker(this._loadableURL, {
  265. name: this.name
  266. });
  267. worker.onmessage = event => {
  268. if (!event.data) {
  269. this.onError(new Error('No data received'));
  270. } else {
  271. this.onMessage(event.data);
  272. }
  273. };
  274. worker.onerror = error => {
  275. this.onError(this._getErrorFromErrorEvent(error));
  276. this.terminated = true;
  277. };
  278. worker.onmessageerror = event => console.error(event);
  279. return worker;
  280. }
  281. }
  282. class WorkerPool {
  283. constructor(props) {
  284. _defineProperty(this, "name", 'unnamed');
  285. _defineProperty(this, "source", void 0);
  286. _defineProperty(this, "url", void 0);
  287. _defineProperty(this, "maxConcurrency", 1);
  288. _defineProperty(this, "maxMobileConcurrency", 1);
  289. _defineProperty(this, "onDebug", () => {});
  290. _defineProperty(this, "reuseWorkers", true);
  291. _defineProperty(this, "props", {});
  292. _defineProperty(this, "jobQueue", []);
  293. _defineProperty(this, "idleQueue", []);
  294. _defineProperty(this, "count", 0);
  295. _defineProperty(this, "isDestroyed", false);
  296. this.source = props.source;
  297. this.url = props.url;
  298. this.setProps(props);
  299. }
  300. destroy() {
  301. this.idleQueue.forEach(worker => worker.destroy());
  302. this.isDestroyed = true;
  303. }
  304. setProps(props) {
  305. this.props = { ...this.props,
  306. ...props
  307. };
  308. if (props.name !== undefined) {
  309. this.name = props.name;
  310. }
  311. if (props.maxConcurrency !== undefined) {
  312. this.maxConcurrency = props.maxConcurrency;
  313. }
  314. if (props.maxMobileConcurrency !== undefined) {
  315. this.maxMobileConcurrency = props.maxMobileConcurrency;
  316. }
  317. if (props.reuseWorkers !== undefined) {
  318. this.reuseWorkers = props.reuseWorkers;
  319. }
  320. if (props.onDebug !== undefined) {
  321. this.onDebug = props.onDebug;
  322. }
  323. }
  324. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  325. const startPromise = new Promise(onStart => {
  326. this.jobQueue.push({
  327. name,
  328. onMessage,
  329. onError,
  330. onStart
  331. });
  332. return this;
  333. });
  334. this._startQueuedJob();
  335. return await startPromise;
  336. }
  337. async _startQueuedJob() {
  338. if (!this.jobQueue.length) {
  339. return;
  340. }
  341. const workerThread = this._getAvailableWorker();
  342. if (!workerThread) {
  343. return;
  344. }
  345. const queuedJob = this.jobQueue.shift();
  346. if (queuedJob) {
  347. this.onDebug({
  348. message: 'Starting job',
  349. name: queuedJob.name,
  350. workerThread,
  351. backlog: this.jobQueue.length
  352. });
  353. const job = new WorkerJob(queuedJob.name, workerThread);
  354. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  355. workerThread.onError = error => queuedJob.onError(job, error);
  356. queuedJob.onStart(job);
  357. try {
  358. await job.result;
  359. } finally {
  360. this.returnWorkerToQueue(workerThread);
  361. }
  362. }
  363. }
  364. returnWorkerToQueue(worker) {
  365. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  366. if (shouldDestroyWorker) {
  367. worker.destroy();
  368. this.count--;
  369. } else {
  370. this.idleQueue.push(worker);
  371. }
  372. if (!this.isDestroyed) {
  373. this._startQueuedJob();
  374. }
  375. }
  376. _getAvailableWorker() {
  377. if (this.idleQueue.length > 0) {
  378. return this.idleQueue.shift() || null;
  379. }
  380. if (this.count < this._getMaxConcurrency()) {
  381. this.count++;
  382. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  383. return new WorkerThread({
  384. name,
  385. source: this.source,
  386. url: this.url
  387. });
  388. }
  389. return null;
  390. }
  391. _getMaxConcurrency() {
  392. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  393. }
  394. }
  395. const DEFAULT_PROPS$3 = {
  396. maxConcurrency: 3,
  397. maxMobileConcurrency: 1,
  398. onDebug: () => {},
  399. reuseWorkers: true
  400. };
  401. class WorkerFarm {
  402. static isSupported() {
  403. return WorkerThread.isSupported();
  404. }
  405. static getWorkerFarm(props = {}) {
  406. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  407. WorkerFarm._workerFarm.setProps(props);
  408. return WorkerFarm._workerFarm;
  409. }
  410. constructor(props) {
  411. _defineProperty(this, "props", void 0);
  412. _defineProperty(this, "workerPools", new Map());
  413. this.props = { ...DEFAULT_PROPS$3
  414. };
  415. this.setProps(props);
  416. this.workerPools = new Map();
  417. }
  418. destroy() {
  419. for (const workerPool of this.workerPools.values()) {
  420. workerPool.destroy();
  421. }
  422. }
  423. setProps(props) {
  424. this.props = { ...this.props,
  425. ...props
  426. };
  427. for (const workerPool of this.workerPools.values()) {
  428. workerPool.setProps(this._getWorkerPoolProps());
  429. }
  430. }
  431. getWorkerPool(options) {
  432. const {
  433. name,
  434. source,
  435. url
  436. } = options;
  437. let workerPool = this.workerPools.get(name);
  438. if (!workerPool) {
  439. workerPool = new WorkerPool({
  440. name,
  441. source,
  442. url
  443. });
  444. workerPool.setProps(this._getWorkerPoolProps());
  445. this.workerPools.set(name, workerPool);
  446. }
  447. return workerPool;
  448. }
  449. _getWorkerPoolProps() {
  450. return {
  451. maxConcurrency: this.props.maxConcurrency,
  452. maxMobileConcurrency: this.props.maxMobileConcurrency,
  453. reuseWorkers: this.props.reuseWorkers,
  454. onDebug: this.props.onDebug
  455. };
  456. }
  457. }
  458. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  459. const NPM_TAG = 'latest';
  460. function getWorkerURL(worker, options = {}) {
  461. const workerOptions = options[worker.id] || {};
  462. const workerFile = "".concat(worker.id, "-worker.js");
  463. let url = workerOptions.workerUrl;
  464. if (!url && worker.id === 'compression') {
  465. url = options.workerUrl;
  466. }
  467. if (options._workerType === 'test') {
  468. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  469. }
  470. if (!url) {
  471. let version = worker.version;
  472. if (version === 'latest') {
  473. version = NPM_TAG;
  474. }
  475. const versionTag = version ? "@".concat(version) : '';
  476. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  477. }
  478. assert$6(url);
  479. return url;
  480. }
  481. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  482. assert$6(worker, 'no worker provided');
  483. const workerVersion = worker.version;
  484. if (!coreVersion || !workerVersion) {
  485. return false;
  486. }
  487. return true;
  488. }
  489. var ChildProcessProxy = {};
  490. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  491. 'default': ChildProcessProxy
  492. }));
  493. const VERSION$7 = "3.1.4" ;
  494. const loadLibraryPromises = {};
  495. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  496. if (moduleName) {
  497. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  498. }
  499. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  500. return await loadLibraryPromises[libraryUrl];
  501. }
  502. function getLibraryUrl(library, moduleName, options) {
  503. if (library.startsWith('http')) {
  504. return library;
  505. }
  506. const modules = options.modules || {};
  507. if (modules[library]) {
  508. return modules[library];
  509. }
  510. if (!isBrowser$1) {
  511. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  512. }
  513. if (options.CDN) {
  514. assert$6(options.CDN.startsWith('http'));
  515. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  516. }
  517. if (isWorker) {
  518. return "../src/libs/".concat(library);
  519. }
  520. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  521. }
  522. async function loadLibraryFromFile(libraryUrl) {
  523. if (libraryUrl.endsWith('wasm')) {
  524. const response = await fetch(libraryUrl);
  525. return await response.arrayBuffer();
  526. }
  527. if (!isBrowser$1) {
  528. try {
  529. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  530. } catch {
  531. return null;
  532. }
  533. }
  534. if (isWorker) {
  535. return importScripts(libraryUrl);
  536. }
  537. const response = await fetch(libraryUrl);
  538. const scriptSource = await response.text();
  539. return loadLibraryFromString(scriptSource, libraryUrl);
  540. }
  541. function loadLibraryFromString(scriptSource, id) {
  542. if (!isBrowser$1) {
  543. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  544. }
  545. if (isWorker) {
  546. eval.call(global_, scriptSource);
  547. return null;
  548. }
  549. const script = document.createElement('script');
  550. script.id = id;
  551. try {
  552. script.appendChild(document.createTextNode(scriptSource));
  553. } catch (e) {
  554. script.text = scriptSource;
  555. }
  556. document.body.appendChild(script);
  557. return null;
  558. }
  559. function canParseWithWorker(loader, options) {
  560. if (!WorkerFarm.isSupported()) {
  561. return false;
  562. }
  563. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  564. }
  565. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  566. const name = loader.id;
  567. const url = getWorkerURL(loader, options);
  568. const workerFarm = WorkerFarm.getWorkerFarm(options);
  569. const workerPool = workerFarm.getWorkerPool({
  570. name,
  571. url
  572. });
  573. options = JSON.parse(JSON.stringify(options));
  574. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  575. job.postMessage('process', {
  576. input: data,
  577. options
  578. });
  579. const result = await job.result;
  580. return await result.result;
  581. }
  582. async function onMessage(parseOnMainThread, job, type, payload) {
  583. switch (type) {
  584. case 'done':
  585. job.done(payload);
  586. break;
  587. case 'error':
  588. job.error(new Error(payload.error));
  589. break;
  590. case 'process':
  591. const {
  592. id,
  593. input,
  594. options
  595. } = payload;
  596. try {
  597. const result = await parseOnMainThread(input, options);
  598. job.postMessage('done', {
  599. id,
  600. result
  601. });
  602. } catch (error) {
  603. const message = error instanceof Error ? error.message : 'unknown error';
  604. job.postMessage('error', {
  605. id,
  606. error: message
  607. });
  608. }
  609. break;
  610. default:
  611. console.warn("parse-with-worker unknown message ".concat(type));
  612. }
  613. }
  614. function getFirstCharacters$1(data, length = 5) {
  615. if (typeof data === 'string') {
  616. return data.slice(0, length);
  617. } else if (ArrayBuffer.isView(data)) {
  618. return getMagicString$3(data.buffer, data.byteOffset, length);
  619. } else if (data instanceof ArrayBuffer) {
  620. const byteOffset = 0;
  621. return getMagicString$3(data, byteOffset, length);
  622. }
  623. return '';
  624. }
  625. function getMagicString$3(arrayBuffer, byteOffset, length) {
  626. if (arrayBuffer.byteLength <= byteOffset + length) {
  627. return '';
  628. }
  629. const dataView = new DataView(arrayBuffer);
  630. let magic = '';
  631. for (let i = 0; i < length; i++) {
  632. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  633. }
  634. return magic;
  635. }
  636. function parseJSON(string) {
  637. try {
  638. return JSON.parse(string);
  639. } catch (_) {
  640. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  641. }
  642. }
  643. function isBuffer$1(value) {
  644. return value && typeof value === 'object' && value.isBuffer;
  645. }
  646. function bufferToArrayBuffer(buffer) {
  647. if (isBuffer$1(buffer)) {
  648. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  649. return typedArray.slice().buffer;
  650. }
  651. return buffer;
  652. }
  653. function toArrayBuffer(data) {
  654. if (isBuffer$1(data)) {
  655. return bufferToArrayBuffer(data);
  656. }
  657. if (data instanceof ArrayBuffer) {
  658. return data;
  659. }
  660. if (ArrayBuffer.isView(data)) {
  661. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  662. return data.buffer;
  663. }
  664. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  665. }
  666. if (typeof data === 'string') {
  667. const text = data;
  668. const uint8Array = new TextEncoder().encode(text);
  669. return uint8Array.buffer;
  670. }
  671. if (data && typeof data === 'object' && data._toArrayBuffer) {
  672. return data._toArrayBuffer();
  673. }
  674. throw new Error('toArrayBuffer');
  675. }
  676. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  677. byteLength = byteLength || arrayBuffer1.byteLength;
  678. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  679. return false;
  680. }
  681. const array1 = new Uint8Array(arrayBuffer1);
  682. const array2 = new Uint8Array(arrayBuffer2);
  683. for (let i = 0; i < array1.length; ++i) {
  684. if (array1[i] !== array2[i]) {
  685. return false;
  686. }
  687. }
  688. return true;
  689. }
  690. function concatenateArrayBuffers(...sources) {
  691. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  692. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  693. const result = new Uint8Array(byteLength);
  694. let offset = 0;
  695. for (const sourceArray of sourceArrays) {
  696. result.set(sourceArray, offset);
  697. offset += sourceArray.byteLength;
  698. }
  699. return result.buffer;
  700. }
  701. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  702. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  703. const arrayCopy = new Uint8Array(subArray);
  704. return arrayCopy.buffer;
  705. }
  706. function padToNBytes(byteLength, padding) {
  707. assert$7(byteLength >= 0);
  708. assert$7(padding > 0);
  709. return byteLength + (padding - 1) & ~(padding - 1);
  710. }
  711. function copyToArray(source, target, targetOffset) {
  712. let sourceArray;
  713. if (source instanceof ArrayBuffer) {
  714. sourceArray = new Uint8Array(source);
  715. } else {
  716. const srcByteOffset = source.byteOffset;
  717. const srcByteLength = source.byteLength;
  718. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  719. }
  720. target.set(sourceArray, targetOffset);
  721. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  722. }
  723. async function concatenateArrayBuffersAsync(asyncIterator) {
  724. const arrayBuffers = [];
  725. for await (const chunk of asyncIterator) {
  726. arrayBuffers.push(chunk);
  727. }
  728. return concatenateArrayBuffers(...arrayBuffers);
  729. }
  730. function getHiResTimestamp$1() {
  731. let timestamp;
  732. if (typeof window !== 'undefined' && window.performance) {
  733. timestamp = window.performance.now();
  734. } else if (typeof process !== 'undefined' && process.hrtime) {
  735. const timeParts = process.hrtime();
  736. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  737. } else {
  738. timestamp = Date.now();
  739. }
  740. return timestamp;
  741. }
  742. class Stat {
  743. constructor(name, type) {
  744. _defineProperty(this, "name", void 0);
  745. _defineProperty(this, "type", void 0);
  746. _defineProperty(this, "sampleSize", 1);
  747. _defineProperty(this, "time", void 0);
  748. _defineProperty(this, "count", void 0);
  749. _defineProperty(this, "samples", void 0);
  750. _defineProperty(this, "lastTiming", void 0);
  751. _defineProperty(this, "lastSampleTime", void 0);
  752. _defineProperty(this, "lastSampleCount", void 0);
  753. _defineProperty(this, "_count", 0);
  754. _defineProperty(this, "_time", 0);
  755. _defineProperty(this, "_samples", 0);
  756. _defineProperty(this, "_startTime", 0);
  757. _defineProperty(this, "_timerPending", false);
  758. this.name = name;
  759. this.type = type;
  760. this.reset();
  761. }
  762. setSampleSize(samples) {
  763. this.sampleSize = samples;
  764. return this;
  765. }
  766. incrementCount() {
  767. this.addCount(1);
  768. return this;
  769. }
  770. decrementCount() {
  771. this.subtractCount(1);
  772. return this;
  773. }
  774. addCount(value) {
  775. this._count += value;
  776. this._samples++;
  777. this._checkSampling();
  778. return this;
  779. }
  780. subtractCount(value) {
  781. this._count -= value;
  782. this._samples++;
  783. this._checkSampling();
  784. return this;
  785. }
  786. addTime(time) {
  787. this._time += time;
  788. this.lastTiming = time;
  789. this._samples++;
  790. this._checkSampling();
  791. return this;
  792. }
  793. timeStart() {
  794. this._startTime = getHiResTimestamp$1();
  795. this._timerPending = true;
  796. return this;
  797. }
  798. timeEnd() {
  799. if (!this._timerPending) {
  800. return this;
  801. }
  802. this.addTime(getHiResTimestamp$1() - this._startTime);
  803. this._timerPending = false;
  804. this._checkSampling();
  805. return this;
  806. }
  807. getSampleAverageCount() {
  808. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  809. }
  810. getSampleAverageTime() {
  811. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  812. }
  813. getSampleHz() {
  814. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  815. }
  816. getAverageCount() {
  817. return this.samples > 0 ? this.count / this.samples : 0;
  818. }
  819. getAverageTime() {
  820. return this.samples > 0 ? this.time / this.samples : 0;
  821. }
  822. getHz() {
  823. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  824. }
  825. reset() {
  826. this.time = 0;
  827. this.count = 0;
  828. this.samples = 0;
  829. this.lastTiming = 0;
  830. this.lastSampleTime = 0;
  831. this.lastSampleCount = 0;
  832. this._count = 0;
  833. this._time = 0;
  834. this._samples = 0;
  835. this._startTime = 0;
  836. this._timerPending = false;
  837. return this;
  838. }
  839. _checkSampling() {
  840. if (this._samples === this.sampleSize) {
  841. this.lastSampleTime = this._time;
  842. this.lastSampleCount = this._count;
  843. this.count += this._count;
  844. this.time += this._time;
  845. this.samples += this._samples;
  846. this._time = 0;
  847. this._count = 0;
  848. this._samples = 0;
  849. }
  850. }
  851. }
  852. class Stats {
  853. constructor(options) {
  854. _defineProperty(this, "id", void 0);
  855. _defineProperty(this, "stats", {});
  856. this.id = options.id;
  857. this.stats = {};
  858. this._initializeStats(options.stats);
  859. Object.seal(this);
  860. }
  861. get(name) {
  862. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  863. return this._getOrCreate({
  864. name,
  865. type
  866. });
  867. }
  868. get size() {
  869. return Object.keys(this.stats).length;
  870. }
  871. reset() {
  872. for (const key in this.stats) {
  873. this.stats[key].reset();
  874. }
  875. return this;
  876. }
  877. forEach(fn) {
  878. for (const key in this.stats) {
  879. fn(this.stats[key]);
  880. }
  881. }
  882. getTable() {
  883. const table = {};
  884. this.forEach(stat => {
  885. table[stat.name] = {
  886. time: stat.time || 0,
  887. count: stat.count || 0,
  888. average: stat.getAverageTime() || 0,
  889. hz: stat.getHz() || 0
  890. };
  891. });
  892. return table;
  893. }
  894. _initializeStats() {
  895. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  896. stats.forEach(stat => this._getOrCreate(stat));
  897. }
  898. _getOrCreate(stat) {
  899. if (!stat || !stat.name) {
  900. return null;
  901. }
  902. const {
  903. name,
  904. type
  905. } = stat;
  906. if (!this.stats[name]) {
  907. if (stat instanceof Stat) {
  908. this.stats[name] = stat;
  909. } else {
  910. this.stats[name] = new Stat(name, type);
  911. }
  912. }
  913. return this.stats[name];
  914. }
  915. }
  916. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  917. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  918. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  919. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  920. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  921. const DEFAULT_PROPS$2 = {
  922. id: 'request-scheduler',
  923. throttleRequests: true,
  924. maxRequests: 6
  925. };
  926. class RequestScheduler {
  927. constructor(props = {}) {
  928. _defineProperty(this, "props", void 0);
  929. _defineProperty(this, "stats", void 0);
  930. _defineProperty(this, "activeRequestCount", 0);
  931. _defineProperty(this, "requestQueue", []);
  932. _defineProperty(this, "requestMap", new Map());
  933. _defineProperty(this, "deferredUpdate", null);
  934. this.props = { ...DEFAULT_PROPS$2,
  935. ...props
  936. };
  937. this.stats = new Stats({
  938. id: this.props.id
  939. });
  940. this.stats.get(STAT_QUEUED_REQUESTS);
  941. this.stats.get(STAT_ACTIVE_REQUESTS);
  942. this.stats.get(STAT_CANCELLED_REQUESTS);
  943. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  944. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  945. }
  946. scheduleRequest(handle, getPriority = () => 0) {
  947. if (!this.props.throttleRequests) {
  948. return Promise.resolve({
  949. done: () => {}
  950. });
  951. }
  952. if (this.requestMap.has(handle)) {
  953. return this.requestMap.get(handle);
  954. }
  955. const request = {
  956. handle,
  957. priority: 0,
  958. getPriority
  959. };
  960. const promise = new Promise(resolve => {
  961. request.resolve = resolve;
  962. return request;
  963. });
  964. this.requestQueue.push(request);
  965. this.requestMap.set(handle, promise);
  966. this._issueNewRequests();
  967. return promise;
  968. }
  969. _issueRequest(request) {
  970. const {
  971. handle,
  972. resolve
  973. } = request;
  974. let isDone = false;
  975. const done = () => {
  976. if (!isDone) {
  977. isDone = true;
  978. this.requestMap.delete(handle);
  979. this.activeRequestCount--;
  980. this._issueNewRequests();
  981. }
  982. };
  983. this.activeRequestCount++;
  984. return resolve ? resolve({
  985. done
  986. }) : Promise.resolve({
  987. done
  988. });
  989. }
  990. _issueNewRequests() {
  991. if (!this.deferredUpdate) {
  992. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  993. }
  994. }
  995. _issueNewRequestsAsync() {
  996. this.deferredUpdate = null;
  997. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  998. if (freeSlots === 0) {
  999. return;
  1000. }
  1001. this._updateAllRequests();
  1002. for (let i = 0; i < freeSlots; ++i) {
  1003. const request = this.requestQueue.shift();
  1004. if (request) {
  1005. this._issueRequest(request);
  1006. }
  1007. }
  1008. }
  1009. _updateAllRequests() {
  1010. const requestQueue = this.requestQueue;
  1011. for (let i = 0; i < requestQueue.length; ++i) {
  1012. const request = requestQueue[i];
  1013. if (!this._updateRequest(request)) {
  1014. requestQueue.splice(i, 1);
  1015. this.requestMap.delete(request.handle);
  1016. i--;
  1017. }
  1018. }
  1019. requestQueue.sort((a, b) => a.priority - b.priority);
  1020. }
  1021. _updateRequest(request) {
  1022. request.priority = request.getPriority(request.handle);
  1023. if (request.priority < 0) {
  1024. request.resolve(null);
  1025. return false;
  1026. }
  1027. return true;
  1028. }
  1029. }
  1030. let pathPrefix = '';
  1031. const fileAliases = {};
  1032. function resolvePath(filename) {
  1033. for (const alias in fileAliases) {
  1034. if (filename.startsWith(alias)) {
  1035. const replacement = fileAliases[alias];
  1036. filename = filename.replace(alias, replacement);
  1037. }
  1038. }
  1039. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1040. filename = "".concat(pathPrefix).concat(filename);
  1041. }
  1042. return filename;
  1043. }
  1044. function filename(url) {
  1045. const slashIndex = url && url.lastIndexOf('/');
  1046. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1047. }
  1048. function dirname(url) {
  1049. const slashIndex = url && url.lastIndexOf('/');
  1050. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1051. }
  1052. const isBoolean = x => typeof x === 'boolean';
  1053. const isFunction = x => typeof x === 'function';
  1054. const isObject = x => x !== null && typeof x === 'object';
  1055. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1056. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1057. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1058. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1059. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1060. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1061. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1062. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1063. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1064. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1065. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1066. function parseMIMEType(mimeString) {
  1067. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1068. if (matches) {
  1069. return matches[1];
  1070. }
  1071. return mimeString;
  1072. }
  1073. function parseMIMETypeFromURL(url) {
  1074. const matches = DATA_URL_PATTERN.exec(url);
  1075. if (matches) {
  1076. return matches[1];
  1077. }
  1078. return '';
  1079. }
  1080. const QUERY_STRING_PATTERN = /\?.*/;
  1081. function getResourceUrlAndType(resource) {
  1082. if (isResponse(resource)) {
  1083. const url = stripQueryString(resource.url || '');
  1084. const contentTypeHeader = resource.headers.get('content-type') || '';
  1085. return {
  1086. url,
  1087. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1088. };
  1089. }
  1090. if (isBlob(resource)) {
  1091. return {
  1092. url: stripQueryString(resource.name || ''),
  1093. type: resource.type || ''
  1094. };
  1095. }
  1096. if (typeof resource === 'string') {
  1097. return {
  1098. url: stripQueryString(resource),
  1099. type: parseMIMETypeFromURL(resource)
  1100. };
  1101. }
  1102. return {
  1103. url: '',
  1104. type: ''
  1105. };
  1106. }
  1107. function getResourceContentLength(resource) {
  1108. if (isResponse(resource)) {
  1109. return resource.headers['content-length'] || -1;
  1110. }
  1111. if (isBlob(resource)) {
  1112. return resource.size;
  1113. }
  1114. if (typeof resource === 'string') {
  1115. return resource.length;
  1116. }
  1117. if (resource instanceof ArrayBuffer) {
  1118. return resource.byteLength;
  1119. }
  1120. if (ArrayBuffer.isView(resource)) {
  1121. return resource.byteLength;
  1122. }
  1123. return -1;
  1124. }
  1125. function stripQueryString(url) {
  1126. return url.replace(QUERY_STRING_PATTERN, '');
  1127. }
  1128. async function makeResponse(resource) {
  1129. if (isResponse(resource)) {
  1130. return resource;
  1131. }
  1132. const headers = {};
  1133. const contentLength = getResourceContentLength(resource);
  1134. if (contentLength >= 0) {
  1135. headers['content-length'] = String(contentLength);
  1136. }
  1137. const {
  1138. url,
  1139. type
  1140. } = getResourceUrlAndType(resource);
  1141. if (type) {
  1142. headers['content-type'] = type;
  1143. }
  1144. const initialDataUrl = await getInitialDataUrl(resource);
  1145. if (initialDataUrl) {
  1146. headers['x-first-bytes'] = initialDataUrl;
  1147. }
  1148. if (typeof resource === 'string') {
  1149. resource = new TextEncoder().encode(resource);
  1150. }
  1151. const response = new Response(resource, {
  1152. headers
  1153. });
  1154. Object.defineProperty(response, 'url', {
  1155. value: url
  1156. });
  1157. return response;
  1158. }
  1159. async function checkResponse(response) {
  1160. if (!response.ok) {
  1161. const message = await getResponseError(response);
  1162. throw new Error(message);
  1163. }
  1164. }
  1165. async function getResponseError(response) {
  1166. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1167. try {
  1168. const contentType = response.headers.get('Content-Type');
  1169. let text = response.statusText;
  1170. if (contentType.includes('application/json')) {
  1171. text += " ".concat(await response.text());
  1172. }
  1173. message += text;
  1174. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1175. } catch (error) {}
  1176. return message;
  1177. }
  1178. async function getInitialDataUrl(resource) {
  1179. const INITIAL_DATA_LENGTH = 5;
  1180. if (typeof resource === 'string') {
  1181. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1182. }
  1183. if (resource instanceof Blob) {
  1184. const blobSlice = resource.slice(0, 5);
  1185. return await new Promise(resolve => {
  1186. const reader = new FileReader();
  1187. reader.onload = event => {
  1188. var _event$target;
  1189. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1190. };
  1191. reader.readAsDataURL(blobSlice);
  1192. });
  1193. }
  1194. if (resource instanceof ArrayBuffer) {
  1195. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1196. const base64 = arrayBufferToBase64(slice);
  1197. return "data:base64,".concat(base64);
  1198. }
  1199. return null;
  1200. }
  1201. function arrayBufferToBase64(buffer) {
  1202. let binary = '';
  1203. const bytes = new Uint8Array(buffer);
  1204. for (let i = 0; i < bytes.byteLength; i++) {
  1205. binary += String.fromCharCode(bytes[i]);
  1206. }
  1207. return btoa(binary);
  1208. }
  1209. async function fetchFile(url, options) {
  1210. if (typeof url === 'string') {
  1211. url = resolvePath(url);
  1212. let fetchOptions = options;
  1213. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1214. fetchOptions = options.fetch;
  1215. }
  1216. return await fetch(url, fetchOptions);
  1217. }
  1218. return await makeResponse(url);
  1219. }
  1220. function isElectron(mockUserAgent) {
  1221. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1222. return true;
  1223. }
  1224. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1225. return true;
  1226. }
  1227. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1228. const userAgent = mockUserAgent || realUserAgent;
  1229. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1230. return true;
  1231. }
  1232. return false;
  1233. }
  1234. function isBrowser() {
  1235. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1236. return !isNode || isElectron();
  1237. }
  1238. const globals = {
  1239. self: typeof self !== 'undefined' && self,
  1240. window: typeof window !== 'undefined' && window,
  1241. global: typeof global !== 'undefined' && global,
  1242. document: typeof document !== 'undefined' && document,
  1243. process: typeof process === 'object' && process
  1244. };
  1245. const window_ = globals.window || globals.self || globals.global;
  1246. const process_ = globals.process || {};
  1247. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1248. isBrowser();
  1249. function getStorage(type) {
  1250. try {
  1251. const storage = window[type];
  1252. const x = '__storage_test__';
  1253. storage.setItem(x, x);
  1254. storage.removeItem(x);
  1255. return storage;
  1256. } catch (e) {
  1257. return null;
  1258. }
  1259. }
  1260. class LocalStorage {
  1261. constructor(id) {
  1262. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1263. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1264. _defineProperty(this, "storage", void 0);
  1265. _defineProperty(this, "id", void 0);
  1266. _defineProperty(this, "config", {});
  1267. this.storage = getStorage(type);
  1268. this.id = id;
  1269. this.config = {};
  1270. Object.assign(this.config, defaultSettings);
  1271. this._loadConfiguration();
  1272. }
  1273. getConfiguration() {
  1274. return this.config;
  1275. }
  1276. setConfiguration(configuration) {
  1277. this.config = {};
  1278. return this.updateConfiguration(configuration);
  1279. }
  1280. updateConfiguration(configuration) {
  1281. Object.assign(this.config, configuration);
  1282. if (this.storage) {
  1283. const serialized = JSON.stringify(this.config);
  1284. this.storage.setItem(this.id, serialized);
  1285. }
  1286. return this;
  1287. }
  1288. _loadConfiguration() {
  1289. let configuration = {};
  1290. if (this.storage) {
  1291. const serializedConfiguration = this.storage.getItem(this.id);
  1292. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1293. }
  1294. Object.assign(this.config, configuration);
  1295. return this;
  1296. }
  1297. }
  1298. function formatTime(ms) {
  1299. let formatted;
  1300. if (ms < 10) {
  1301. formatted = "".concat(ms.toFixed(2), "ms");
  1302. } else if (ms < 100) {
  1303. formatted = "".concat(ms.toFixed(1), "ms");
  1304. } else if (ms < 1000) {
  1305. formatted = "".concat(ms.toFixed(0), "ms");
  1306. } else {
  1307. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1308. }
  1309. return formatted;
  1310. }
  1311. function leftPad(string) {
  1312. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1313. const padLength = Math.max(length - string.length, 0);
  1314. return "".concat(' '.repeat(padLength)).concat(string);
  1315. }
  1316. function formatImage(image, message, scale) {
  1317. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1318. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1319. if (image.width > maxWidth) {
  1320. scale = Math.min(scale, maxWidth / image.width);
  1321. }
  1322. const width = image.width * scale;
  1323. const height = image.height * scale;
  1324. 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('');
  1325. return ["".concat(message, " %c+"), style];
  1326. }
  1327. let COLOR;
  1328. (function (COLOR) {
  1329. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1330. COLOR[COLOR["RED"] = 31] = "RED";
  1331. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1332. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1333. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1334. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1335. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1336. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1337. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1338. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1339. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1340. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1341. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1342. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1343. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1344. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1345. })(COLOR || (COLOR = {}));
  1346. function getColor(color) {
  1347. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1348. }
  1349. function addColor(string, color, background) {
  1350. if (!isBrowser && typeof string === 'string') {
  1351. if (color) {
  1352. color = getColor(color);
  1353. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1354. }
  1355. if (background) {
  1356. color = getColor(background);
  1357. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1358. }
  1359. }
  1360. return string;
  1361. }
  1362. function autobind(obj) {
  1363. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1364. const proto = Object.getPrototypeOf(obj);
  1365. const propNames = Object.getOwnPropertyNames(proto);
  1366. for (const key of propNames) {
  1367. if (typeof obj[key] === 'function') {
  1368. if (!predefined.find(name => key === name)) {
  1369. obj[key] = obj[key].bind(obj);
  1370. }
  1371. }
  1372. }
  1373. }
  1374. function assert$5(condition, message) {
  1375. if (!condition) {
  1376. throw new Error(message || 'Assertion failed');
  1377. }
  1378. }
  1379. function getHiResTimestamp() {
  1380. let timestamp;
  1381. if (isBrowser && 'performance' in window_) {
  1382. var _window$performance, _window$performance$n;
  1383. 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);
  1384. } else if ('hrtime' in process_) {
  1385. var _process$hrtime;
  1386. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1387. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1388. } else {
  1389. timestamp = Date.now();
  1390. }
  1391. return timestamp;
  1392. }
  1393. const originalConsole = {
  1394. debug: isBrowser ? console.debug || console.log : console.log,
  1395. log: console.log,
  1396. info: console.info,
  1397. warn: console.warn,
  1398. error: console.error
  1399. };
  1400. const DEFAULT_SETTINGS = {
  1401. enabled: true,
  1402. level: 0
  1403. };
  1404. function noop$1() {}
  1405. const cache = {};
  1406. const ONCE = {
  1407. once: true
  1408. };
  1409. class Log {
  1410. constructor() {
  1411. let {
  1412. id
  1413. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1414. id: ''
  1415. };
  1416. _defineProperty(this, "id", void 0);
  1417. _defineProperty(this, "VERSION", VERSION$6);
  1418. _defineProperty(this, "_startTs", getHiResTimestamp());
  1419. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1420. _defineProperty(this, "_storage", void 0);
  1421. _defineProperty(this, "userData", {});
  1422. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1423. this.id = id;
  1424. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1425. this.userData = {};
  1426. this.timeStamp("".concat(this.id, " started"));
  1427. autobind(this);
  1428. Object.seal(this);
  1429. }
  1430. set level(newLevel) {
  1431. this.setLevel(newLevel);
  1432. }
  1433. get level() {
  1434. return this.getLevel();
  1435. }
  1436. isEnabled() {
  1437. return this._storage.config.enabled;
  1438. }
  1439. getLevel() {
  1440. return this._storage.config.level;
  1441. }
  1442. getTotal() {
  1443. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1444. }
  1445. getDelta() {
  1446. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1447. }
  1448. set priority(newPriority) {
  1449. this.level = newPriority;
  1450. }
  1451. get priority() {
  1452. return this.level;
  1453. }
  1454. getPriority() {
  1455. return this.level;
  1456. }
  1457. enable() {
  1458. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1459. this._storage.updateConfiguration({
  1460. enabled
  1461. });
  1462. return this;
  1463. }
  1464. setLevel(level) {
  1465. this._storage.updateConfiguration({
  1466. level
  1467. });
  1468. return this;
  1469. }
  1470. get(setting) {
  1471. return this._storage.config[setting];
  1472. }
  1473. set(setting, value) {
  1474. this._storage.updateConfiguration({
  1475. [setting]: value
  1476. });
  1477. }
  1478. settings() {
  1479. if (console.table) {
  1480. console.table(this._storage.config);
  1481. } else {
  1482. console.log(this._storage.config);
  1483. }
  1484. }
  1485. assert(condition, message) {
  1486. assert$5(condition, message);
  1487. }
  1488. warn(message) {
  1489. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1490. }
  1491. error(message) {
  1492. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1493. }
  1494. deprecated(oldUsage, newUsage) {
  1495. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1496. }
  1497. removed(oldUsage, newUsage) {
  1498. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1499. }
  1500. probe(logLevel, message) {
  1501. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1502. time: true,
  1503. once: true
  1504. });
  1505. }
  1506. log(logLevel, message) {
  1507. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1508. }
  1509. info(logLevel, message) {
  1510. return this._getLogFunction(logLevel, message, console.info, arguments);
  1511. }
  1512. once(logLevel, message) {
  1513. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1514. args[_key - 2] = arguments[_key];
  1515. }
  1516. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1517. }
  1518. table(logLevel, table, columns) {
  1519. if (table) {
  1520. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1521. tag: getTableHeader(table)
  1522. });
  1523. }
  1524. return noop$1;
  1525. }
  1526. image(_ref) {
  1527. let {
  1528. logLevel,
  1529. priority,
  1530. image,
  1531. message = '',
  1532. scale = 1
  1533. } = _ref;
  1534. if (!this._shouldLog(logLevel || priority)) {
  1535. return noop$1;
  1536. }
  1537. return isBrowser ? logImageInBrowser({
  1538. image,
  1539. message,
  1540. scale
  1541. }) : logImageInNode({
  1542. image,
  1543. message,
  1544. scale
  1545. });
  1546. }
  1547. time(logLevel, message) {
  1548. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1549. }
  1550. timeEnd(logLevel, message) {
  1551. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1552. }
  1553. timeStamp(logLevel, message) {
  1554. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1555. }
  1556. group(logLevel, message) {
  1557. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1558. collapsed: false
  1559. };
  1560. const options = normalizeArguments({
  1561. logLevel,
  1562. message,
  1563. opts
  1564. });
  1565. const {
  1566. collapsed
  1567. } = opts;
  1568. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1569. return this._getLogFunction(options);
  1570. }
  1571. groupCollapsed(logLevel, message) {
  1572. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1573. return this.group(logLevel, message, Object.assign({}, opts, {
  1574. collapsed: true
  1575. }));
  1576. }
  1577. groupEnd(logLevel) {
  1578. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1579. }
  1580. withGroup(logLevel, message, func) {
  1581. this.group(logLevel, message)();
  1582. try {
  1583. func();
  1584. } finally {
  1585. this.groupEnd(logLevel)();
  1586. }
  1587. }
  1588. trace() {
  1589. if (console.trace) {
  1590. console.trace();
  1591. }
  1592. }
  1593. _shouldLog(logLevel) {
  1594. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1595. }
  1596. _getLogFunction(logLevel, message, method, args, opts) {
  1597. if (this._shouldLog(logLevel)) {
  1598. opts = normalizeArguments({
  1599. logLevel,
  1600. message,
  1601. args,
  1602. opts
  1603. });
  1604. method = method || opts.method;
  1605. assert$5(method);
  1606. opts.total = this.getTotal();
  1607. opts.delta = this.getDelta();
  1608. this._deltaTs = getHiResTimestamp();
  1609. const tag = opts.tag || opts.message;
  1610. if (opts.once) {
  1611. if (!cache[tag]) {
  1612. cache[tag] = getHiResTimestamp();
  1613. } else {
  1614. return noop$1;
  1615. }
  1616. }
  1617. message = decorateMessage(this.id, opts.message, opts);
  1618. return method.bind(console, message, ...opts.args);
  1619. }
  1620. return noop$1;
  1621. }
  1622. }
  1623. _defineProperty(Log, "VERSION", VERSION$6);
  1624. function normalizeLogLevel(logLevel) {
  1625. if (!logLevel) {
  1626. return 0;
  1627. }
  1628. let resolvedLevel;
  1629. switch (typeof logLevel) {
  1630. case 'number':
  1631. resolvedLevel = logLevel;
  1632. break;
  1633. case 'object':
  1634. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1635. break;
  1636. default:
  1637. return 0;
  1638. }
  1639. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1640. return resolvedLevel;
  1641. }
  1642. function normalizeArguments(opts) {
  1643. const {
  1644. logLevel,
  1645. message
  1646. } = opts;
  1647. opts.logLevel = normalizeLogLevel(logLevel);
  1648. const args = opts.args ? Array.from(opts.args) : [];
  1649. while (args.length && args.shift() !== message) {}
  1650. switch (typeof logLevel) {
  1651. case 'string':
  1652. case 'function':
  1653. if (message !== undefined) {
  1654. args.unshift(message);
  1655. }
  1656. opts.message = logLevel;
  1657. break;
  1658. case 'object':
  1659. Object.assign(opts, logLevel);
  1660. break;
  1661. }
  1662. if (typeof opts.message === 'function') {
  1663. opts.message = opts.message();
  1664. }
  1665. const messageType = typeof opts.message;
  1666. assert$5(messageType === 'string' || messageType === 'object');
  1667. return Object.assign(opts, {
  1668. args
  1669. }, opts.opts);
  1670. }
  1671. function decorateMessage(id, message, opts) {
  1672. if (typeof message === 'string') {
  1673. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1674. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1675. message = addColor(message, opts.color, opts.background);
  1676. }
  1677. return message;
  1678. }
  1679. function logImageInNode(_ref2) {
  1680. let {
  1681. image,
  1682. message = '',
  1683. scale = 1
  1684. } = _ref2;
  1685. let asciify = null;
  1686. try {
  1687. asciify = module.require('asciify-image');
  1688. } catch (error) {}
  1689. if (asciify) {
  1690. return () => asciify(image, {
  1691. fit: 'box',
  1692. width: "".concat(Math.round(80 * scale), "%")
  1693. }).then(data => console.log(data));
  1694. }
  1695. return noop$1;
  1696. }
  1697. function logImageInBrowser(_ref3) {
  1698. let {
  1699. image,
  1700. message = '',
  1701. scale = 1
  1702. } = _ref3;
  1703. if (typeof image === 'string') {
  1704. const img = new Image();
  1705. img.onload = () => {
  1706. const args = formatImage(img, message, scale);
  1707. console.log(...args);
  1708. };
  1709. img.src = image;
  1710. return noop$1;
  1711. }
  1712. const element = image.nodeName || '';
  1713. if (element.toLowerCase() === 'img') {
  1714. console.log(...formatImage(image, message, scale));
  1715. return noop$1;
  1716. }
  1717. if (element.toLowerCase() === 'canvas') {
  1718. const img = new Image();
  1719. img.onload = () => console.log(...formatImage(img, message, scale));
  1720. img.src = image.toDataURL();
  1721. return noop$1;
  1722. }
  1723. return noop$1;
  1724. }
  1725. function getTableHeader(table) {
  1726. for (const key in table) {
  1727. for (const title in table[key]) {
  1728. return title || 'untitled';
  1729. }
  1730. }
  1731. return 'empty';
  1732. }
  1733. const probeLog = new Log({
  1734. id: 'loaders.gl'
  1735. });
  1736. class NullLog {
  1737. log() {
  1738. return () => {};
  1739. }
  1740. info() {
  1741. return () => {};
  1742. }
  1743. warn() {
  1744. return () => {};
  1745. }
  1746. error() {
  1747. return () => {};
  1748. }
  1749. }
  1750. class ConsoleLog {
  1751. constructor() {
  1752. _defineProperty(this, "console", void 0);
  1753. this.console = console;
  1754. }
  1755. log(...args) {
  1756. return this.console.log.bind(this.console, ...args);
  1757. }
  1758. info(...args) {
  1759. return this.console.info.bind(this.console, ...args);
  1760. }
  1761. warn(...args) {
  1762. return this.console.warn.bind(this.console, ...args);
  1763. }
  1764. error(...args) {
  1765. return this.console.error.bind(this.console, ...args);
  1766. }
  1767. }
  1768. const DEFAULT_LOADER_OPTIONS = {
  1769. fetch: null,
  1770. mimeType: undefined,
  1771. nothrow: false,
  1772. log: new ConsoleLog(),
  1773. CDN: 'https://unpkg.com/@loaders.gl',
  1774. worker: true,
  1775. maxConcurrency: 3,
  1776. maxMobileConcurrency: 1,
  1777. reuseWorkers: true,
  1778. _workerType: '',
  1779. limit: 0,
  1780. _limitMB: 0,
  1781. batchSize: 'auto',
  1782. batchDebounceMs: 0,
  1783. metadata: false,
  1784. transforms: []
  1785. };
  1786. const REMOVED_LOADER_OPTIONS = {
  1787. throws: 'nothrow',
  1788. dataType: '(no longer used)',
  1789. uri: 'baseUri',
  1790. method: 'fetch.method',
  1791. headers: 'fetch.headers',
  1792. body: 'fetch.body',
  1793. mode: 'fetch.mode',
  1794. credentials: 'fetch.credentials',
  1795. cache: 'fetch.cache',
  1796. redirect: 'fetch.redirect',
  1797. referrer: 'fetch.referrer',
  1798. referrerPolicy: 'fetch.referrerPolicy',
  1799. integrity: 'fetch.integrity',
  1800. keepalive: 'fetch.keepalive',
  1801. signal: 'fetch.signal'
  1802. };
  1803. function getGlobalLoaderState() {
  1804. globalThis.loaders = globalThis.loaders || {};
  1805. const {
  1806. loaders
  1807. } = globalThis;
  1808. loaders._state = loaders._state || {};
  1809. return loaders._state;
  1810. }
  1811. const getGlobalLoaderOptions = () => {
  1812. const state = getGlobalLoaderState();
  1813. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1814. };
  1815. return state.globalOptions;
  1816. };
  1817. function normalizeOptions(options, loader, loaders, url) {
  1818. loaders = loaders || [];
  1819. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1820. validateOptions(options, loaders);
  1821. return normalizeOptionsInternal(loader, options, url);
  1822. }
  1823. function getFetchFunction(options, context) {
  1824. const globalOptions = getGlobalLoaderOptions();
  1825. const fetchOptions = options || globalOptions;
  1826. if (typeof fetchOptions.fetch === 'function') {
  1827. return fetchOptions.fetch;
  1828. }
  1829. if (isObject(fetchOptions.fetch)) {
  1830. return url => fetchFile(url, fetchOptions);
  1831. }
  1832. if (context !== null && context !== void 0 && context.fetch) {
  1833. return context === null || context === void 0 ? void 0 : context.fetch;
  1834. }
  1835. return fetchFile;
  1836. }
  1837. function validateOptions(options, loaders) {
  1838. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1839. for (const loader of loaders) {
  1840. const idOptions = options && options[loader.id] || {};
  1841. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1842. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1843. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1844. }
  1845. }
  1846. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1847. const loaderName = id || 'Top level';
  1848. const prefix = id ? "".concat(id, ".") : '';
  1849. for (const key in options) {
  1850. const isSubOptions = !id && isObject(options[key]);
  1851. const isBaseUriOption = key === 'baseUri' && !id;
  1852. const isWorkerUrlOption = key === 'workerUrl' && id;
  1853. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1854. if (key in deprecatedOptions) {
  1855. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1856. } else if (!isSubOptions) {
  1857. const suggestion = findSimilarOption(key, loaders);
  1858. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1859. }
  1860. }
  1861. }
  1862. }
  1863. function findSimilarOption(optionKey, loaders) {
  1864. const lowerCaseOptionKey = optionKey.toLowerCase();
  1865. let bestSuggestion = '';
  1866. for (const loader of loaders) {
  1867. for (const key in loader.options) {
  1868. if (optionKey === key) {
  1869. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1870. }
  1871. const lowerCaseKey = key.toLowerCase();
  1872. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1873. if (isPartialMatch) {
  1874. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1875. }
  1876. }
  1877. }
  1878. return bestSuggestion;
  1879. }
  1880. function normalizeOptionsInternal(loader, options, url) {
  1881. const loaderDefaultOptions = loader.options || {};
  1882. const mergedOptions = { ...loaderDefaultOptions
  1883. };
  1884. addUrlOptions(mergedOptions, url);
  1885. if (mergedOptions.log === null) {
  1886. mergedOptions.log = new NullLog();
  1887. }
  1888. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1889. mergeNestedFields(mergedOptions, options);
  1890. return mergedOptions;
  1891. }
  1892. function mergeNestedFields(mergedOptions, options) {
  1893. for (const key in options) {
  1894. if (key in options) {
  1895. const value = options[key];
  1896. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1897. mergedOptions[key] = { ...mergedOptions[key],
  1898. ...options[key]
  1899. };
  1900. } else {
  1901. mergedOptions[key] = options[key];
  1902. }
  1903. }
  1904. }
  1905. }
  1906. function addUrlOptions(options, url) {
  1907. if (url && !('baseUri' in options)) {
  1908. options.baseUri = url;
  1909. }
  1910. }
  1911. function isLoaderObject(loader) {
  1912. var _loader;
  1913. if (!loader) {
  1914. return false;
  1915. }
  1916. if (Array.isArray(loader)) {
  1917. loader = loader[0];
  1918. }
  1919. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1920. return hasExtensions;
  1921. }
  1922. function normalizeLoader(loader) {
  1923. var _loader2, _loader3;
  1924. assert$7(loader, 'null loader');
  1925. assert$7(isLoaderObject(loader), 'invalid loader');
  1926. let options;
  1927. if (Array.isArray(loader)) {
  1928. options = loader[1];
  1929. loader = loader[0];
  1930. loader = { ...loader,
  1931. options: { ...loader.options,
  1932. ...options
  1933. }
  1934. };
  1935. }
  1936. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1937. loader.text = true;
  1938. }
  1939. if (!loader.text) {
  1940. loader.binary = true;
  1941. }
  1942. return loader;
  1943. }
  1944. const getGlobalLoaderRegistry = () => {
  1945. const state = getGlobalLoaderState();
  1946. state.loaderRegistry = state.loaderRegistry || [];
  1947. return state.loaderRegistry;
  1948. };
  1949. function getRegisteredLoaders() {
  1950. return getGlobalLoaderRegistry();
  1951. }
  1952. const EXT_PATTERN = /\.([^.]+)$/;
  1953. async function selectLoader(data, loaders = [], options, context) {
  1954. if (!validHTTPResponse(data)) {
  1955. return null;
  1956. }
  1957. let loader = selectLoaderSync(data, loaders, { ...options,
  1958. nothrow: true
  1959. }, context);
  1960. if (loader) {
  1961. return loader;
  1962. }
  1963. if (isBlob(data)) {
  1964. data = await data.slice(0, 10).arrayBuffer();
  1965. loader = selectLoaderSync(data, loaders, options, context);
  1966. }
  1967. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1968. throw new Error(getNoValidLoaderMessage(data));
  1969. }
  1970. return loader;
  1971. }
  1972. function selectLoaderSync(data, loaders = [], options, context) {
  1973. if (!validHTTPResponse(data)) {
  1974. return null;
  1975. }
  1976. if (loaders && !Array.isArray(loaders)) {
  1977. return normalizeLoader(loaders);
  1978. }
  1979. let candidateLoaders = [];
  1980. if (loaders) {
  1981. candidateLoaders = candidateLoaders.concat(loaders);
  1982. }
  1983. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1984. candidateLoaders.push(...getRegisteredLoaders());
  1985. }
  1986. normalizeLoaders(candidateLoaders);
  1987. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1988. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1989. throw new Error(getNoValidLoaderMessage(data));
  1990. }
  1991. return loader;
  1992. }
  1993. function selectLoaderInternal(data, loaders, options, context) {
  1994. const {
  1995. url,
  1996. type
  1997. } = getResourceUrlAndType(data);
  1998. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1999. let loader = null;
  2000. if (options !== null && options !== void 0 && options.mimeType) {
  2001. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  2002. }
  2003. loader = loader || findLoaderByUrl(loaders, testUrl);
  2004. loader = loader || findLoaderByMIMEType(loaders, type);
  2005. loader = loader || findLoaderByInitialBytes(loaders, data);
  2006. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  2007. return loader;
  2008. }
  2009. function validHTTPResponse(data) {
  2010. if (data instanceof Response) {
  2011. if (data.status === 204) {
  2012. return false;
  2013. }
  2014. }
  2015. return true;
  2016. }
  2017. function getNoValidLoaderMessage(data) {
  2018. const {
  2019. url,
  2020. type
  2021. } = getResourceUrlAndType(data);
  2022. let message = 'No valid loader found (';
  2023. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2024. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2025. const firstCharacters = data ? getFirstCharacters(data) : '';
  2026. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2027. message += ')';
  2028. return message;
  2029. }
  2030. function normalizeLoaders(loaders) {
  2031. for (const loader of loaders) {
  2032. normalizeLoader(loader);
  2033. }
  2034. }
  2035. function findLoaderByUrl(loaders, url) {
  2036. const match = url && EXT_PATTERN.exec(url);
  2037. const extension = match && match[1];
  2038. return extension ? findLoaderByExtension(loaders, extension) : null;
  2039. }
  2040. function findLoaderByExtension(loaders, extension) {
  2041. extension = extension.toLowerCase();
  2042. for (const loader of loaders) {
  2043. for (const loaderExtension of loader.extensions) {
  2044. if (loaderExtension.toLowerCase() === extension) {
  2045. return loader;
  2046. }
  2047. }
  2048. }
  2049. return null;
  2050. }
  2051. function findLoaderByMIMEType(loaders, mimeType) {
  2052. for (const loader of loaders) {
  2053. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2054. return loader;
  2055. }
  2056. if (mimeType === "application/x.".concat(loader.id)) {
  2057. return loader;
  2058. }
  2059. }
  2060. return null;
  2061. }
  2062. function findLoaderByInitialBytes(loaders, data) {
  2063. if (!data) {
  2064. return null;
  2065. }
  2066. for (const loader of loaders) {
  2067. if (typeof data === 'string') {
  2068. if (testDataAgainstText(data, loader)) {
  2069. return loader;
  2070. }
  2071. } else if (ArrayBuffer.isView(data)) {
  2072. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2073. return loader;
  2074. }
  2075. } else if (data instanceof ArrayBuffer) {
  2076. const byteOffset = 0;
  2077. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2078. return loader;
  2079. }
  2080. }
  2081. }
  2082. return null;
  2083. }
  2084. function testDataAgainstText(data, loader) {
  2085. if (loader.testText) {
  2086. return loader.testText(data);
  2087. }
  2088. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2089. return tests.some(test => data.startsWith(test));
  2090. }
  2091. function testDataAgainstBinary(data, byteOffset, loader) {
  2092. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2093. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2094. }
  2095. function testBinary(data, byteOffset, loader, test) {
  2096. if (test instanceof ArrayBuffer) {
  2097. return compareArrayBuffers(test, data, test.byteLength);
  2098. }
  2099. switch (typeof test) {
  2100. case 'function':
  2101. return test(data, loader);
  2102. case 'string':
  2103. const magic = getMagicString$2(data, byteOffset, test.length);
  2104. return test === magic;
  2105. default:
  2106. return false;
  2107. }
  2108. }
  2109. function getFirstCharacters(data, length = 5) {
  2110. if (typeof data === 'string') {
  2111. return data.slice(0, length);
  2112. } else if (ArrayBuffer.isView(data)) {
  2113. return getMagicString$2(data.buffer, data.byteOffset, length);
  2114. } else if (data instanceof ArrayBuffer) {
  2115. const byteOffset = 0;
  2116. return getMagicString$2(data, byteOffset, length);
  2117. }
  2118. return '';
  2119. }
  2120. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2121. if (arrayBuffer.byteLength < byteOffset + length) {
  2122. return '';
  2123. }
  2124. const dataView = new DataView(arrayBuffer);
  2125. let magic = '';
  2126. for (let i = 0; i < length; i++) {
  2127. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2128. }
  2129. return magic;
  2130. }
  2131. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2132. function* makeStringIterator(string, options) {
  2133. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2134. let offset = 0;
  2135. const textEncoder = new TextEncoder();
  2136. while (offset < string.length) {
  2137. const chunkLength = Math.min(string.length - offset, chunkSize);
  2138. const chunk = string.slice(offset, offset + chunkLength);
  2139. offset += chunkLength;
  2140. yield textEncoder.encode(chunk);
  2141. }
  2142. }
  2143. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2144. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2145. const {
  2146. chunkSize = DEFAULT_CHUNK_SIZE$1
  2147. } = options;
  2148. let byteOffset = 0;
  2149. while (byteOffset < arrayBuffer.byteLength) {
  2150. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2151. const chunk = new ArrayBuffer(chunkByteLength);
  2152. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2153. const chunkArray = new Uint8Array(chunk);
  2154. chunkArray.set(sourceArray);
  2155. byteOffset += chunkByteLength;
  2156. yield chunk;
  2157. }
  2158. }
  2159. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2160. async function* makeBlobIterator(blob, options) {
  2161. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2162. let offset = 0;
  2163. while (offset < blob.size) {
  2164. const end = offset + chunkSize;
  2165. const chunk = await blob.slice(offset, end).arrayBuffer();
  2166. offset = end;
  2167. yield chunk;
  2168. }
  2169. }
  2170. function makeStreamIterator(stream, options) {
  2171. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2172. }
  2173. async function* makeBrowserStreamIterator(stream, options) {
  2174. const reader = stream.getReader();
  2175. let nextBatchPromise;
  2176. try {
  2177. while (true) {
  2178. const currentBatchPromise = nextBatchPromise || reader.read();
  2179. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2180. nextBatchPromise = reader.read();
  2181. }
  2182. const {
  2183. done,
  2184. value
  2185. } = await currentBatchPromise;
  2186. if (done) {
  2187. return;
  2188. }
  2189. yield toArrayBuffer(value);
  2190. }
  2191. } catch (error) {
  2192. reader.releaseLock();
  2193. }
  2194. }
  2195. async function* makeNodeStreamIterator(stream, options) {
  2196. for await (const chunk of stream) {
  2197. yield toArrayBuffer(chunk);
  2198. }
  2199. }
  2200. function makeIterator(data, options) {
  2201. if (typeof data === 'string') {
  2202. return makeStringIterator(data, options);
  2203. }
  2204. if (data instanceof ArrayBuffer) {
  2205. return makeArrayBufferIterator(data, options);
  2206. }
  2207. if (isBlob(data)) {
  2208. return makeBlobIterator(data, options);
  2209. }
  2210. if (isReadableStream(data)) {
  2211. return makeStreamIterator(data, options);
  2212. }
  2213. if (isResponse(data)) {
  2214. const response = data;
  2215. return makeStreamIterator(response.body, options);
  2216. }
  2217. throw new Error('makeIterator');
  2218. }
  2219. const ERR_DATA = 'Cannot convert supplied data type';
  2220. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2221. if (loader.text && typeof data === 'string') {
  2222. return data;
  2223. }
  2224. if (isBuffer(data)) {
  2225. data = data.buffer;
  2226. }
  2227. if (data instanceof ArrayBuffer) {
  2228. const arrayBuffer = data;
  2229. if (loader.text && !loader.binary) {
  2230. const textDecoder = new TextDecoder('utf8');
  2231. return textDecoder.decode(arrayBuffer);
  2232. }
  2233. return arrayBuffer;
  2234. }
  2235. if (ArrayBuffer.isView(data)) {
  2236. if (loader.text && !loader.binary) {
  2237. const textDecoder = new TextDecoder('utf8');
  2238. return textDecoder.decode(data);
  2239. }
  2240. let arrayBuffer = data.buffer;
  2241. const byteLength = data.byteLength || data.length;
  2242. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2243. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2244. }
  2245. return arrayBuffer;
  2246. }
  2247. throw new Error(ERR_DATA);
  2248. }
  2249. async function getArrayBufferOrStringFromData(data, loader, options) {
  2250. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2251. if (typeof data === 'string' || isArrayBuffer) {
  2252. return getArrayBufferOrStringFromDataSync(data, loader);
  2253. }
  2254. if (isBlob(data)) {
  2255. data = await makeResponse(data);
  2256. }
  2257. if (isResponse(data)) {
  2258. const response = data;
  2259. await checkResponse(response);
  2260. return loader.binary ? await response.arrayBuffer() : await response.text();
  2261. }
  2262. if (isReadableStream(data)) {
  2263. data = makeIterator(data, options);
  2264. }
  2265. if (isIterable(data) || isAsyncIterable(data)) {
  2266. return concatenateArrayBuffersAsync(data);
  2267. }
  2268. throw new Error(ERR_DATA);
  2269. }
  2270. function getLoaderContext(context, options, previousContext = null) {
  2271. if (previousContext) {
  2272. return previousContext;
  2273. }
  2274. const resolvedContext = {
  2275. fetch: getFetchFunction(options, context),
  2276. ...context
  2277. };
  2278. if (!Array.isArray(resolvedContext.loaders)) {
  2279. resolvedContext.loaders = null;
  2280. }
  2281. return resolvedContext;
  2282. }
  2283. function getLoadersFromContext(loaders, context) {
  2284. if (!context && loaders && !Array.isArray(loaders)) {
  2285. return loaders;
  2286. }
  2287. let candidateLoaders;
  2288. if (loaders) {
  2289. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2290. }
  2291. if (context && context.loaders) {
  2292. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2293. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2294. }
  2295. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2296. }
  2297. async function parse$3(data, loaders, options, context) {
  2298. assert$6(!context || typeof context === 'object');
  2299. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2300. context = undefined;
  2301. options = loaders;
  2302. loaders = undefined;
  2303. }
  2304. data = await data;
  2305. options = options || {};
  2306. const {
  2307. url
  2308. } = getResourceUrlAndType(data);
  2309. const typedLoaders = loaders;
  2310. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2311. const loader = await selectLoader(data, candidateLoaders, options);
  2312. if (!loader) {
  2313. return null;
  2314. }
  2315. options = normalizeOptions(options, loader, candidateLoaders, url);
  2316. context = getLoaderContext({
  2317. url,
  2318. parse: parse$3,
  2319. loaders: candidateLoaders
  2320. }, options, context);
  2321. return await parseWithLoader(loader, data, options, context);
  2322. }
  2323. async function parseWithLoader(loader, data, options, context) {
  2324. validateWorkerVersion(loader);
  2325. data = await getArrayBufferOrStringFromData(data, loader, options);
  2326. if (loader.parseTextSync && typeof data === 'string') {
  2327. options.dataType = 'text';
  2328. return loader.parseTextSync(data, options, context, loader);
  2329. }
  2330. if (canParseWithWorker(loader, options)) {
  2331. return await parseWithWorker(loader, data, options, context, parse$3);
  2332. }
  2333. if (loader.parseText && typeof data === 'string') {
  2334. return await loader.parseText(data, options, context, loader);
  2335. }
  2336. if (loader.parse) {
  2337. return await loader.parse(data, options, context, loader);
  2338. }
  2339. assert$6(!loader.parseSync);
  2340. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2341. }
  2342. async function load(url, loaders, options, context) {
  2343. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2344. options = loaders;
  2345. loaders = undefined;
  2346. }
  2347. const fetch = getFetchFunction(options);
  2348. let data = url;
  2349. if (typeof url === 'string') {
  2350. data = await fetch(url);
  2351. }
  2352. if (isBlob(url)) {
  2353. data = await fetch(url);
  2354. }
  2355. return await parse$3(data, loaders, options);
  2356. }
  2357. function assert$4(condition, message) {
  2358. if (!condition) {
  2359. throw new Error("math.gl assertion ".concat(message));
  2360. }
  2361. }
  2362. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2363. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2364. const config = {};
  2365. config.EPSILON = 1e-12;
  2366. config.debug = false;
  2367. config.precision = 4;
  2368. config.printTypes = false;
  2369. config.printDegrees = false;
  2370. config.printRowMajor = true;
  2371. function round(value) {
  2372. return Math.round(value / config.EPSILON) * config.EPSILON;
  2373. }
  2374. function formatValue(value, {
  2375. precision = config.precision || 4
  2376. } = {}) {
  2377. value = round(value);
  2378. return "".concat(parseFloat(value.toPrecision(precision)));
  2379. }
  2380. function isArray(value) {
  2381. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2382. }
  2383. function duplicateArray(array) {
  2384. return array.clone ? array.clone() : new Array(array.length);
  2385. }
  2386. function map$1(value, func, result) {
  2387. if (isArray(value)) {
  2388. result = result || duplicateArray(value);
  2389. for (let i = 0; i < result.length && i < value.length; ++i) {
  2390. result[i] = func(value[i], i, result);
  2391. }
  2392. return result;
  2393. }
  2394. return func(value);
  2395. }
  2396. function toRadians(degrees) {
  2397. return radians(degrees);
  2398. }
  2399. function toDegrees(radians) {
  2400. return degrees(radians);
  2401. }
  2402. function radians(degrees, result) {
  2403. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2404. }
  2405. function degrees(radians, result) {
  2406. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2407. }
  2408. function clamp(value, min, max) {
  2409. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2410. }
  2411. function equals(a, b, epsilon) {
  2412. const oldEpsilon = config.EPSILON;
  2413. if (epsilon) {
  2414. config.EPSILON = epsilon;
  2415. }
  2416. try {
  2417. if (a === b) {
  2418. return true;
  2419. }
  2420. if (isArray(a) && isArray(b)) {
  2421. if (a.length !== b.length) {
  2422. return false;
  2423. }
  2424. for (let i = 0; i < a.length; ++i) {
  2425. if (!equals(a[i], b[i])) {
  2426. return false;
  2427. }
  2428. }
  2429. return true;
  2430. }
  2431. if (a && a.equals) {
  2432. return a.equals(b);
  2433. }
  2434. if (b && b.equals) {
  2435. return b.equals(a);
  2436. }
  2437. if (Number.isFinite(a) && Number.isFinite(b)) {
  2438. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2439. }
  2440. return false;
  2441. } finally {
  2442. config.EPSILON = oldEpsilon;
  2443. }
  2444. }
  2445. function _extendableBuiltin(cls) {
  2446. function ExtendableBuiltin() {
  2447. var instance = Reflect.construct(cls, Array.from(arguments));
  2448. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2449. return instance;
  2450. }
  2451. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2452. constructor: {
  2453. value: cls,
  2454. enumerable: false,
  2455. writable: true,
  2456. configurable: true
  2457. }
  2458. });
  2459. if (Object.setPrototypeOf) {
  2460. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2461. } else {
  2462. ExtendableBuiltin.__proto__ = cls;
  2463. }
  2464. return ExtendableBuiltin;
  2465. }
  2466. class MathArray extends _extendableBuiltin(Array) {
  2467. get ELEMENTS() {
  2468. assert$4(false);
  2469. return 0;
  2470. }
  2471. clone() {
  2472. return new this.constructor().copy(this);
  2473. }
  2474. from(arrayOrObject) {
  2475. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2476. }
  2477. fromArray(array, offset = 0) {
  2478. for (let i = 0; i < this.ELEMENTS; ++i) {
  2479. this[i] = array[i + offset];
  2480. }
  2481. return this.check();
  2482. }
  2483. to(arrayOrObject) {
  2484. if (arrayOrObject === this) {
  2485. return this;
  2486. }
  2487. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2488. }
  2489. toTarget(target) {
  2490. return target ? this.to(target) : this;
  2491. }
  2492. toArray(array = [], offset = 0) {
  2493. for (let i = 0; i < this.ELEMENTS; ++i) {
  2494. array[offset + i] = this[i];
  2495. }
  2496. return array;
  2497. }
  2498. toFloat32Array() {
  2499. return new Float32Array(this);
  2500. }
  2501. toString() {
  2502. return this.formatString(config);
  2503. }
  2504. formatString(opts) {
  2505. let string = '';
  2506. for (let i = 0; i < this.ELEMENTS; ++i) {
  2507. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2508. }
  2509. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2510. }
  2511. equals(array) {
  2512. if (!array || this.length !== array.length) {
  2513. return false;
  2514. }
  2515. for (let i = 0; i < this.ELEMENTS; ++i) {
  2516. if (!equals(this[i], array[i])) {
  2517. return false;
  2518. }
  2519. }
  2520. return true;
  2521. }
  2522. exactEquals(array) {
  2523. if (!array || this.length !== array.length) {
  2524. return false;
  2525. }
  2526. for (let i = 0; i < this.ELEMENTS; ++i) {
  2527. if (this[i] !== array[i]) {
  2528. return false;
  2529. }
  2530. }
  2531. return true;
  2532. }
  2533. negate() {
  2534. for (let i = 0; i < this.ELEMENTS; ++i) {
  2535. this[i] = -this[i];
  2536. }
  2537. return this.check();
  2538. }
  2539. lerp(a, b, t) {
  2540. if (t === undefined) {
  2541. t = b;
  2542. b = a;
  2543. a = this;
  2544. }
  2545. for (let i = 0; i < this.ELEMENTS; ++i) {
  2546. const ai = a[i];
  2547. this[i] = ai + t * (b[i] - ai);
  2548. }
  2549. return this.check();
  2550. }
  2551. min(vector) {
  2552. for (let i = 0; i < this.ELEMENTS; ++i) {
  2553. this[i] = Math.min(vector[i], this[i]);
  2554. }
  2555. return this.check();
  2556. }
  2557. max(vector) {
  2558. for (let i = 0; i < this.ELEMENTS; ++i) {
  2559. this[i] = Math.max(vector[i], this[i]);
  2560. }
  2561. return this.check();
  2562. }
  2563. clamp(minVector, maxVector) {
  2564. for (let i = 0; i < this.ELEMENTS; ++i) {
  2565. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2566. }
  2567. return this.check();
  2568. }
  2569. add(...vectors) {
  2570. for (const vector of vectors) {
  2571. for (let i = 0; i < this.ELEMENTS; ++i) {
  2572. this[i] += vector[i];
  2573. }
  2574. }
  2575. return this.check();
  2576. }
  2577. subtract(...vectors) {
  2578. for (const vector of vectors) {
  2579. for (let i = 0; i < this.ELEMENTS; ++i) {
  2580. this[i] -= vector[i];
  2581. }
  2582. }
  2583. return this.check();
  2584. }
  2585. scale(scale) {
  2586. if (Array.isArray(scale)) {
  2587. return this.multiply(scale);
  2588. }
  2589. for (let i = 0; i < this.ELEMENTS; ++i) {
  2590. this[i] *= scale;
  2591. }
  2592. return this.check();
  2593. }
  2594. sub(a) {
  2595. return this.subtract(a);
  2596. }
  2597. setScalar(a) {
  2598. for (let i = 0; i < this.ELEMENTS; ++i) {
  2599. this[i] = a;
  2600. }
  2601. return this.check();
  2602. }
  2603. addScalar(a) {
  2604. for (let i = 0; i < this.ELEMENTS; ++i) {
  2605. this[i] += a;
  2606. }
  2607. return this.check();
  2608. }
  2609. subScalar(a) {
  2610. return this.addScalar(-a);
  2611. }
  2612. multiplyScalar(scalar) {
  2613. for (let i = 0; i < this.ELEMENTS; ++i) {
  2614. this[i] *= scalar;
  2615. }
  2616. return this.check();
  2617. }
  2618. divideScalar(a) {
  2619. return this.scale(1 / a);
  2620. }
  2621. clampScalar(min, max) {
  2622. for (let i = 0; i < this.ELEMENTS; ++i) {
  2623. this[i] = Math.min(Math.max(this[i], min), max);
  2624. }
  2625. return this.check();
  2626. }
  2627. multiplyByScalar(scalar) {
  2628. return this.scale(scalar);
  2629. }
  2630. get elements() {
  2631. return this;
  2632. }
  2633. check() {
  2634. if (config.debug && !this.validate()) {
  2635. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2636. }
  2637. return this;
  2638. }
  2639. validate() {
  2640. let valid = this.length === this.ELEMENTS;
  2641. for (let i = 0; i < this.ELEMENTS; ++i) {
  2642. valid = valid && Number.isFinite(this[i]);
  2643. }
  2644. return valid;
  2645. }
  2646. }
  2647. function validateVector(v, length) {
  2648. if (v.length !== length) {
  2649. return false;
  2650. }
  2651. for (let i = 0; i < v.length; ++i) {
  2652. if (!Number.isFinite(v[i])) {
  2653. return false;
  2654. }
  2655. }
  2656. return true;
  2657. }
  2658. function checkNumber(value) {
  2659. if (!Number.isFinite(value)) {
  2660. throw new Error("Invalid number ".concat(value));
  2661. }
  2662. return value;
  2663. }
  2664. function checkVector(v, length, callerName = '') {
  2665. if (config.debug && !validateVector(v, length)) {
  2666. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2667. }
  2668. return v;
  2669. }
  2670. const map = {};
  2671. function deprecated(method, version) {
  2672. if (!map[method]) {
  2673. map[method] = true;
  2674. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2675. }
  2676. }
  2677. class Vector extends MathArray {
  2678. get ELEMENTS() {
  2679. assert$4(false);
  2680. return 0;
  2681. }
  2682. copy(vector) {
  2683. assert$4(false);
  2684. return this;
  2685. }
  2686. get x() {
  2687. return this[0];
  2688. }
  2689. set x(value) {
  2690. this[0] = checkNumber(value);
  2691. }
  2692. get y() {
  2693. return this[1];
  2694. }
  2695. set y(value) {
  2696. this[1] = checkNumber(value);
  2697. }
  2698. len() {
  2699. return Math.sqrt(this.lengthSquared());
  2700. }
  2701. magnitude() {
  2702. return this.len();
  2703. }
  2704. lengthSquared() {
  2705. let length = 0;
  2706. for (let i = 0; i < this.ELEMENTS; ++i) {
  2707. length += this[i] * this[i];
  2708. }
  2709. return length;
  2710. }
  2711. magnitudeSquared() {
  2712. return this.lengthSquared();
  2713. }
  2714. distance(mathArray) {
  2715. return Math.sqrt(this.distanceSquared(mathArray));
  2716. }
  2717. distanceSquared(mathArray) {
  2718. let length = 0;
  2719. for (let i = 0; i < this.ELEMENTS; ++i) {
  2720. const dist = this[i] - mathArray[i];
  2721. length += dist * dist;
  2722. }
  2723. return checkNumber(length);
  2724. }
  2725. dot(mathArray) {
  2726. let product = 0;
  2727. for (let i = 0; i < this.ELEMENTS; ++i) {
  2728. product += this[i] * mathArray[i];
  2729. }
  2730. return checkNumber(product);
  2731. }
  2732. normalize() {
  2733. const length = this.magnitude();
  2734. if (length !== 0) {
  2735. for (let i = 0; i < this.ELEMENTS; ++i) {
  2736. this[i] /= length;
  2737. }
  2738. }
  2739. return this.check();
  2740. }
  2741. multiply(...vectors) {
  2742. for (const vector of vectors) {
  2743. for (let i = 0; i < this.ELEMENTS; ++i) {
  2744. this[i] *= vector[i];
  2745. }
  2746. }
  2747. return this.check();
  2748. }
  2749. divide(...vectors) {
  2750. for (const vector of vectors) {
  2751. for (let i = 0; i < this.ELEMENTS; ++i) {
  2752. this[i] /= vector[i];
  2753. }
  2754. }
  2755. return this.check();
  2756. }
  2757. lengthSq() {
  2758. return this.lengthSquared();
  2759. }
  2760. distanceTo(vector) {
  2761. return this.distance(vector);
  2762. }
  2763. distanceToSquared(vector) {
  2764. return this.distanceSquared(vector);
  2765. }
  2766. getComponent(i) {
  2767. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2768. return checkNumber(this[i]);
  2769. }
  2770. setComponent(i, value) {
  2771. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2772. this[i] = value;
  2773. return this.check();
  2774. }
  2775. addVectors(a, b) {
  2776. return this.copy(a).add(b);
  2777. }
  2778. subVectors(a, b) {
  2779. return this.copy(a).subtract(b);
  2780. }
  2781. multiplyVectors(a, b) {
  2782. return this.copy(a).multiply(b);
  2783. }
  2784. addScaledVector(a, b) {
  2785. return this.add(new this.constructor(a).multiplyScalar(b));
  2786. }
  2787. }
  2788. /**
  2789. * Common utilities
  2790. * @module glMatrix
  2791. */
  2792. // Configuration Constants
  2793. var EPSILON = 0.000001;
  2794. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2795. if (!Math.hypot) Math.hypot = function () {
  2796. var y = 0,
  2797. i = arguments.length;
  2798. while (i--) {
  2799. y += arguments[i] * arguments[i];
  2800. }
  2801. return Math.sqrt(y);
  2802. };
  2803. /**
  2804. * 2 Dimensional Vector
  2805. * @module vec2
  2806. */
  2807. /**
  2808. * Creates a new, empty vec2
  2809. *
  2810. * @returns {vec2} a new 2D vector
  2811. */
  2812. function create$4() {
  2813. var out = new ARRAY_TYPE(2);
  2814. if (ARRAY_TYPE != Float32Array) {
  2815. out[0] = 0;
  2816. out[1] = 0;
  2817. }
  2818. return out;
  2819. }
  2820. /**
  2821. * Transforms the vec2 with a mat2
  2822. *
  2823. * @param {vec2} out the receiving vector
  2824. * @param {ReadonlyVec2} a the vector to transform
  2825. * @param {ReadonlyMat2} m matrix to transform with
  2826. * @returns {vec2} out
  2827. */
  2828. function transformMat2(out, a, m) {
  2829. var x = a[0],
  2830. y = a[1];
  2831. out[0] = m[0] * x + m[2] * y;
  2832. out[1] = m[1] * x + m[3] * y;
  2833. return out;
  2834. }
  2835. /**
  2836. * Transforms the vec2 with a mat2d
  2837. *
  2838. * @param {vec2} out the receiving vector
  2839. * @param {ReadonlyVec2} a the vector to transform
  2840. * @param {ReadonlyMat2d} m matrix to transform with
  2841. * @returns {vec2} out
  2842. */
  2843. function transformMat2d(out, a, m) {
  2844. var x = a[0],
  2845. y = a[1];
  2846. out[0] = m[0] * x + m[2] * y + m[4];
  2847. out[1] = m[1] * x + m[3] * y + m[5];
  2848. return out;
  2849. }
  2850. /**
  2851. * Transforms the vec2 with a mat3
  2852. * 3rd vector component is implicitly '1'
  2853. *
  2854. * @param {vec2} out the receiving vector
  2855. * @param {ReadonlyVec2} a the vector to transform
  2856. * @param {ReadonlyMat3} m matrix to transform with
  2857. * @returns {vec2} out
  2858. */
  2859. function transformMat3$1(out, a, m) {
  2860. var x = a[0],
  2861. y = a[1];
  2862. out[0] = m[0] * x + m[3] * y + m[6];
  2863. out[1] = m[1] * x + m[4] * y + m[7];
  2864. return out;
  2865. }
  2866. /**
  2867. * Transforms the vec2 with a mat4
  2868. * 3rd vector component is implicitly '0'
  2869. * 4th vector component is implicitly '1'
  2870. *
  2871. * @param {vec2} out the receiving vector
  2872. * @param {ReadonlyVec2} a the vector to transform
  2873. * @param {ReadonlyMat4} m matrix to transform with
  2874. * @returns {vec2} out
  2875. */
  2876. function transformMat4$2(out, a, m) {
  2877. var x = a[0];
  2878. var y = a[1];
  2879. out[0] = m[0] * x + m[4] * y + m[12];
  2880. out[1] = m[1] * x + m[5] * y + m[13];
  2881. return out;
  2882. }
  2883. /**
  2884. * Perform some operation over an array of vec2s.
  2885. *
  2886. * @param {Array} a the array of vectors to iterate over
  2887. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2888. * @param {Number} offset Number of elements to skip at the beginning of the array
  2889. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2890. * @param {Function} fn Function to call for each vector in the array
  2891. * @param {Object} [arg] additional argument to pass to fn
  2892. * @returns {Array} a
  2893. * @function
  2894. */
  2895. (function () {
  2896. var vec = create$4();
  2897. return function (a, stride, offset, count, fn, arg) {
  2898. var i, l;
  2899. if (!stride) {
  2900. stride = 2;
  2901. }
  2902. if (!offset) {
  2903. offset = 0;
  2904. }
  2905. if (count) {
  2906. l = Math.min(count * stride + offset, a.length);
  2907. } else {
  2908. l = a.length;
  2909. }
  2910. for (i = offset; i < l; i += stride) {
  2911. vec[0] = a[i];
  2912. vec[1] = a[i + 1];
  2913. fn(vec, vec, arg);
  2914. a[i] = vec[0];
  2915. a[i + 1] = vec[1];
  2916. }
  2917. return a;
  2918. };
  2919. })();
  2920. function vec2_transformMat4AsVector(out, a, m) {
  2921. const x = a[0];
  2922. const y = a[1];
  2923. const w = m[3] * x + m[7] * y || 1.0;
  2924. out[0] = (m[0] * x + m[4] * y) / w;
  2925. out[1] = (m[1] * x + m[5] * y) / w;
  2926. return out;
  2927. }
  2928. function vec3_transformMat4AsVector(out, a, m) {
  2929. const x = a[0];
  2930. const y = a[1];
  2931. const z = a[2];
  2932. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2933. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2934. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2935. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2936. return out;
  2937. }
  2938. function vec3_transformMat2(out, a, m) {
  2939. const x = a[0];
  2940. const y = a[1];
  2941. out[0] = m[0] * x + m[2] * y;
  2942. out[1] = m[1] * x + m[3] * y;
  2943. out[2] = a[2];
  2944. return out;
  2945. }
  2946. function vec4_transformMat3(out, a, m) {
  2947. const x = a[0];
  2948. const y = a[1];
  2949. const z = a[2];
  2950. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2951. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2952. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2953. out[3] = a[3];
  2954. return out;
  2955. }
  2956. class Vector2 extends Vector {
  2957. constructor(x = 0, y = 0) {
  2958. super(2);
  2959. if (isArray(x) && arguments.length === 1) {
  2960. this.copy(x);
  2961. } else {
  2962. if (config.debug) {
  2963. checkNumber(x);
  2964. checkNumber(y);
  2965. }
  2966. this[0] = x;
  2967. this[1] = y;
  2968. }
  2969. }
  2970. set(x, y) {
  2971. this[0] = x;
  2972. this[1] = y;
  2973. return this.check();
  2974. }
  2975. copy(array) {
  2976. this[0] = array[0];
  2977. this[1] = array[1];
  2978. return this.check();
  2979. }
  2980. fromObject(object) {
  2981. if (config.debug) {
  2982. checkNumber(object.x);
  2983. checkNumber(object.y);
  2984. }
  2985. this[0] = object.x;
  2986. this[1] = object.y;
  2987. return this.check();
  2988. }
  2989. toObject(object) {
  2990. object.x = this[0];
  2991. object.y = this[1];
  2992. return object;
  2993. }
  2994. get ELEMENTS() {
  2995. return 2;
  2996. }
  2997. horizontalAngle() {
  2998. return Math.atan2(this.y, this.x);
  2999. }
  3000. verticalAngle() {
  3001. return Math.atan2(this.x, this.y);
  3002. }
  3003. transform(matrix4) {
  3004. return this.transformAsPoint(matrix4);
  3005. }
  3006. transformAsPoint(matrix4) {
  3007. transformMat4$2(this, this, matrix4);
  3008. return this.check();
  3009. }
  3010. transformAsVector(matrix4) {
  3011. vec2_transformMat4AsVector(this, this, matrix4);
  3012. return this.check();
  3013. }
  3014. transformByMatrix3(matrix3) {
  3015. transformMat3$1(this, this, matrix3);
  3016. return this.check();
  3017. }
  3018. transformByMatrix2x3(matrix2x3) {
  3019. transformMat2d(this, this, matrix2x3);
  3020. return this.check();
  3021. }
  3022. transformByMatrix2(matrix2) {
  3023. transformMat2(this, this, matrix2);
  3024. return this.check();
  3025. }
  3026. }
  3027. /**
  3028. * 3 Dimensional Vector
  3029. * @module vec3
  3030. */
  3031. /**
  3032. * Creates a new, empty vec3
  3033. *
  3034. * @returns {vec3} a new 3D vector
  3035. */
  3036. function create$3() {
  3037. var out = new ARRAY_TYPE(3);
  3038. if (ARRAY_TYPE != Float32Array) {
  3039. out[0] = 0;
  3040. out[1] = 0;
  3041. out[2] = 0;
  3042. }
  3043. return out;
  3044. }
  3045. /**
  3046. * Calculates the length of a vec3
  3047. *
  3048. * @param {ReadonlyVec3} a vector to calculate length of
  3049. * @returns {Number} length of a
  3050. */
  3051. function length$2(a) {
  3052. var x = a[0];
  3053. var y = a[1];
  3054. var z = a[2];
  3055. return Math.hypot(x, y, z);
  3056. }
  3057. /**
  3058. * Creates a new vec3 initialized with the given values
  3059. *
  3060. * @param {Number} x X component
  3061. * @param {Number} y Y component
  3062. * @param {Number} z Z component
  3063. * @returns {vec3} a new 3D vector
  3064. */
  3065. function fromValues(x, y, z) {
  3066. var out = new ARRAY_TYPE(3);
  3067. out[0] = x;
  3068. out[1] = y;
  3069. out[2] = z;
  3070. return out;
  3071. }
  3072. /**
  3073. * Normalize a vec3
  3074. *
  3075. * @param {vec3} out the receiving vector
  3076. * @param {ReadonlyVec3} a vector to normalize
  3077. * @returns {vec3} out
  3078. */
  3079. function normalize$2(out, a) {
  3080. var x = a[0];
  3081. var y = a[1];
  3082. var z = a[2];
  3083. var len = x * x + y * y + z * z;
  3084. if (len > 0) {
  3085. //TODO: evaluate use of glm_invsqrt here?
  3086. len = 1 / Math.sqrt(len);
  3087. }
  3088. out[0] = a[0] * len;
  3089. out[1] = a[1] * len;
  3090. out[2] = a[2] * len;
  3091. return out;
  3092. }
  3093. /**
  3094. * Calculates the dot product of two vec3's
  3095. *
  3096. * @param {ReadonlyVec3} a the first operand
  3097. * @param {ReadonlyVec3} b the second operand
  3098. * @returns {Number} dot product of a and b
  3099. */
  3100. function dot$2(a, b) {
  3101. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3102. }
  3103. /**
  3104. * Computes the cross product of two vec3's
  3105. *
  3106. * @param {vec3} out the receiving vector
  3107. * @param {ReadonlyVec3} a the first operand
  3108. * @param {ReadonlyVec3} b the second operand
  3109. * @returns {vec3} out
  3110. */
  3111. function cross(out, a, b) {
  3112. var ax = a[0],
  3113. ay = a[1],
  3114. az = a[2];
  3115. var bx = b[0],
  3116. by = b[1],
  3117. bz = b[2];
  3118. out[0] = ay * bz - az * by;
  3119. out[1] = az * bx - ax * bz;
  3120. out[2] = ax * by - ay * bx;
  3121. return out;
  3122. }
  3123. /**
  3124. * Transforms the vec3 with a mat4.
  3125. * 4th vector component is implicitly '1'
  3126. *
  3127. * @param {vec3} out the receiving vector
  3128. * @param {ReadonlyVec3} a the vector to transform
  3129. * @param {ReadonlyMat4} m matrix to transform with
  3130. * @returns {vec3} out
  3131. */
  3132. function transformMat4$1(out, a, m) {
  3133. var x = a[0],
  3134. y = a[1],
  3135. z = a[2];
  3136. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3137. w = w || 1.0;
  3138. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3139. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3140. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3141. return out;
  3142. }
  3143. /**
  3144. * Transforms the vec3 with a mat3.
  3145. *
  3146. * @param {vec3} out the receiving vector
  3147. * @param {ReadonlyVec3} a the vector to transform
  3148. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3149. * @returns {vec3} out
  3150. */
  3151. function transformMat3(out, a, m) {
  3152. var x = a[0],
  3153. y = a[1],
  3154. z = a[2];
  3155. out[0] = x * m[0] + y * m[3] + z * m[6];
  3156. out[1] = x * m[1] + y * m[4] + z * m[7];
  3157. out[2] = x * m[2] + y * m[5] + z * m[8];
  3158. return out;
  3159. }
  3160. /**
  3161. * Transforms the vec3 with a quat
  3162. * Can also be used for dual quaternions. (Multiply it with the real part)
  3163. *
  3164. * @param {vec3} out the receiving vector
  3165. * @param {ReadonlyVec3} a the vector to transform
  3166. * @param {ReadonlyQuat} q quaternion to transform with
  3167. * @returns {vec3} out
  3168. */
  3169. function transformQuat$1(out, a, q) {
  3170. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3171. var qx = q[0],
  3172. qy = q[1],
  3173. qz = q[2],
  3174. qw = q[3];
  3175. var x = a[0],
  3176. y = a[1],
  3177. z = a[2]; // var qvec = [qx, qy, qz];
  3178. // var uv = vec3.cross([], qvec, a);
  3179. var uvx = qy * z - qz * y,
  3180. uvy = qz * x - qx * z,
  3181. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3182. var uuvx = qy * uvz - qz * uvy,
  3183. uuvy = qz * uvx - qx * uvz,
  3184. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3185. var w2 = qw * 2;
  3186. uvx *= w2;
  3187. uvy *= w2;
  3188. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3189. uuvx *= 2;
  3190. uuvy *= 2;
  3191. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3192. out[0] = x + uvx + uuvx;
  3193. out[1] = y + uvy + uuvy;
  3194. out[2] = z + uvz + uuvz;
  3195. return out;
  3196. }
  3197. /**
  3198. * Rotate a 3D vector around the x-axis
  3199. * @param {vec3} out The receiving vec3
  3200. * @param {ReadonlyVec3} a The vec3 point to rotate
  3201. * @param {ReadonlyVec3} b The origin of the rotation
  3202. * @param {Number} rad The angle of rotation in radians
  3203. * @returns {vec3} out
  3204. */
  3205. function rotateX$2(out, a, b, rad) {
  3206. var p = [],
  3207. r = []; //Translate point to the origin
  3208. p[0] = a[0] - b[0];
  3209. p[1] = a[1] - b[1];
  3210. p[2] = a[2] - b[2]; //perform rotation
  3211. r[0] = p[0];
  3212. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3213. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3214. out[0] = r[0] + b[0];
  3215. out[1] = r[1] + b[1];
  3216. out[2] = r[2] + b[2];
  3217. return out;
  3218. }
  3219. /**
  3220. * Rotate a 3D vector around the y-axis
  3221. * @param {vec3} out The receiving vec3
  3222. * @param {ReadonlyVec3} a The vec3 point to rotate
  3223. * @param {ReadonlyVec3} b The origin of the rotation
  3224. * @param {Number} rad The angle of rotation in radians
  3225. * @returns {vec3} out
  3226. */
  3227. function rotateY$2(out, a, b, rad) {
  3228. var p = [],
  3229. r = []; //Translate point to the origin
  3230. p[0] = a[0] - b[0];
  3231. p[1] = a[1] - b[1];
  3232. p[2] = a[2] - b[2]; //perform rotation
  3233. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3234. r[1] = p[1];
  3235. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3236. out[0] = r[0] + b[0];
  3237. out[1] = r[1] + b[1];
  3238. out[2] = r[2] + b[2];
  3239. return out;
  3240. }
  3241. /**
  3242. * Rotate a 3D vector around the z-axis
  3243. * @param {vec3} out The receiving vec3
  3244. * @param {ReadonlyVec3} a The vec3 point to rotate
  3245. * @param {ReadonlyVec3} b The origin of the rotation
  3246. * @param {Number} rad The angle of rotation in radians
  3247. * @returns {vec3} out
  3248. */
  3249. function rotateZ$2(out, a, b, rad) {
  3250. var p = [],
  3251. r = []; //Translate point to the origin
  3252. p[0] = a[0] - b[0];
  3253. p[1] = a[1] - b[1];
  3254. p[2] = a[2] - b[2]; //perform rotation
  3255. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3256. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3257. r[2] = p[2]; //translate to correct position
  3258. out[0] = r[0] + b[0];
  3259. out[1] = r[1] + b[1];
  3260. out[2] = r[2] + b[2];
  3261. return out;
  3262. }
  3263. /**
  3264. * Get the angle between two 3D vectors
  3265. * @param {ReadonlyVec3} a The first operand
  3266. * @param {ReadonlyVec3} b The second operand
  3267. * @returns {Number} The angle in radians
  3268. */
  3269. function angle(a, b) {
  3270. var ax = a[0],
  3271. ay = a[1],
  3272. az = a[2],
  3273. bx = b[0],
  3274. by = b[1],
  3275. bz = b[2],
  3276. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3277. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3278. mag = mag1 * mag2,
  3279. cosine = mag && dot$2(a, b) / mag;
  3280. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3281. }
  3282. /**
  3283. * Alias for {@link vec3.length}
  3284. * @function
  3285. */
  3286. var len = length$2;
  3287. /**
  3288. * Perform some operation over an array of vec3s.
  3289. *
  3290. * @param {Array} a the array of vectors to iterate over
  3291. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3292. * @param {Number} offset Number of elements to skip at the beginning of the array
  3293. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3294. * @param {Function} fn Function to call for each vector in the array
  3295. * @param {Object} [arg] additional argument to pass to fn
  3296. * @returns {Array} a
  3297. * @function
  3298. */
  3299. (function () {
  3300. var vec = create$3();
  3301. return function (a, stride, offset, count, fn, arg) {
  3302. var i, l;
  3303. if (!stride) {
  3304. stride = 3;
  3305. }
  3306. if (!offset) {
  3307. offset = 0;
  3308. }
  3309. if (count) {
  3310. l = Math.min(count * stride + offset, a.length);
  3311. } else {
  3312. l = a.length;
  3313. }
  3314. for (i = offset; i < l; i += stride) {
  3315. vec[0] = a[i];
  3316. vec[1] = a[i + 1];
  3317. vec[2] = a[i + 2];
  3318. fn(vec, vec, arg);
  3319. a[i] = vec[0];
  3320. a[i + 1] = vec[1];
  3321. a[i + 2] = vec[2];
  3322. }
  3323. return a;
  3324. };
  3325. })();
  3326. const ORIGIN = [0, 0, 0];
  3327. const constants$2 = {};
  3328. class Vector3 extends Vector {
  3329. static get ZERO() {
  3330. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3331. }
  3332. constructor(x = 0, y = 0, z = 0) {
  3333. super(-0, -0, -0);
  3334. if (arguments.length === 1 && isArray(x)) {
  3335. this.copy(x);
  3336. } else {
  3337. if (config.debug) {
  3338. checkNumber(x);
  3339. checkNumber(y);
  3340. checkNumber(z);
  3341. }
  3342. this[0] = x;
  3343. this[1] = y;
  3344. this[2] = z;
  3345. }
  3346. }
  3347. set(x, y, z) {
  3348. this[0] = x;
  3349. this[1] = y;
  3350. this[2] = z;
  3351. return this.check();
  3352. }
  3353. copy(array) {
  3354. this[0] = array[0];
  3355. this[1] = array[1];
  3356. this[2] = array[2];
  3357. return this.check();
  3358. }
  3359. fromObject(object) {
  3360. if (config.debug) {
  3361. checkNumber(object.x);
  3362. checkNumber(object.y);
  3363. checkNumber(object.z);
  3364. }
  3365. this[0] = object.x;
  3366. this[1] = object.y;
  3367. this[2] = object.z;
  3368. return this.check();
  3369. }
  3370. toObject(object) {
  3371. object.x = this[0];
  3372. object.y = this[1];
  3373. object.z = this[2];
  3374. return object;
  3375. }
  3376. get ELEMENTS() {
  3377. return 3;
  3378. }
  3379. get z() {
  3380. return this[2];
  3381. }
  3382. set z(value) {
  3383. this[2] = checkNumber(value);
  3384. }
  3385. angle(vector) {
  3386. return angle(this, vector);
  3387. }
  3388. cross(vector) {
  3389. cross(this, this, vector);
  3390. return this.check();
  3391. }
  3392. rotateX({
  3393. radians,
  3394. origin = ORIGIN
  3395. }) {
  3396. rotateX$2(this, this, origin, radians);
  3397. return this.check();
  3398. }
  3399. rotateY({
  3400. radians,
  3401. origin = ORIGIN
  3402. }) {
  3403. rotateY$2(this, this, origin, radians);
  3404. return this.check();
  3405. }
  3406. rotateZ({
  3407. radians,
  3408. origin = ORIGIN
  3409. }) {
  3410. rotateZ$2(this, this, origin, radians);
  3411. return this.check();
  3412. }
  3413. transform(matrix4) {
  3414. return this.transformAsPoint(matrix4);
  3415. }
  3416. transformAsPoint(matrix4) {
  3417. transformMat4$1(this, this, matrix4);
  3418. return this.check();
  3419. }
  3420. transformAsVector(matrix4) {
  3421. vec3_transformMat4AsVector(this, this, matrix4);
  3422. return this.check();
  3423. }
  3424. transformByMatrix3(matrix3) {
  3425. transformMat3(this, this, matrix3);
  3426. return this.check();
  3427. }
  3428. transformByMatrix2(matrix2) {
  3429. vec3_transformMat2(this, this, matrix2);
  3430. return this.check();
  3431. }
  3432. transformByQuaternion(quaternion) {
  3433. transformQuat$1(this, this, quaternion);
  3434. return this.check();
  3435. }
  3436. }
  3437. class Matrix extends MathArray {
  3438. get ELEMENTS() {
  3439. assert$4(false);
  3440. return 0;
  3441. }
  3442. get RANK() {
  3443. assert$4(false);
  3444. return 0;
  3445. }
  3446. toString() {
  3447. let string = '[';
  3448. if (config.printRowMajor) {
  3449. string += 'row-major:';
  3450. for (let row = 0; row < this.RANK; ++row) {
  3451. for (let col = 0; col < this.RANK; ++col) {
  3452. string += " ".concat(this[col * this.RANK + row]);
  3453. }
  3454. }
  3455. } else {
  3456. string += 'column-major:';
  3457. for (let i = 0; i < this.ELEMENTS; ++i) {
  3458. string += " ".concat(this[i]);
  3459. }
  3460. }
  3461. string += ']';
  3462. return string;
  3463. }
  3464. getElementIndex(row, col) {
  3465. return col * this.RANK + row;
  3466. }
  3467. getElement(row, col) {
  3468. return this[col * this.RANK + row];
  3469. }
  3470. setElement(row, col, value) {
  3471. this[col * this.RANK + row] = checkNumber(value);
  3472. return this;
  3473. }
  3474. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3475. const firstIndex = columnIndex * this.RANK;
  3476. for (let i = 0; i < this.RANK; ++i) {
  3477. result[i] = this[firstIndex + i];
  3478. }
  3479. return result;
  3480. }
  3481. setColumn(columnIndex, columnVector) {
  3482. const firstIndex = columnIndex * this.RANK;
  3483. for (let i = 0; i < this.RANK; ++i) {
  3484. this[firstIndex + i] = columnVector[i];
  3485. }
  3486. return this;
  3487. }
  3488. }
  3489. /**
  3490. * 3x3 Matrix
  3491. * @module mat3
  3492. */
  3493. /**
  3494. * Creates a new identity mat3
  3495. *
  3496. * @returns {mat3} a new 3x3 matrix
  3497. */
  3498. function create$2() {
  3499. var out = new ARRAY_TYPE(9);
  3500. if (ARRAY_TYPE != Float32Array) {
  3501. out[1] = 0;
  3502. out[2] = 0;
  3503. out[3] = 0;
  3504. out[5] = 0;
  3505. out[6] = 0;
  3506. out[7] = 0;
  3507. }
  3508. out[0] = 1;
  3509. out[4] = 1;
  3510. out[8] = 1;
  3511. return out;
  3512. }
  3513. /**
  3514. * Transpose the values of a mat3
  3515. *
  3516. * @param {mat3} out the receiving matrix
  3517. * @param {ReadonlyMat3} a the source matrix
  3518. * @returns {mat3} out
  3519. */
  3520. function transpose$1(out, a) {
  3521. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3522. if (out === a) {
  3523. var a01 = a[1],
  3524. a02 = a[2],
  3525. a12 = a[5];
  3526. out[1] = a[3];
  3527. out[2] = a[6];
  3528. out[3] = a01;
  3529. out[5] = a[7];
  3530. out[6] = a02;
  3531. out[7] = a12;
  3532. } else {
  3533. out[0] = a[0];
  3534. out[1] = a[3];
  3535. out[2] = a[6];
  3536. out[3] = a[1];
  3537. out[4] = a[4];
  3538. out[5] = a[7];
  3539. out[6] = a[2];
  3540. out[7] = a[5];
  3541. out[8] = a[8];
  3542. }
  3543. return out;
  3544. }
  3545. /**
  3546. * Inverts a mat3
  3547. *
  3548. * @param {mat3} out the receiving matrix
  3549. * @param {ReadonlyMat3} a the source matrix
  3550. * @returns {mat3} out
  3551. */
  3552. function invert$2(out, a) {
  3553. var a00 = a[0],
  3554. a01 = a[1],
  3555. a02 = a[2];
  3556. var a10 = a[3],
  3557. a11 = a[4],
  3558. a12 = a[5];
  3559. var a20 = a[6],
  3560. a21 = a[7],
  3561. a22 = a[8];
  3562. var b01 = a22 * a11 - a12 * a21;
  3563. var b11 = -a22 * a10 + a12 * a20;
  3564. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3565. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3566. if (!det) {
  3567. return null;
  3568. }
  3569. det = 1.0 / det;
  3570. out[0] = b01 * det;
  3571. out[1] = (-a22 * a01 + a02 * a21) * det;
  3572. out[2] = (a12 * a01 - a02 * a11) * det;
  3573. out[3] = b11 * det;
  3574. out[4] = (a22 * a00 - a02 * a20) * det;
  3575. out[5] = (-a12 * a00 + a02 * a10) * det;
  3576. out[6] = b21 * det;
  3577. out[7] = (-a21 * a00 + a01 * a20) * det;
  3578. out[8] = (a11 * a00 - a01 * a10) * det;
  3579. return out;
  3580. }
  3581. /**
  3582. * Calculates the determinant of a mat3
  3583. *
  3584. * @param {ReadonlyMat3} a the source matrix
  3585. * @returns {Number} determinant of a
  3586. */
  3587. function determinant$1(a) {
  3588. var a00 = a[0],
  3589. a01 = a[1],
  3590. a02 = a[2];
  3591. var a10 = a[3],
  3592. a11 = a[4],
  3593. a12 = a[5];
  3594. var a20 = a[6],
  3595. a21 = a[7],
  3596. a22 = a[8];
  3597. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3598. }
  3599. /**
  3600. * Multiplies two mat3's
  3601. *
  3602. * @param {mat3} out the receiving matrix
  3603. * @param {ReadonlyMat3} a the first operand
  3604. * @param {ReadonlyMat3} b the second operand
  3605. * @returns {mat3} out
  3606. */
  3607. function multiply$2(out, a, b) {
  3608. var a00 = a[0],
  3609. a01 = a[1],
  3610. a02 = a[2];
  3611. var a10 = a[3],
  3612. a11 = a[4],
  3613. a12 = a[5];
  3614. var a20 = a[6],
  3615. a21 = a[7],
  3616. a22 = a[8];
  3617. var b00 = b[0],
  3618. b01 = b[1],
  3619. b02 = b[2];
  3620. var b10 = b[3],
  3621. b11 = b[4],
  3622. b12 = b[5];
  3623. var b20 = b[6],
  3624. b21 = b[7],
  3625. b22 = b[8];
  3626. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3627. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3628. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3629. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3630. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3631. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3632. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3633. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3634. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3635. return out;
  3636. }
  3637. /**
  3638. * Translate a mat3 by the given vector
  3639. *
  3640. * @param {mat3} out the receiving matrix
  3641. * @param {ReadonlyMat3} a the matrix to translate
  3642. * @param {ReadonlyVec2} v vector to translate by
  3643. * @returns {mat3} out
  3644. */
  3645. function translate$1(out, a, v) {
  3646. var a00 = a[0],
  3647. a01 = a[1],
  3648. a02 = a[2],
  3649. a10 = a[3],
  3650. a11 = a[4],
  3651. a12 = a[5],
  3652. a20 = a[6],
  3653. a21 = a[7],
  3654. a22 = a[8],
  3655. x = v[0],
  3656. y = v[1];
  3657. out[0] = a00;
  3658. out[1] = a01;
  3659. out[2] = a02;
  3660. out[3] = a10;
  3661. out[4] = a11;
  3662. out[5] = a12;
  3663. out[6] = x * a00 + y * a10 + a20;
  3664. out[7] = x * a01 + y * a11 + a21;
  3665. out[8] = x * a02 + y * a12 + a22;
  3666. return out;
  3667. }
  3668. /**
  3669. * Rotates a mat3 by the given angle
  3670. *
  3671. * @param {mat3} out the receiving matrix
  3672. * @param {ReadonlyMat3} a the matrix to rotate
  3673. * @param {Number} rad the angle to rotate the matrix by
  3674. * @returns {mat3} out
  3675. */
  3676. function rotate$1(out, a, rad) {
  3677. var a00 = a[0],
  3678. a01 = a[1],
  3679. a02 = a[2],
  3680. a10 = a[3],
  3681. a11 = a[4],
  3682. a12 = a[5],
  3683. a20 = a[6],
  3684. a21 = a[7],
  3685. a22 = a[8],
  3686. s = Math.sin(rad),
  3687. c = Math.cos(rad);
  3688. out[0] = c * a00 + s * a10;
  3689. out[1] = c * a01 + s * a11;
  3690. out[2] = c * a02 + s * a12;
  3691. out[3] = c * a10 - s * a00;
  3692. out[4] = c * a11 - s * a01;
  3693. out[5] = c * a12 - s * a02;
  3694. out[6] = a20;
  3695. out[7] = a21;
  3696. out[8] = a22;
  3697. return out;
  3698. }
  3699. /**
  3700. * Scales the mat3 by the dimensions in the given vec2
  3701. *
  3702. * @param {mat3} out the receiving matrix
  3703. * @param {ReadonlyMat3} a the matrix to rotate
  3704. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3705. * @returns {mat3} out
  3706. **/
  3707. function scale$3(out, a, v) {
  3708. var x = v[0],
  3709. y = v[1];
  3710. out[0] = x * a[0];
  3711. out[1] = x * a[1];
  3712. out[2] = x * a[2];
  3713. out[3] = y * a[3];
  3714. out[4] = y * a[4];
  3715. out[5] = y * a[5];
  3716. out[6] = a[6];
  3717. out[7] = a[7];
  3718. out[8] = a[8];
  3719. return out;
  3720. }
  3721. /**
  3722. * Calculates a 3x3 matrix from the given quaternion
  3723. *
  3724. * @param {mat3} out mat3 receiving operation result
  3725. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3726. *
  3727. * @returns {mat3} out
  3728. */
  3729. function fromQuat$1(out, q) {
  3730. var x = q[0],
  3731. y = q[1],
  3732. z = q[2],
  3733. w = q[3];
  3734. var x2 = x + x;
  3735. var y2 = y + y;
  3736. var z2 = z + z;
  3737. var xx = x * x2;
  3738. var yx = y * x2;
  3739. var yy = y * y2;
  3740. var zx = z * x2;
  3741. var zy = z * y2;
  3742. var zz = z * z2;
  3743. var wx = w * x2;
  3744. var wy = w * y2;
  3745. var wz = w * z2;
  3746. out[0] = 1 - yy - zz;
  3747. out[3] = yx - wz;
  3748. out[6] = zx + wy;
  3749. out[1] = yx + wz;
  3750. out[4] = 1 - xx - zz;
  3751. out[7] = zy - wx;
  3752. out[2] = zx - wy;
  3753. out[5] = zy + wx;
  3754. out[8] = 1 - xx - yy;
  3755. return out;
  3756. }
  3757. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3758. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3759. const INDICES$1 = Object.freeze({
  3760. COL0ROW0: 0,
  3761. COL0ROW1: 1,
  3762. COL0ROW2: 2,
  3763. COL1ROW0: 3,
  3764. COL1ROW1: 4,
  3765. COL1ROW2: 5,
  3766. COL2ROW0: 6,
  3767. COL2ROW1: 7,
  3768. COL2ROW2: 8
  3769. });
  3770. const constants$1 = {};
  3771. class Matrix3 extends Matrix {
  3772. static get IDENTITY() {
  3773. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3774. return constants$1.IDENTITY;
  3775. }
  3776. static get ZERO() {
  3777. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3778. return constants$1.ZERO;
  3779. }
  3780. get ELEMENTS() {
  3781. return 9;
  3782. }
  3783. get RANK() {
  3784. return 3;
  3785. }
  3786. get INDICES() {
  3787. return INDICES$1;
  3788. }
  3789. constructor(array) {
  3790. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3791. if (arguments.length === 1 && Array.isArray(array)) {
  3792. this.copy(array);
  3793. } else {
  3794. this.identity();
  3795. }
  3796. }
  3797. copy(array) {
  3798. this[0] = array[0];
  3799. this[1] = array[1];
  3800. this[2] = array[2];
  3801. this[3] = array[3];
  3802. this[4] = array[4];
  3803. this[5] = array[5];
  3804. this[6] = array[6];
  3805. this[7] = array[7];
  3806. this[8] = array[8];
  3807. return this.check();
  3808. }
  3809. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3810. this[0] = m00;
  3811. this[1] = m10;
  3812. this[2] = m20;
  3813. this[3] = m01;
  3814. this[4] = m11;
  3815. this[5] = m21;
  3816. this[6] = m02;
  3817. this[7] = m12;
  3818. this[8] = m22;
  3819. return this.check();
  3820. }
  3821. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3822. this[0] = m00;
  3823. this[1] = m10;
  3824. this[2] = m20;
  3825. this[3] = m01;
  3826. this[4] = m11;
  3827. this[5] = m21;
  3828. this[6] = m02;
  3829. this[7] = m12;
  3830. this[8] = m22;
  3831. return this.check();
  3832. }
  3833. determinant() {
  3834. return determinant$1(this);
  3835. }
  3836. identity() {
  3837. return this.copy(IDENTITY$1);
  3838. }
  3839. fromQuaternion(q) {
  3840. fromQuat$1(this, q);
  3841. return this.check();
  3842. }
  3843. transpose() {
  3844. transpose$1(this, this);
  3845. return this.check();
  3846. }
  3847. invert() {
  3848. invert$2(this, this);
  3849. return this.check();
  3850. }
  3851. multiplyLeft(a) {
  3852. multiply$2(this, a, this);
  3853. return this.check();
  3854. }
  3855. multiplyRight(a) {
  3856. multiply$2(this, this, a);
  3857. return this.check();
  3858. }
  3859. rotate(radians) {
  3860. rotate$1(this, this, radians);
  3861. return this.check();
  3862. }
  3863. scale(factor) {
  3864. if (Array.isArray(factor)) {
  3865. scale$3(this, this, factor);
  3866. } else {
  3867. scale$3(this, this, [factor, factor, factor]);
  3868. }
  3869. return this.check();
  3870. }
  3871. translate(vec) {
  3872. translate$1(this, this, vec);
  3873. return this.check();
  3874. }
  3875. transform(vector, result) {
  3876. switch (vector.length) {
  3877. case 2:
  3878. result = transformMat3$1(result || [-0, -0], vector, this);
  3879. break;
  3880. case 3:
  3881. result = transformMat3(result || [-0, -0, -0], vector, this);
  3882. break;
  3883. case 4:
  3884. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3885. break;
  3886. default:
  3887. throw new Error('Illegal vector');
  3888. }
  3889. checkVector(result, vector.length);
  3890. return result;
  3891. }
  3892. transformVector(vector, result) {
  3893. deprecated('Matrix3.transformVector');
  3894. return this.transform(vector, result);
  3895. }
  3896. transformVector2(vector, result) {
  3897. deprecated('Matrix3.transformVector');
  3898. return this.transform(vector, result);
  3899. }
  3900. transformVector3(vector, result) {
  3901. deprecated('Matrix3.transformVector');
  3902. return this.transform(vector, result);
  3903. }
  3904. }
  3905. /**
  3906. * Set a mat4 to the identity matrix
  3907. *
  3908. * @param {mat4} out the receiving matrix
  3909. * @returns {mat4} out
  3910. */
  3911. function identity$1(out) {
  3912. out[0] = 1;
  3913. out[1] = 0;
  3914. out[2] = 0;
  3915. out[3] = 0;
  3916. out[4] = 0;
  3917. out[5] = 1;
  3918. out[6] = 0;
  3919. out[7] = 0;
  3920. out[8] = 0;
  3921. out[9] = 0;
  3922. out[10] = 1;
  3923. out[11] = 0;
  3924. out[12] = 0;
  3925. out[13] = 0;
  3926. out[14] = 0;
  3927. out[15] = 1;
  3928. return out;
  3929. }
  3930. /**
  3931. * Transpose the values of a mat4
  3932. *
  3933. * @param {mat4} out the receiving matrix
  3934. * @param {ReadonlyMat4} a the source matrix
  3935. * @returns {mat4} out
  3936. */
  3937. function transpose(out, a) {
  3938. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3939. if (out === a) {
  3940. var a01 = a[1],
  3941. a02 = a[2],
  3942. a03 = a[3];
  3943. var a12 = a[6],
  3944. a13 = a[7];
  3945. var a23 = a[11];
  3946. out[1] = a[4];
  3947. out[2] = a[8];
  3948. out[3] = a[12];
  3949. out[4] = a01;
  3950. out[6] = a[9];
  3951. out[7] = a[13];
  3952. out[8] = a02;
  3953. out[9] = a12;
  3954. out[11] = a[14];
  3955. out[12] = a03;
  3956. out[13] = a13;
  3957. out[14] = a23;
  3958. } else {
  3959. out[0] = a[0];
  3960. out[1] = a[4];
  3961. out[2] = a[8];
  3962. out[3] = a[12];
  3963. out[4] = a[1];
  3964. out[5] = a[5];
  3965. out[6] = a[9];
  3966. out[7] = a[13];
  3967. out[8] = a[2];
  3968. out[9] = a[6];
  3969. out[10] = a[10];
  3970. out[11] = a[14];
  3971. out[12] = a[3];
  3972. out[13] = a[7];
  3973. out[14] = a[11];
  3974. out[15] = a[15];
  3975. }
  3976. return out;
  3977. }
  3978. /**
  3979. * Inverts a mat4
  3980. *
  3981. * @param {mat4} out the receiving matrix
  3982. * @param {ReadonlyMat4} a the source matrix
  3983. * @returns {mat4} out
  3984. */
  3985. function invert$1(out, a) {
  3986. var a00 = a[0],
  3987. a01 = a[1],
  3988. a02 = a[2],
  3989. a03 = a[3];
  3990. var a10 = a[4],
  3991. a11 = a[5],
  3992. a12 = a[6],
  3993. a13 = a[7];
  3994. var a20 = a[8],
  3995. a21 = a[9],
  3996. a22 = a[10],
  3997. a23 = a[11];
  3998. var a30 = a[12],
  3999. a31 = a[13],
  4000. a32 = a[14],
  4001. a33 = a[15];
  4002. var b00 = a00 * a11 - a01 * a10;
  4003. var b01 = a00 * a12 - a02 * a10;
  4004. var b02 = a00 * a13 - a03 * a10;
  4005. var b03 = a01 * a12 - a02 * a11;
  4006. var b04 = a01 * a13 - a03 * a11;
  4007. var b05 = a02 * a13 - a03 * a12;
  4008. var b06 = a20 * a31 - a21 * a30;
  4009. var b07 = a20 * a32 - a22 * a30;
  4010. var b08 = a20 * a33 - a23 * a30;
  4011. var b09 = a21 * a32 - a22 * a31;
  4012. var b10 = a21 * a33 - a23 * a31;
  4013. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4014. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4015. if (!det) {
  4016. return null;
  4017. }
  4018. det = 1.0 / det;
  4019. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  4020. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  4021. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4022. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4023. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4024. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4025. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4026. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4027. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4028. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4029. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4030. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4031. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4032. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4033. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4034. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4035. return out;
  4036. }
  4037. /**
  4038. * Calculates the determinant of a mat4
  4039. *
  4040. * @param {ReadonlyMat4} a the source matrix
  4041. * @returns {Number} determinant of a
  4042. */
  4043. function determinant(a) {
  4044. var a00 = a[0],
  4045. a01 = a[1],
  4046. a02 = a[2],
  4047. a03 = a[3];
  4048. var a10 = a[4],
  4049. a11 = a[5],
  4050. a12 = a[6],
  4051. a13 = a[7];
  4052. var a20 = a[8],
  4053. a21 = a[9],
  4054. a22 = a[10],
  4055. a23 = a[11];
  4056. var a30 = a[12],
  4057. a31 = a[13],
  4058. a32 = a[14],
  4059. a33 = a[15];
  4060. var b00 = a00 * a11 - a01 * a10;
  4061. var b01 = a00 * a12 - a02 * a10;
  4062. var b02 = a00 * a13 - a03 * a10;
  4063. var b03 = a01 * a12 - a02 * a11;
  4064. var b04 = a01 * a13 - a03 * a11;
  4065. var b05 = a02 * a13 - a03 * a12;
  4066. var b06 = a20 * a31 - a21 * a30;
  4067. var b07 = a20 * a32 - a22 * a30;
  4068. var b08 = a20 * a33 - a23 * a30;
  4069. var b09 = a21 * a32 - a22 * a31;
  4070. var b10 = a21 * a33 - a23 * a31;
  4071. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4072. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4073. }
  4074. /**
  4075. * Multiplies two mat4s
  4076. *
  4077. * @param {mat4} out the receiving matrix
  4078. * @param {ReadonlyMat4} a the first operand
  4079. * @param {ReadonlyMat4} b the second operand
  4080. * @returns {mat4} out
  4081. */
  4082. function multiply$1(out, a, b) {
  4083. var a00 = a[0],
  4084. a01 = a[1],
  4085. a02 = a[2],
  4086. a03 = a[3];
  4087. var a10 = a[4],
  4088. a11 = a[5],
  4089. a12 = a[6],
  4090. a13 = a[7];
  4091. var a20 = a[8],
  4092. a21 = a[9],
  4093. a22 = a[10],
  4094. a23 = a[11];
  4095. var a30 = a[12],
  4096. a31 = a[13],
  4097. a32 = a[14],
  4098. a33 = a[15]; // Cache only the current line of the second matrix
  4099. var b0 = b[0],
  4100. b1 = b[1],
  4101. b2 = b[2],
  4102. b3 = b[3];
  4103. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4104. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4105. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4106. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4107. b0 = b[4];
  4108. b1 = b[5];
  4109. b2 = b[6];
  4110. b3 = b[7];
  4111. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4112. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4113. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4114. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4115. b0 = b[8];
  4116. b1 = b[9];
  4117. b2 = b[10];
  4118. b3 = b[11];
  4119. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4120. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4121. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4122. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4123. b0 = b[12];
  4124. b1 = b[13];
  4125. b2 = b[14];
  4126. b3 = b[15];
  4127. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4128. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4129. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4130. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4131. return out;
  4132. }
  4133. /**
  4134. * Translate a mat4 by the given vector
  4135. *
  4136. * @param {mat4} out the receiving matrix
  4137. * @param {ReadonlyMat4} a the matrix to translate
  4138. * @param {ReadonlyVec3} v vector to translate by
  4139. * @returns {mat4} out
  4140. */
  4141. function translate(out, a, v) {
  4142. var x = v[0],
  4143. y = v[1],
  4144. z = v[2];
  4145. var a00, a01, a02, a03;
  4146. var a10, a11, a12, a13;
  4147. var a20, a21, a22, a23;
  4148. if (a === out) {
  4149. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4150. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4151. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4152. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4153. } else {
  4154. a00 = a[0];
  4155. a01 = a[1];
  4156. a02 = a[2];
  4157. a03 = a[3];
  4158. a10 = a[4];
  4159. a11 = a[5];
  4160. a12 = a[6];
  4161. a13 = a[7];
  4162. a20 = a[8];
  4163. a21 = a[9];
  4164. a22 = a[10];
  4165. a23 = a[11];
  4166. out[0] = a00;
  4167. out[1] = a01;
  4168. out[2] = a02;
  4169. out[3] = a03;
  4170. out[4] = a10;
  4171. out[5] = a11;
  4172. out[6] = a12;
  4173. out[7] = a13;
  4174. out[8] = a20;
  4175. out[9] = a21;
  4176. out[10] = a22;
  4177. out[11] = a23;
  4178. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4179. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4180. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4181. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4182. }
  4183. return out;
  4184. }
  4185. /**
  4186. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4187. *
  4188. * @param {mat4} out the receiving matrix
  4189. * @param {ReadonlyMat4} a the matrix to scale
  4190. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4191. * @returns {mat4} out
  4192. **/
  4193. function scale$2(out, a, v) {
  4194. var x = v[0],
  4195. y = v[1],
  4196. z = v[2];
  4197. out[0] = a[0] * x;
  4198. out[1] = a[1] * x;
  4199. out[2] = a[2] * x;
  4200. out[3] = a[3] * x;
  4201. out[4] = a[4] * y;
  4202. out[5] = a[5] * y;
  4203. out[6] = a[6] * y;
  4204. out[7] = a[7] * y;
  4205. out[8] = a[8] * z;
  4206. out[9] = a[9] * z;
  4207. out[10] = a[10] * z;
  4208. out[11] = a[11] * z;
  4209. out[12] = a[12];
  4210. out[13] = a[13];
  4211. out[14] = a[14];
  4212. out[15] = a[15];
  4213. return out;
  4214. }
  4215. /**
  4216. * Rotates a mat4 by the given angle around the given axis
  4217. *
  4218. * @param {mat4} out the receiving matrix
  4219. * @param {ReadonlyMat4} a the matrix to rotate
  4220. * @param {Number} rad the angle to rotate the matrix by
  4221. * @param {ReadonlyVec3} axis the axis to rotate around
  4222. * @returns {mat4} out
  4223. */
  4224. function rotate(out, a, rad, axis) {
  4225. var x = axis[0],
  4226. y = axis[1],
  4227. z = axis[2];
  4228. var len = Math.hypot(x, y, z);
  4229. var s, c, t;
  4230. var a00, a01, a02, a03;
  4231. var a10, a11, a12, a13;
  4232. var a20, a21, a22, a23;
  4233. var b00, b01, b02;
  4234. var b10, b11, b12;
  4235. var b20, b21, b22;
  4236. if (len < EPSILON) {
  4237. return null;
  4238. }
  4239. len = 1 / len;
  4240. x *= len;
  4241. y *= len;
  4242. z *= len;
  4243. s = Math.sin(rad);
  4244. c = Math.cos(rad);
  4245. t = 1 - c;
  4246. a00 = a[0];
  4247. a01 = a[1];
  4248. a02 = a[2];
  4249. a03 = a[3];
  4250. a10 = a[4];
  4251. a11 = a[5];
  4252. a12 = a[6];
  4253. a13 = a[7];
  4254. a20 = a[8];
  4255. a21 = a[9];
  4256. a22 = a[10];
  4257. a23 = a[11]; // Construct the elements of the rotation matrix
  4258. b00 = x * x * t + c;
  4259. b01 = y * x * t + z * s;
  4260. b02 = z * x * t - y * s;
  4261. b10 = x * y * t - z * s;
  4262. b11 = y * y * t + c;
  4263. b12 = z * y * t + x * s;
  4264. b20 = x * z * t + y * s;
  4265. b21 = y * z * t - x * s;
  4266. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4267. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4268. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4269. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4270. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4271. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4272. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4273. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4274. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4275. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4276. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4277. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4278. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4279. if (a !== out) {
  4280. // If the source and destination differ, copy the unchanged last row
  4281. out[12] = a[12];
  4282. out[13] = a[13];
  4283. out[14] = a[14];
  4284. out[15] = a[15];
  4285. }
  4286. return out;
  4287. }
  4288. /**
  4289. * Rotates a matrix by the given angle around the X axis
  4290. *
  4291. * @param {mat4} out the receiving matrix
  4292. * @param {ReadonlyMat4} a the matrix to rotate
  4293. * @param {Number} rad the angle to rotate the matrix by
  4294. * @returns {mat4} out
  4295. */
  4296. function rotateX$1(out, a, rad) {
  4297. var s = Math.sin(rad);
  4298. var c = Math.cos(rad);
  4299. var a10 = a[4];
  4300. var a11 = a[5];
  4301. var a12 = a[6];
  4302. var a13 = a[7];
  4303. var a20 = a[8];
  4304. var a21 = a[9];
  4305. var a22 = a[10];
  4306. var a23 = a[11];
  4307. if (a !== out) {
  4308. // If the source and destination differ, copy the unchanged rows
  4309. out[0] = a[0];
  4310. out[1] = a[1];
  4311. out[2] = a[2];
  4312. out[3] = a[3];
  4313. out[12] = a[12];
  4314. out[13] = a[13];
  4315. out[14] = a[14];
  4316. out[15] = a[15];
  4317. } // Perform axis-specific matrix multiplication
  4318. out[4] = a10 * c + a20 * s;
  4319. out[5] = a11 * c + a21 * s;
  4320. out[6] = a12 * c + a22 * s;
  4321. out[7] = a13 * c + a23 * s;
  4322. out[8] = a20 * c - a10 * s;
  4323. out[9] = a21 * c - a11 * s;
  4324. out[10] = a22 * c - a12 * s;
  4325. out[11] = a23 * c - a13 * s;
  4326. return out;
  4327. }
  4328. /**
  4329. * Rotates a matrix by the given angle around the Y axis
  4330. *
  4331. * @param {mat4} out the receiving matrix
  4332. * @param {ReadonlyMat4} a the matrix to rotate
  4333. * @param {Number} rad the angle to rotate the matrix by
  4334. * @returns {mat4} out
  4335. */
  4336. function rotateY$1(out, a, rad) {
  4337. var s = Math.sin(rad);
  4338. var c = Math.cos(rad);
  4339. var a00 = a[0];
  4340. var a01 = a[1];
  4341. var a02 = a[2];
  4342. var a03 = a[3];
  4343. var a20 = a[8];
  4344. var a21 = a[9];
  4345. var a22 = a[10];
  4346. var a23 = a[11];
  4347. if (a !== out) {
  4348. // If the source and destination differ, copy the unchanged rows
  4349. out[4] = a[4];
  4350. out[5] = a[5];
  4351. out[6] = a[6];
  4352. out[7] = a[7];
  4353. out[12] = a[12];
  4354. out[13] = a[13];
  4355. out[14] = a[14];
  4356. out[15] = a[15];
  4357. } // Perform axis-specific matrix multiplication
  4358. out[0] = a00 * c - a20 * s;
  4359. out[1] = a01 * c - a21 * s;
  4360. out[2] = a02 * c - a22 * s;
  4361. out[3] = a03 * c - a23 * s;
  4362. out[8] = a00 * s + a20 * c;
  4363. out[9] = a01 * s + a21 * c;
  4364. out[10] = a02 * s + a22 * c;
  4365. out[11] = a03 * s + a23 * c;
  4366. return out;
  4367. }
  4368. /**
  4369. * Rotates a matrix by the given angle around the Z axis
  4370. *
  4371. * @param {mat4} out the receiving matrix
  4372. * @param {ReadonlyMat4} a the matrix to rotate
  4373. * @param {Number} rad the angle to rotate the matrix by
  4374. * @returns {mat4} out
  4375. */
  4376. function rotateZ$1(out, a, rad) {
  4377. var s = Math.sin(rad);
  4378. var c = Math.cos(rad);
  4379. var a00 = a[0];
  4380. var a01 = a[1];
  4381. var a02 = a[2];
  4382. var a03 = a[3];
  4383. var a10 = a[4];
  4384. var a11 = a[5];
  4385. var a12 = a[6];
  4386. var a13 = a[7];
  4387. if (a !== out) {
  4388. // If the source and destination differ, copy the unchanged last row
  4389. out[8] = a[8];
  4390. out[9] = a[9];
  4391. out[10] = a[10];
  4392. out[11] = a[11];
  4393. out[12] = a[12];
  4394. out[13] = a[13];
  4395. out[14] = a[14];
  4396. out[15] = a[15];
  4397. } // Perform axis-specific matrix multiplication
  4398. out[0] = a00 * c + a10 * s;
  4399. out[1] = a01 * c + a11 * s;
  4400. out[2] = a02 * c + a12 * s;
  4401. out[3] = a03 * c + a13 * s;
  4402. out[4] = a10 * c - a00 * s;
  4403. out[5] = a11 * c - a01 * s;
  4404. out[6] = a12 * c - a02 * s;
  4405. out[7] = a13 * c - a03 * s;
  4406. return out;
  4407. }
  4408. /**
  4409. * Returns the scaling factor component of a transformation
  4410. * matrix. If a matrix is built with fromRotationTranslationScale
  4411. * with a normalized Quaternion paramter, the returned vector will be
  4412. * the same as the scaling vector
  4413. * originally supplied.
  4414. * @param {vec3} out Vector to receive scaling factor component
  4415. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4416. * @return {vec3} out
  4417. */
  4418. function getScaling(out, mat) {
  4419. var m11 = mat[0];
  4420. var m12 = mat[1];
  4421. var m13 = mat[2];
  4422. var m21 = mat[4];
  4423. var m22 = mat[5];
  4424. var m23 = mat[6];
  4425. var m31 = mat[8];
  4426. var m32 = mat[9];
  4427. var m33 = mat[10];
  4428. out[0] = Math.hypot(m11, m12, m13);
  4429. out[1] = Math.hypot(m21, m22, m23);
  4430. out[2] = Math.hypot(m31, m32, m33);
  4431. return out;
  4432. }
  4433. /**
  4434. * Calculates a 4x4 matrix from the given quaternion
  4435. *
  4436. * @param {mat4} out mat4 receiving operation result
  4437. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4438. *
  4439. * @returns {mat4} out
  4440. */
  4441. function fromQuat(out, q) {
  4442. var x = q[0],
  4443. y = q[1],
  4444. z = q[2],
  4445. w = q[3];
  4446. var x2 = x + x;
  4447. var y2 = y + y;
  4448. var z2 = z + z;
  4449. var xx = x * x2;
  4450. var yx = y * x2;
  4451. var yy = y * y2;
  4452. var zx = z * x2;
  4453. var zy = z * y2;
  4454. var zz = z * z2;
  4455. var wx = w * x2;
  4456. var wy = w * y2;
  4457. var wz = w * z2;
  4458. out[0] = 1 - yy - zz;
  4459. out[1] = yx + wz;
  4460. out[2] = zx - wy;
  4461. out[3] = 0;
  4462. out[4] = yx - wz;
  4463. out[5] = 1 - xx - zz;
  4464. out[6] = zy + wx;
  4465. out[7] = 0;
  4466. out[8] = zx + wy;
  4467. out[9] = zy - wx;
  4468. out[10] = 1 - xx - yy;
  4469. out[11] = 0;
  4470. out[12] = 0;
  4471. out[13] = 0;
  4472. out[14] = 0;
  4473. out[15] = 1;
  4474. return out;
  4475. }
  4476. /**
  4477. * Generates a frustum matrix with the given bounds
  4478. *
  4479. * @param {mat4} out mat4 frustum matrix will be written into
  4480. * @param {Number} left Left bound of the frustum
  4481. * @param {Number} right Right bound of the frustum
  4482. * @param {Number} bottom Bottom bound of the frustum
  4483. * @param {Number} top Top bound of the frustum
  4484. * @param {Number} near Near bound of the frustum
  4485. * @param {Number} far Far bound of the frustum
  4486. * @returns {mat4} out
  4487. */
  4488. function frustum(out, left, right, bottom, top, near, far) {
  4489. var rl = 1 / (right - left);
  4490. var tb = 1 / (top - bottom);
  4491. var nf = 1 / (near - far);
  4492. out[0] = near * 2 * rl;
  4493. out[1] = 0;
  4494. out[2] = 0;
  4495. out[3] = 0;
  4496. out[4] = 0;
  4497. out[5] = near * 2 * tb;
  4498. out[6] = 0;
  4499. out[7] = 0;
  4500. out[8] = (right + left) * rl;
  4501. out[9] = (top + bottom) * tb;
  4502. out[10] = (far + near) * nf;
  4503. out[11] = -1;
  4504. out[12] = 0;
  4505. out[13] = 0;
  4506. out[14] = far * near * 2 * nf;
  4507. out[15] = 0;
  4508. return out;
  4509. }
  4510. /**
  4511. * Generates a perspective projection matrix with the given bounds.
  4512. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4513. *
  4514. * @param {mat4} out mat4 frustum matrix will be written into
  4515. * @param {number} fovy Vertical field of view in radians
  4516. * @param {number} aspect Aspect ratio. typically viewport width/height
  4517. * @param {number} near Near bound of the frustum
  4518. * @param {number} far Far bound of the frustum, can be null or Infinity
  4519. * @returns {mat4} out
  4520. */
  4521. function perspective(out, fovy, aspect, near, far) {
  4522. var f = 1.0 / Math.tan(fovy / 2),
  4523. nf;
  4524. out[0] = f / aspect;
  4525. out[1] = 0;
  4526. out[2] = 0;
  4527. out[3] = 0;
  4528. out[4] = 0;
  4529. out[5] = f;
  4530. out[6] = 0;
  4531. out[7] = 0;
  4532. out[8] = 0;
  4533. out[9] = 0;
  4534. out[11] = -1;
  4535. out[12] = 0;
  4536. out[13] = 0;
  4537. out[15] = 0;
  4538. if (far != null && far !== Infinity) {
  4539. nf = 1 / (near - far);
  4540. out[10] = (far + near) * nf;
  4541. out[14] = 2 * far * near * nf;
  4542. } else {
  4543. out[10] = -1;
  4544. out[14] = -2 * near;
  4545. }
  4546. return out;
  4547. }
  4548. /**
  4549. * Generates a orthogonal projection matrix with the given bounds
  4550. *
  4551. * @param {mat4} out mat4 frustum matrix will be written into
  4552. * @param {number} left Left bound of the frustum
  4553. * @param {number} right Right bound of the frustum
  4554. * @param {number} bottom Bottom bound of the frustum
  4555. * @param {number} top Top bound of the frustum
  4556. * @param {number} near Near bound of the frustum
  4557. * @param {number} far Far bound of the frustum
  4558. * @returns {mat4} out
  4559. */
  4560. function ortho(out, left, right, bottom, top, near, far) {
  4561. var lr = 1 / (left - right);
  4562. var bt = 1 / (bottom - top);
  4563. var nf = 1 / (near - far);
  4564. out[0] = -2 * lr;
  4565. out[1] = 0;
  4566. out[2] = 0;
  4567. out[3] = 0;
  4568. out[4] = 0;
  4569. out[5] = -2 * bt;
  4570. out[6] = 0;
  4571. out[7] = 0;
  4572. out[8] = 0;
  4573. out[9] = 0;
  4574. out[10] = 2 * nf;
  4575. out[11] = 0;
  4576. out[12] = (left + right) * lr;
  4577. out[13] = (top + bottom) * bt;
  4578. out[14] = (far + near) * nf;
  4579. out[15] = 1;
  4580. return out;
  4581. }
  4582. /**
  4583. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4584. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4585. *
  4586. * @param {mat4} out mat4 frustum matrix will be written into
  4587. * @param {ReadonlyVec3} eye Position of the viewer
  4588. * @param {ReadonlyVec3} center Point the viewer is looking at
  4589. * @param {ReadonlyVec3} up vec3 pointing up
  4590. * @returns {mat4} out
  4591. */
  4592. function lookAt(out, eye, center, up) {
  4593. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4594. var eyex = eye[0];
  4595. var eyey = eye[1];
  4596. var eyez = eye[2];
  4597. var upx = up[0];
  4598. var upy = up[1];
  4599. var upz = up[2];
  4600. var centerx = center[0];
  4601. var centery = center[1];
  4602. var centerz = center[2];
  4603. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4604. return identity$1(out);
  4605. }
  4606. z0 = eyex - centerx;
  4607. z1 = eyey - centery;
  4608. z2 = eyez - centerz;
  4609. len = 1 / Math.hypot(z0, z1, z2);
  4610. z0 *= len;
  4611. z1 *= len;
  4612. z2 *= len;
  4613. x0 = upy * z2 - upz * z1;
  4614. x1 = upz * z0 - upx * z2;
  4615. x2 = upx * z1 - upy * z0;
  4616. len = Math.hypot(x0, x1, x2);
  4617. if (!len) {
  4618. x0 = 0;
  4619. x1 = 0;
  4620. x2 = 0;
  4621. } else {
  4622. len = 1 / len;
  4623. x0 *= len;
  4624. x1 *= len;
  4625. x2 *= len;
  4626. }
  4627. y0 = z1 * x2 - z2 * x1;
  4628. y1 = z2 * x0 - z0 * x2;
  4629. y2 = z0 * x1 - z1 * x0;
  4630. len = Math.hypot(y0, y1, y2);
  4631. if (!len) {
  4632. y0 = 0;
  4633. y1 = 0;
  4634. y2 = 0;
  4635. } else {
  4636. len = 1 / len;
  4637. y0 *= len;
  4638. y1 *= len;
  4639. y2 *= len;
  4640. }
  4641. out[0] = x0;
  4642. out[1] = y0;
  4643. out[2] = z0;
  4644. out[3] = 0;
  4645. out[4] = x1;
  4646. out[5] = y1;
  4647. out[6] = z1;
  4648. out[7] = 0;
  4649. out[8] = x2;
  4650. out[9] = y2;
  4651. out[10] = z2;
  4652. out[11] = 0;
  4653. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4654. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4655. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4656. out[15] = 1;
  4657. return out;
  4658. }
  4659. /**
  4660. * 4 Dimensional Vector
  4661. * @module vec4
  4662. */
  4663. /**
  4664. * Creates a new, empty vec4
  4665. *
  4666. * @returns {vec4} a new 4D vector
  4667. */
  4668. function create$1() {
  4669. var out = new ARRAY_TYPE(4);
  4670. if (ARRAY_TYPE != Float32Array) {
  4671. out[0] = 0;
  4672. out[1] = 0;
  4673. out[2] = 0;
  4674. out[3] = 0;
  4675. }
  4676. return out;
  4677. }
  4678. /**
  4679. * Adds two vec4's
  4680. *
  4681. * @param {vec4} out the receiving vector
  4682. * @param {ReadonlyVec4} a the first operand
  4683. * @param {ReadonlyVec4} b the second operand
  4684. * @returns {vec4} out
  4685. */
  4686. function add$1(out, a, b) {
  4687. out[0] = a[0] + b[0];
  4688. out[1] = a[1] + b[1];
  4689. out[2] = a[2] + b[2];
  4690. out[3] = a[3] + b[3];
  4691. return out;
  4692. }
  4693. /**
  4694. * Scales a vec4 by a scalar number
  4695. *
  4696. * @param {vec4} out the receiving vector
  4697. * @param {ReadonlyVec4} a the vector to scale
  4698. * @param {Number} b amount to scale the vector by
  4699. * @returns {vec4} out
  4700. */
  4701. function scale$1(out, a, b) {
  4702. out[0] = a[0] * b;
  4703. out[1] = a[1] * b;
  4704. out[2] = a[2] * b;
  4705. out[3] = a[3] * b;
  4706. return out;
  4707. }
  4708. /**
  4709. * Calculates the length of a vec4
  4710. *
  4711. * @param {ReadonlyVec4} a vector to calculate length of
  4712. * @returns {Number} length of a
  4713. */
  4714. function length$1(a) {
  4715. var x = a[0];
  4716. var y = a[1];
  4717. var z = a[2];
  4718. var w = a[3];
  4719. return Math.hypot(x, y, z, w);
  4720. }
  4721. /**
  4722. * Calculates the squared length of a vec4
  4723. *
  4724. * @param {ReadonlyVec4} a vector to calculate squared length of
  4725. * @returns {Number} squared length of a
  4726. */
  4727. function squaredLength$1(a) {
  4728. var x = a[0];
  4729. var y = a[1];
  4730. var z = a[2];
  4731. var w = a[3];
  4732. return x * x + y * y + z * z + w * w;
  4733. }
  4734. /**
  4735. * Normalize a vec4
  4736. *
  4737. * @param {vec4} out the receiving vector
  4738. * @param {ReadonlyVec4} a vector to normalize
  4739. * @returns {vec4} out
  4740. */
  4741. function normalize$1(out, a) {
  4742. var x = a[0];
  4743. var y = a[1];
  4744. var z = a[2];
  4745. var w = a[3];
  4746. var len = x * x + y * y + z * z + w * w;
  4747. if (len > 0) {
  4748. len = 1 / Math.sqrt(len);
  4749. }
  4750. out[0] = x * len;
  4751. out[1] = y * len;
  4752. out[2] = z * len;
  4753. out[3] = w * len;
  4754. return out;
  4755. }
  4756. /**
  4757. * Calculates the dot product of two vec4's
  4758. *
  4759. * @param {ReadonlyVec4} a the first operand
  4760. * @param {ReadonlyVec4} b the second operand
  4761. * @returns {Number} dot product of a and b
  4762. */
  4763. function dot$1(a, b) {
  4764. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4765. }
  4766. /**
  4767. * Performs a linear interpolation between two vec4's
  4768. *
  4769. * @param {vec4} out the receiving vector
  4770. * @param {ReadonlyVec4} a the first operand
  4771. * @param {ReadonlyVec4} b the second operand
  4772. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4773. * @returns {vec4} out
  4774. */
  4775. function lerp$1(out, a, b, t) {
  4776. var ax = a[0];
  4777. var ay = a[1];
  4778. var az = a[2];
  4779. var aw = a[3];
  4780. out[0] = ax + t * (b[0] - ax);
  4781. out[1] = ay + t * (b[1] - ay);
  4782. out[2] = az + t * (b[2] - az);
  4783. out[3] = aw + t * (b[3] - aw);
  4784. return out;
  4785. }
  4786. /**
  4787. * Transforms the vec4 with a mat4.
  4788. *
  4789. * @param {vec4} out the receiving vector
  4790. * @param {ReadonlyVec4} a the vector to transform
  4791. * @param {ReadonlyMat4} m matrix to transform with
  4792. * @returns {vec4} out
  4793. */
  4794. function transformMat4(out, a, m) {
  4795. var x = a[0],
  4796. y = a[1],
  4797. z = a[2],
  4798. w = a[3];
  4799. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4800. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4801. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4802. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4803. return out;
  4804. }
  4805. /**
  4806. * Transforms the vec4 with a quat
  4807. *
  4808. * @param {vec4} out the receiving vector
  4809. * @param {ReadonlyVec4} a the vector to transform
  4810. * @param {ReadonlyQuat} q quaternion to transform with
  4811. * @returns {vec4} out
  4812. */
  4813. function transformQuat(out, a, q) {
  4814. var x = a[0],
  4815. y = a[1],
  4816. z = a[2];
  4817. var qx = q[0],
  4818. qy = q[1],
  4819. qz = q[2],
  4820. qw = q[3]; // calculate quat * vec
  4821. var ix = qw * x + qy * z - qz * y;
  4822. var iy = qw * y + qz * x - qx * z;
  4823. var iz = qw * z + qx * y - qy * x;
  4824. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4825. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4826. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4827. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4828. out[3] = a[3];
  4829. return out;
  4830. }
  4831. /**
  4832. * Perform some operation over an array of vec4s.
  4833. *
  4834. * @param {Array} a the array of vectors to iterate over
  4835. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4836. * @param {Number} offset Number of elements to skip at the beginning of the array
  4837. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4838. * @param {Function} fn Function to call for each vector in the array
  4839. * @param {Object} [arg] additional argument to pass to fn
  4840. * @returns {Array} a
  4841. * @function
  4842. */
  4843. (function () {
  4844. var vec = create$1();
  4845. return function (a, stride, offset, count, fn, arg) {
  4846. var i, l;
  4847. if (!stride) {
  4848. stride = 4;
  4849. }
  4850. if (!offset) {
  4851. offset = 0;
  4852. }
  4853. if (count) {
  4854. l = Math.min(count * stride + offset, a.length);
  4855. } else {
  4856. l = a.length;
  4857. }
  4858. for (i = offset; i < l; i += stride) {
  4859. vec[0] = a[i];
  4860. vec[1] = a[i + 1];
  4861. vec[2] = a[i + 2];
  4862. vec[3] = a[i + 3];
  4863. fn(vec, vec, arg);
  4864. a[i] = vec[0];
  4865. a[i + 1] = vec[1];
  4866. a[i + 2] = vec[2];
  4867. a[i + 3] = vec[3];
  4868. }
  4869. return a;
  4870. };
  4871. })();
  4872. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4873. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4874. const INDICES = Object.freeze({
  4875. COL0ROW0: 0,
  4876. COL0ROW1: 1,
  4877. COL0ROW2: 2,
  4878. COL0ROW3: 3,
  4879. COL1ROW0: 4,
  4880. COL1ROW1: 5,
  4881. COL1ROW2: 6,
  4882. COL1ROW3: 7,
  4883. COL2ROW0: 8,
  4884. COL2ROW1: 9,
  4885. COL2ROW2: 10,
  4886. COL2ROW3: 11,
  4887. COL3ROW0: 12,
  4888. COL3ROW1: 13,
  4889. COL3ROW2: 14,
  4890. COL3ROW3: 15
  4891. });
  4892. const constants = {};
  4893. class Matrix4 extends Matrix {
  4894. static get IDENTITY() {
  4895. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4896. return constants.IDENTITY;
  4897. }
  4898. static get ZERO() {
  4899. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4900. return constants.ZERO;
  4901. }
  4902. get INDICES() {
  4903. return INDICES;
  4904. }
  4905. get ELEMENTS() {
  4906. return 16;
  4907. }
  4908. get RANK() {
  4909. return 4;
  4910. }
  4911. constructor(array) {
  4912. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4913. if (arguments.length === 1 && Array.isArray(array)) {
  4914. this.copy(array);
  4915. } else {
  4916. this.identity();
  4917. }
  4918. }
  4919. copy(array) {
  4920. this[0] = array[0];
  4921. this[1] = array[1];
  4922. this[2] = array[2];
  4923. this[3] = array[3];
  4924. this[4] = array[4];
  4925. this[5] = array[5];
  4926. this[6] = array[6];
  4927. this[7] = array[7];
  4928. this[8] = array[8];
  4929. this[9] = array[9];
  4930. this[10] = array[10];
  4931. this[11] = array[11];
  4932. this[12] = array[12];
  4933. this[13] = array[13];
  4934. this[14] = array[14];
  4935. this[15] = array[15];
  4936. return this.check();
  4937. }
  4938. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4939. this[0] = m00;
  4940. this[1] = m10;
  4941. this[2] = m20;
  4942. this[3] = m30;
  4943. this[4] = m01;
  4944. this[5] = m11;
  4945. this[6] = m21;
  4946. this[7] = m31;
  4947. this[8] = m02;
  4948. this[9] = m12;
  4949. this[10] = m22;
  4950. this[11] = m32;
  4951. this[12] = m03;
  4952. this[13] = m13;
  4953. this[14] = m23;
  4954. this[15] = m33;
  4955. return this.check();
  4956. }
  4957. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4958. this[0] = m00;
  4959. this[1] = m10;
  4960. this[2] = m20;
  4961. this[3] = m30;
  4962. this[4] = m01;
  4963. this[5] = m11;
  4964. this[6] = m21;
  4965. this[7] = m31;
  4966. this[8] = m02;
  4967. this[9] = m12;
  4968. this[10] = m22;
  4969. this[11] = m32;
  4970. this[12] = m03;
  4971. this[13] = m13;
  4972. this[14] = m23;
  4973. this[15] = m33;
  4974. return this.check();
  4975. }
  4976. toRowMajor(result) {
  4977. result[0] = this[0];
  4978. result[1] = this[4];
  4979. result[2] = this[8];
  4980. result[3] = this[12];
  4981. result[4] = this[1];
  4982. result[5] = this[5];
  4983. result[6] = this[9];
  4984. result[7] = this[13];
  4985. result[8] = this[2];
  4986. result[9] = this[6];
  4987. result[10] = this[10];
  4988. result[11] = this[14];
  4989. result[12] = this[3];
  4990. result[13] = this[7];
  4991. result[14] = this[11];
  4992. result[15] = this[15];
  4993. return result;
  4994. }
  4995. identity() {
  4996. return this.copy(IDENTITY);
  4997. }
  4998. fromQuaternion(q) {
  4999. fromQuat(this, q);
  5000. return this.check();
  5001. }
  5002. frustum({
  5003. left,
  5004. right,
  5005. bottom,
  5006. top,
  5007. near,
  5008. far
  5009. }) {
  5010. if (far === Infinity) {
  5011. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  5012. } else {
  5013. frustum(this, left, right, bottom, top, near, far);
  5014. }
  5015. return this.check();
  5016. }
  5017. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  5018. const column0Row0 = 2.0 * near / (right - left);
  5019. const column1Row1 = 2.0 * near / (top - bottom);
  5020. const column2Row0 = (right + left) / (right - left);
  5021. const column2Row1 = (top + bottom) / (top - bottom);
  5022. const column2Row2 = -1.0;
  5023. const column2Row3 = -1.0;
  5024. const column3Row2 = -2.0 * near;
  5025. result[0] = column0Row0;
  5026. result[1] = 0.0;
  5027. result[2] = 0.0;
  5028. result[3] = 0.0;
  5029. result[4] = 0.0;
  5030. result[5] = column1Row1;
  5031. result[6] = 0.0;
  5032. result[7] = 0.0;
  5033. result[8] = column2Row0;
  5034. result[9] = column2Row1;
  5035. result[10] = column2Row2;
  5036. result[11] = column2Row3;
  5037. result[12] = 0.0;
  5038. result[13] = 0.0;
  5039. result[14] = column3Row2;
  5040. result[15] = 0.0;
  5041. return result;
  5042. }
  5043. lookAt(eye, center, up) {
  5044. if (arguments.length === 1) {
  5045. ({
  5046. eye,
  5047. center,
  5048. up
  5049. } = eye);
  5050. }
  5051. center = center || [0, 0, 0];
  5052. up = up || [0, 1, 0];
  5053. lookAt(this, eye, center, up);
  5054. return this.check();
  5055. }
  5056. ortho({
  5057. left,
  5058. right,
  5059. bottom,
  5060. top,
  5061. near = 0.1,
  5062. far = 500
  5063. }) {
  5064. ortho(this, left, right, bottom, top, near, far);
  5065. return this.check();
  5066. }
  5067. orthographic({
  5068. fovy = 45 * Math.PI / 180,
  5069. aspect = 1,
  5070. focalDistance = 1,
  5071. near = 0.1,
  5072. far = 500
  5073. }) {
  5074. if (fovy > Math.PI * 2) {
  5075. throw Error('radians');
  5076. }
  5077. const halfY = fovy / 2;
  5078. const top = focalDistance * Math.tan(halfY);
  5079. const right = top * aspect;
  5080. return new Matrix4().ortho({
  5081. left: -right,
  5082. right,
  5083. bottom: -top,
  5084. top,
  5085. near,
  5086. far
  5087. });
  5088. }
  5089. perspective({
  5090. fovy = undefined,
  5091. fov = 45 * Math.PI / 180,
  5092. aspect = 1,
  5093. near = 0.1,
  5094. far = 500
  5095. } = {}) {
  5096. fovy = fovy || fov;
  5097. if (fovy > Math.PI * 2) {
  5098. throw Error('radians');
  5099. }
  5100. perspective(this, fovy, aspect, near, far);
  5101. return this.check();
  5102. }
  5103. determinant() {
  5104. return determinant(this);
  5105. }
  5106. getScale(result = [-0, -0, -0]) {
  5107. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5108. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5109. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5110. return result;
  5111. }
  5112. getTranslation(result = [-0, -0, -0]) {
  5113. result[0] = this[12];
  5114. result[1] = this[13];
  5115. result[2] = this[14];
  5116. return result;
  5117. }
  5118. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5119. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5120. const inverseScale0 = 1 / scale[0];
  5121. const inverseScale1 = 1 / scale[1];
  5122. const inverseScale2 = 1 / scale[2];
  5123. result[0] = this[0] * inverseScale0;
  5124. result[1] = this[1] * inverseScale1;
  5125. result[2] = this[2] * inverseScale2;
  5126. result[3] = 0;
  5127. result[4] = this[4] * inverseScale0;
  5128. result[5] = this[5] * inverseScale1;
  5129. result[6] = this[6] * inverseScale2;
  5130. result[7] = 0;
  5131. result[8] = this[8] * inverseScale0;
  5132. result[9] = this[9] * inverseScale1;
  5133. result[10] = this[10] * inverseScale2;
  5134. result[11] = 0;
  5135. result[12] = 0;
  5136. result[13] = 0;
  5137. result[14] = 0;
  5138. result[15] = 1;
  5139. return result;
  5140. }
  5141. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5142. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5143. const inverseScale0 = 1 / scale[0];
  5144. const inverseScale1 = 1 / scale[1];
  5145. const inverseScale2 = 1 / scale[2];
  5146. result[0] = this[0] * inverseScale0;
  5147. result[1] = this[1] * inverseScale1;
  5148. result[2] = this[2] * inverseScale2;
  5149. result[3] = this[4] * inverseScale0;
  5150. result[4] = this[5] * inverseScale1;
  5151. result[5] = this[6] * inverseScale2;
  5152. result[6] = this[8] * inverseScale0;
  5153. result[7] = this[9] * inverseScale1;
  5154. result[8] = this[10] * inverseScale2;
  5155. return result;
  5156. }
  5157. transpose() {
  5158. transpose(this, this);
  5159. return this.check();
  5160. }
  5161. invert() {
  5162. invert$1(this, this);
  5163. return this.check();
  5164. }
  5165. multiplyLeft(a) {
  5166. multiply$1(this, a, this);
  5167. return this.check();
  5168. }
  5169. multiplyRight(a) {
  5170. multiply$1(this, this, a);
  5171. return this.check();
  5172. }
  5173. rotateX(radians) {
  5174. rotateX$1(this, this, radians);
  5175. return this.check();
  5176. }
  5177. rotateY(radians) {
  5178. rotateY$1(this, this, radians);
  5179. return this.check();
  5180. }
  5181. rotateZ(radians) {
  5182. rotateZ$1(this, this, radians);
  5183. return this.check();
  5184. }
  5185. rotateXYZ([rx, ry, rz]) {
  5186. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5187. }
  5188. rotateAxis(radians, axis) {
  5189. rotate(this, this, radians, axis);
  5190. return this.check();
  5191. }
  5192. scale(factor) {
  5193. if (Array.isArray(factor)) {
  5194. scale$2(this, this, factor);
  5195. } else {
  5196. scale$2(this, this, [factor, factor, factor]);
  5197. }
  5198. return this.check();
  5199. }
  5200. translate(vec) {
  5201. translate(this, this, vec);
  5202. return this.check();
  5203. }
  5204. transform(vector, result) {
  5205. if (vector.length === 4) {
  5206. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5207. checkVector(result, 4);
  5208. return result;
  5209. }
  5210. return this.transformAsPoint(vector, result);
  5211. }
  5212. transformAsPoint(vector, result) {
  5213. const {
  5214. length
  5215. } = vector;
  5216. switch (length) {
  5217. case 2:
  5218. result = transformMat4$2(result || [-0, -0], vector, this);
  5219. break;
  5220. case 3:
  5221. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5222. break;
  5223. default:
  5224. throw new Error('Illegal vector');
  5225. }
  5226. checkVector(result, vector.length);
  5227. return result;
  5228. }
  5229. transformAsVector(vector, result) {
  5230. switch (vector.length) {
  5231. case 2:
  5232. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5233. break;
  5234. case 3:
  5235. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5236. break;
  5237. default:
  5238. throw new Error('Illegal vector');
  5239. }
  5240. checkVector(result, vector.length);
  5241. return result;
  5242. }
  5243. makeRotationX(radians) {
  5244. return this.identity().rotateX(radians);
  5245. }
  5246. makeTranslation(x, y, z) {
  5247. return this.identity().translate([x, y, z]);
  5248. }
  5249. transformPoint(vector, result) {
  5250. deprecated('Matrix4.transformPoint', '3.0');
  5251. return this.transformAsPoint(vector, result);
  5252. }
  5253. transformVector(vector, result) {
  5254. deprecated('Matrix4.transformVector', '3.0');
  5255. return this.transformAsPoint(vector, result);
  5256. }
  5257. transformDirection(vector, result) {
  5258. deprecated('Matrix4.transformDirection', '3.0');
  5259. return this.transformAsVector(vector, result);
  5260. }
  5261. }
  5262. /**
  5263. * Quaternion
  5264. * @module quat
  5265. */
  5266. /**
  5267. * Creates a new identity quat
  5268. *
  5269. * @returns {quat} a new quaternion
  5270. */
  5271. function create() {
  5272. var out = new ARRAY_TYPE(4);
  5273. if (ARRAY_TYPE != Float32Array) {
  5274. out[0] = 0;
  5275. out[1] = 0;
  5276. out[2] = 0;
  5277. }
  5278. out[3] = 1;
  5279. return out;
  5280. }
  5281. /**
  5282. * Set a quat to the identity quaternion
  5283. *
  5284. * @param {quat} out the receiving quaternion
  5285. * @returns {quat} out
  5286. */
  5287. function identity(out) {
  5288. out[0] = 0;
  5289. out[1] = 0;
  5290. out[2] = 0;
  5291. out[3] = 1;
  5292. return out;
  5293. }
  5294. /**
  5295. * Sets a quat from the given angle and rotation axis,
  5296. * then returns it.
  5297. *
  5298. * @param {quat} out the receiving quaternion
  5299. * @param {ReadonlyVec3} axis the axis around which to rotate
  5300. * @param {Number} rad the angle in radians
  5301. * @returns {quat} out
  5302. **/
  5303. function setAxisAngle(out, axis, rad) {
  5304. rad = rad * 0.5;
  5305. var s = Math.sin(rad);
  5306. out[0] = s * axis[0];
  5307. out[1] = s * axis[1];
  5308. out[2] = s * axis[2];
  5309. out[3] = Math.cos(rad);
  5310. return out;
  5311. }
  5312. /**
  5313. * Multiplies two quat's
  5314. *
  5315. * @param {quat} out the receiving quaternion
  5316. * @param {ReadonlyQuat} a the first operand
  5317. * @param {ReadonlyQuat} b the second operand
  5318. * @returns {quat} out
  5319. */
  5320. function multiply(out, a, b) {
  5321. var ax = a[0],
  5322. ay = a[1],
  5323. az = a[2],
  5324. aw = a[3];
  5325. var bx = b[0],
  5326. by = b[1],
  5327. bz = b[2],
  5328. bw = b[3];
  5329. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5330. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5331. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5332. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5333. return out;
  5334. }
  5335. /**
  5336. * Rotates a quaternion by the given angle about the X axis
  5337. *
  5338. * @param {quat} out quat receiving operation result
  5339. * @param {ReadonlyQuat} a quat to rotate
  5340. * @param {number} rad angle (in radians) to rotate
  5341. * @returns {quat} out
  5342. */
  5343. function rotateX(out, a, rad) {
  5344. rad *= 0.5;
  5345. var ax = a[0],
  5346. ay = a[1],
  5347. az = a[2],
  5348. aw = a[3];
  5349. var bx = Math.sin(rad),
  5350. bw = Math.cos(rad);
  5351. out[0] = ax * bw + aw * bx;
  5352. out[1] = ay * bw + az * bx;
  5353. out[2] = az * bw - ay * bx;
  5354. out[3] = aw * bw - ax * bx;
  5355. return out;
  5356. }
  5357. /**
  5358. * Rotates a quaternion by the given angle about the Y axis
  5359. *
  5360. * @param {quat} out quat receiving operation result
  5361. * @param {ReadonlyQuat} a quat to rotate
  5362. * @param {number} rad angle (in radians) to rotate
  5363. * @returns {quat} out
  5364. */
  5365. function rotateY(out, a, rad) {
  5366. rad *= 0.5;
  5367. var ax = a[0],
  5368. ay = a[1],
  5369. az = a[2],
  5370. aw = a[3];
  5371. var by = Math.sin(rad),
  5372. bw = Math.cos(rad);
  5373. out[0] = ax * bw - az * by;
  5374. out[1] = ay * bw + aw * by;
  5375. out[2] = az * bw + ax * by;
  5376. out[3] = aw * bw - ay * by;
  5377. return out;
  5378. }
  5379. /**
  5380. * Rotates a quaternion by the given angle about the Z axis
  5381. *
  5382. * @param {quat} out quat receiving operation result
  5383. * @param {ReadonlyQuat} a quat to rotate
  5384. * @param {number} rad angle (in radians) to rotate
  5385. * @returns {quat} out
  5386. */
  5387. function rotateZ(out, a, rad) {
  5388. rad *= 0.5;
  5389. var ax = a[0],
  5390. ay = a[1],
  5391. az = a[2],
  5392. aw = a[3];
  5393. var bz = Math.sin(rad),
  5394. bw = Math.cos(rad);
  5395. out[0] = ax * bw + ay * bz;
  5396. out[1] = ay * bw - ax * bz;
  5397. out[2] = az * bw + aw * bz;
  5398. out[3] = aw * bw - az * bz;
  5399. return out;
  5400. }
  5401. /**
  5402. * Calculates the W component of a quat from the X, Y, and Z components.
  5403. * Assumes that quaternion is 1 unit in length.
  5404. * Any existing W component will be ignored.
  5405. *
  5406. * @param {quat} out the receiving quaternion
  5407. * @param {ReadonlyQuat} a quat to calculate W component of
  5408. * @returns {quat} out
  5409. */
  5410. function calculateW(out, a) {
  5411. var x = a[0],
  5412. y = a[1],
  5413. z = a[2];
  5414. out[0] = x;
  5415. out[1] = y;
  5416. out[2] = z;
  5417. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5418. return out;
  5419. }
  5420. /**
  5421. * Performs a spherical linear interpolation between two quat
  5422. *
  5423. * @param {quat} out the receiving quaternion
  5424. * @param {ReadonlyQuat} a the first operand
  5425. * @param {ReadonlyQuat} b the second operand
  5426. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5427. * @returns {quat} out
  5428. */
  5429. function slerp(out, a, b, t) {
  5430. // benchmarks:
  5431. // http://jsperf.com/quaternion-slerp-implementations
  5432. var ax = a[0],
  5433. ay = a[1],
  5434. az = a[2],
  5435. aw = a[3];
  5436. var bx = b[0],
  5437. by = b[1],
  5438. bz = b[2],
  5439. bw = b[3];
  5440. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5441. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5442. if (cosom < 0.0) {
  5443. cosom = -cosom;
  5444. bx = -bx;
  5445. by = -by;
  5446. bz = -bz;
  5447. bw = -bw;
  5448. } // calculate coefficients
  5449. if (1.0 - cosom > EPSILON) {
  5450. // standard case (slerp)
  5451. omega = Math.acos(cosom);
  5452. sinom = Math.sin(omega);
  5453. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5454. scale1 = Math.sin(t * omega) / sinom;
  5455. } else {
  5456. // "from" and "to" quaternions are very close
  5457. // ... so we can do a linear interpolation
  5458. scale0 = 1.0 - t;
  5459. scale1 = t;
  5460. } // calculate final values
  5461. out[0] = scale0 * ax + scale1 * bx;
  5462. out[1] = scale0 * ay + scale1 * by;
  5463. out[2] = scale0 * az + scale1 * bz;
  5464. out[3] = scale0 * aw + scale1 * bw;
  5465. return out;
  5466. }
  5467. /**
  5468. * Calculates the inverse of a quat
  5469. *
  5470. * @param {quat} out the receiving quaternion
  5471. * @param {ReadonlyQuat} a quat to calculate inverse of
  5472. * @returns {quat} out
  5473. */
  5474. function invert(out, a) {
  5475. var a0 = a[0],
  5476. a1 = a[1],
  5477. a2 = a[2],
  5478. a3 = a[3];
  5479. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5480. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5481. out[0] = -a0 * invDot;
  5482. out[1] = -a1 * invDot;
  5483. out[2] = -a2 * invDot;
  5484. out[3] = a3 * invDot;
  5485. return out;
  5486. }
  5487. /**
  5488. * Calculates the conjugate of a quat
  5489. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5490. *
  5491. * @param {quat} out the receiving quaternion
  5492. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5493. * @returns {quat} out
  5494. */
  5495. function conjugate(out, a) {
  5496. out[0] = -a[0];
  5497. out[1] = -a[1];
  5498. out[2] = -a[2];
  5499. out[3] = a[3];
  5500. return out;
  5501. }
  5502. /**
  5503. * Creates a quaternion from the given 3x3 rotation matrix.
  5504. *
  5505. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5506. * to renormalize the quaternion yourself where necessary.
  5507. *
  5508. * @param {quat} out the receiving quaternion
  5509. * @param {ReadonlyMat3} m rotation matrix
  5510. * @returns {quat} out
  5511. * @function
  5512. */
  5513. function fromMat3(out, m) {
  5514. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5515. // article "Quaternion Calculus and Fast Animation".
  5516. var fTrace = m[0] + m[4] + m[8];
  5517. var fRoot;
  5518. if (fTrace > 0.0) {
  5519. // |w| > 1/2, may as well choose w > 1/2
  5520. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5521. out[3] = 0.5 * fRoot;
  5522. fRoot = 0.5 / fRoot; // 1/(4w)
  5523. out[0] = (m[5] - m[7]) * fRoot;
  5524. out[1] = (m[6] - m[2]) * fRoot;
  5525. out[2] = (m[1] - m[3]) * fRoot;
  5526. } else {
  5527. // |w| <= 1/2
  5528. var i = 0;
  5529. if (m[4] > m[0]) i = 1;
  5530. if (m[8] > m[i * 3 + i]) i = 2;
  5531. var j = (i + 1) % 3;
  5532. var k = (i + 2) % 3;
  5533. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5534. out[i] = 0.5 * fRoot;
  5535. fRoot = 0.5 / fRoot;
  5536. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5537. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5538. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5539. }
  5540. return out;
  5541. }
  5542. /**
  5543. * Adds two quat's
  5544. *
  5545. * @param {quat} out the receiving quaternion
  5546. * @param {ReadonlyQuat} a the first operand
  5547. * @param {ReadonlyQuat} b the second operand
  5548. * @returns {quat} out
  5549. * @function
  5550. */
  5551. var add = add$1;
  5552. /**
  5553. * Scales a quat by a scalar number
  5554. *
  5555. * @param {quat} out the receiving vector
  5556. * @param {ReadonlyQuat} a the vector to scale
  5557. * @param {Number} b amount to scale the vector by
  5558. * @returns {quat} out
  5559. * @function
  5560. */
  5561. var scale = scale$1;
  5562. /**
  5563. * Calculates the dot product of two quat's
  5564. *
  5565. * @param {ReadonlyQuat} a the first operand
  5566. * @param {ReadonlyQuat} b the second operand
  5567. * @returns {Number} dot product of a and b
  5568. * @function
  5569. */
  5570. var dot = dot$1;
  5571. /**
  5572. * Performs a linear interpolation between two quat's
  5573. *
  5574. * @param {quat} out the receiving quaternion
  5575. * @param {ReadonlyQuat} a the first operand
  5576. * @param {ReadonlyQuat} b the second operand
  5577. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5578. * @returns {quat} out
  5579. * @function
  5580. */
  5581. var lerp = lerp$1;
  5582. /**
  5583. * Calculates the length of a quat
  5584. *
  5585. * @param {ReadonlyQuat} a vector to calculate length of
  5586. * @returns {Number} length of a
  5587. */
  5588. var length = length$1;
  5589. /**
  5590. * Calculates the squared length of a quat
  5591. *
  5592. * @param {ReadonlyQuat} a vector to calculate squared length of
  5593. * @returns {Number} squared length of a
  5594. * @function
  5595. */
  5596. var squaredLength = squaredLength$1;
  5597. /**
  5598. * Normalize a quat
  5599. *
  5600. * @param {quat} out the receiving quaternion
  5601. * @param {ReadonlyQuat} a quaternion to normalize
  5602. * @returns {quat} out
  5603. * @function
  5604. */
  5605. var normalize = normalize$1;
  5606. /**
  5607. * Sets a quaternion to represent the shortest rotation from one
  5608. * vector to another.
  5609. *
  5610. * Both vectors are assumed to be unit length.
  5611. *
  5612. * @param {quat} out the receiving quaternion.
  5613. * @param {ReadonlyVec3} a the initial vector
  5614. * @param {ReadonlyVec3} b the destination vector
  5615. * @returns {quat} out
  5616. */
  5617. var rotationTo = function () {
  5618. var tmpvec3 = create$3();
  5619. var xUnitVec3 = fromValues(1, 0, 0);
  5620. var yUnitVec3 = fromValues(0, 1, 0);
  5621. return function (out, a, b) {
  5622. var dot = dot$2(a, b);
  5623. if (dot < -0.999999) {
  5624. cross(tmpvec3, xUnitVec3, a);
  5625. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5626. normalize$2(tmpvec3, tmpvec3);
  5627. setAxisAngle(out, tmpvec3, Math.PI);
  5628. return out;
  5629. } else if (dot > 0.999999) {
  5630. out[0] = 0;
  5631. out[1] = 0;
  5632. out[2] = 0;
  5633. out[3] = 1;
  5634. return out;
  5635. } else {
  5636. cross(tmpvec3, a, b);
  5637. out[0] = tmpvec3[0];
  5638. out[1] = tmpvec3[1];
  5639. out[2] = tmpvec3[2];
  5640. out[3] = 1 + dot;
  5641. return normalize(out, out);
  5642. }
  5643. };
  5644. }();
  5645. /**
  5646. * Performs a spherical linear interpolation with two control points
  5647. *
  5648. * @param {quat} out the receiving quaternion
  5649. * @param {ReadonlyQuat} a the first operand
  5650. * @param {ReadonlyQuat} b the second operand
  5651. * @param {ReadonlyQuat} c the third operand
  5652. * @param {ReadonlyQuat} d the fourth operand
  5653. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5654. * @returns {quat} out
  5655. */
  5656. (function () {
  5657. var temp1 = create();
  5658. var temp2 = create();
  5659. return function (out, a, b, c, d, t) {
  5660. slerp(temp1, a, d, t);
  5661. slerp(temp2, b, c, t);
  5662. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5663. return out;
  5664. };
  5665. })();
  5666. /**
  5667. * Sets the specified quaternion with values corresponding to the given
  5668. * axes. Each axis is a vec3 and is expected to be unit length and
  5669. * perpendicular to all other specified axes.
  5670. *
  5671. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5672. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5673. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5674. * @returns {quat} out
  5675. */
  5676. (function () {
  5677. var matr = create$2();
  5678. return function (out, view, right, up) {
  5679. matr[0] = right[0];
  5680. matr[3] = right[1];
  5681. matr[6] = right[2];
  5682. matr[1] = up[0];
  5683. matr[4] = up[1];
  5684. matr[7] = up[2];
  5685. matr[2] = -view[0];
  5686. matr[5] = -view[1];
  5687. matr[8] = -view[2];
  5688. return normalize(out, fromMat3(out, matr));
  5689. };
  5690. })();
  5691. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5692. class Quaternion extends MathArray {
  5693. constructor(x = 0, y = 0, z = 0, w = 1) {
  5694. super(-0, -0, -0, -0);
  5695. if (Array.isArray(x) && arguments.length === 1) {
  5696. this.copy(x);
  5697. } else {
  5698. this.set(x, y, z, w);
  5699. }
  5700. }
  5701. copy(array) {
  5702. this[0] = array[0];
  5703. this[1] = array[1];
  5704. this[2] = array[2];
  5705. this[3] = array[3];
  5706. return this.check();
  5707. }
  5708. set(x, y, z, w) {
  5709. this[0] = x;
  5710. this[1] = y;
  5711. this[2] = z;
  5712. this[3] = w;
  5713. return this.check();
  5714. }
  5715. fromMatrix3(m) {
  5716. fromMat3(this, m);
  5717. return this.check();
  5718. }
  5719. identity() {
  5720. identity(this);
  5721. return this.check();
  5722. }
  5723. fromAxisRotation(axis, rad) {
  5724. setAxisAngle(this, axis, rad);
  5725. return this.check();
  5726. }
  5727. setAxisAngle(axis, rad) {
  5728. return this.fromAxisRotation(axis, rad);
  5729. }
  5730. get ELEMENTS() {
  5731. return 4;
  5732. }
  5733. get x() {
  5734. return this[0];
  5735. }
  5736. set x(value) {
  5737. this[0] = checkNumber(value);
  5738. }
  5739. get y() {
  5740. return this[1];
  5741. }
  5742. set y(value) {
  5743. this[1] = checkNumber(value);
  5744. }
  5745. get z() {
  5746. return this[2];
  5747. }
  5748. set z(value) {
  5749. this[2] = checkNumber(value);
  5750. }
  5751. get w() {
  5752. return this[3];
  5753. }
  5754. set w(value) {
  5755. this[3] = checkNumber(value);
  5756. }
  5757. len() {
  5758. return length(this);
  5759. }
  5760. lengthSquared() {
  5761. return squaredLength(this);
  5762. }
  5763. dot(a, b) {
  5764. if (b !== undefined) {
  5765. throw new Error('Quaternion.dot only takes one argument');
  5766. }
  5767. return dot(this, a);
  5768. }
  5769. rotationTo(vectorA, vectorB) {
  5770. rotationTo(this, vectorA, vectorB);
  5771. return this.check();
  5772. }
  5773. add(a, b) {
  5774. if (b !== undefined) {
  5775. throw new Error('Quaternion.add only takes one argument');
  5776. }
  5777. add(this, this, a);
  5778. return this.check();
  5779. }
  5780. calculateW() {
  5781. calculateW(this, this);
  5782. return this.check();
  5783. }
  5784. conjugate() {
  5785. conjugate(this, this);
  5786. return this.check();
  5787. }
  5788. invert() {
  5789. invert(this, this);
  5790. return this.check();
  5791. }
  5792. lerp(a, b, t) {
  5793. lerp(this, a, b, t);
  5794. return this.check();
  5795. }
  5796. multiplyRight(a, b) {
  5797. assert$4(!b);
  5798. multiply(this, this, a);
  5799. return this.check();
  5800. }
  5801. multiplyLeft(a, b) {
  5802. assert$4(!b);
  5803. multiply(this, a, this);
  5804. return this.check();
  5805. }
  5806. normalize() {
  5807. const length = this.len();
  5808. const l = length > 0 ? 1 / length : 0;
  5809. this[0] = this[0] * l;
  5810. this[1] = this[1] * l;
  5811. this[2] = this[2] * l;
  5812. this[3] = this[3] * l;
  5813. if (length === 0) {
  5814. this[3] = 1;
  5815. }
  5816. return this.check();
  5817. }
  5818. rotateX(rad) {
  5819. rotateX(this, this, rad);
  5820. return this.check();
  5821. }
  5822. rotateY(rad) {
  5823. rotateY(this, this, rad);
  5824. return this.check();
  5825. }
  5826. rotateZ(rad) {
  5827. rotateZ(this, this, rad);
  5828. return this.check();
  5829. }
  5830. scale(b) {
  5831. scale(this, this, b);
  5832. return this.check();
  5833. }
  5834. slerp(start, target, ratio) {
  5835. switch (arguments.length) {
  5836. case 1:
  5837. ({
  5838. start = IDENTITY_QUATERNION,
  5839. target,
  5840. ratio
  5841. } = arguments[0]);
  5842. break;
  5843. case 2:
  5844. [target, ratio] = arguments;
  5845. start = this;
  5846. break;
  5847. }
  5848. slerp(this, start, target, ratio);
  5849. return this.check();
  5850. }
  5851. transformVector4(vector, result = vector) {
  5852. transformQuat(result, vector, this);
  5853. return checkVector(result, 4);
  5854. }
  5855. lengthSq() {
  5856. return this.lengthSquared();
  5857. }
  5858. setFromAxisAngle(axis, rad) {
  5859. return this.setAxisAngle(axis, rad);
  5860. }
  5861. premultiply(a, b) {
  5862. return this.multiplyLeft(a, b);
  5863. }
  5864. multiply(a, b) {
  5865. return this.multiplyRight(a, b);
  5866. }
  5867. }
  5868. var _MathUtils = {
  5869. EPSILON1: 1e-1,
  5870. EPSILON2: 1e-2,
  5871. EPSILON3: 1e-3,
  5872. EPSILON4: 1e-4,
  5873. EPSILON5: 1e-5,
  5874. EPSILON6: 1e-6,
  5875. EPSILON7: 1e-7,
  5876. EPSILON8: 1e-8,
  5877. EPSILON9: 1e-9,
  5878. EPSILON10: 1e-10,
  5879. EPSILON11: 1e-11,
  5880. EPSILON12: 1e-12,
  5881. EPSILON13: 1e-13,
  5882. EPSILON14: 1e-14,
  5883. EPSILON15: 1e-15,
  5884. EPSILON16: 1e-16,
  5885. EPSILON17: 1e-17,
  5886. EPSILON18: 1e-18,
  5887. EPSILON19: 1e-19,
  5888. EPSILON20: 1e-20,
  5889. PI_OVER_TWO: Math.PI / 2,
  5890. PI_OVER_FOUR: Math.PI / 4,
  5891. PI_OVER_SIX: Math.PI / 6,
  5892. TWO_PI: Math.PI * 2
  5893. };
  5894. const WGS84_RADIUS_X$1 = 6378137.0;
  5895. const WGS84_RADIUS_Y$1 = 6378137.0;
  5896. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5897. const noop = x => x;
  5898. const scratchVector$6 = new Vector3();
  5899. function fromCartographic(cartographic, result, map = noop) {
  5900. if (isArray(cartographic)) {
  5901. result[0] = map(cartographic[0]);
  5902. result[1] = map(cartographic[1]);
  5903. result[2] = cartographic[2];
  5904. } else if ('longitude' in cartographic) {
  5905. result[0] = map(cartographic.longitude);
  5906. result[1] = map(cartographic.latitude);
  5907. result[2] = cartographic.height;
  5908. } else {
  5909. result[0] = map(cartographic.x);
  5910. result[1] = map(cartographic.y);
  5911. result[2] = cartographic.z;
  5912. }
  5913. return result;
  5914. }
  5915. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5916. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5917. }
  5918. function toCartographic(vector, cartographic, map = noop) {
  5919. if (isArray(cartographic)) {
  5920. cartographic[0] = map(vector[0]);
  5921. cartographic[1] = map(vector[1]);
  5922. cartographic[2] = vector[2];
  5923. } else if ('longitude' in cartographic) {
  5924. cartographic.longitude = map(vector[0]);
  5925. cartographic.latitude = map(vector[1]);
  5926. cartographic.height = vector[2];
  5927. } else {
  5928. cartographic.x = map(vector[0]);
  5929. cartographic.y = map(vector[1]);
  5930. cartographic.z = vector[2];
  5931. }
  5932. return cartographic;
  5933. }
  5934. function toCartographicFromRadians(vector, cartographic) {
  5935. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5936. }
  5937. const scratchVector$5 = new Vector3();
  5938. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5939. const scaleToGeodeticSurfaceGradient = new Vector3();
  5940. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5941. const {
  5942. oneOverRadii,
  5943. oneOverRadiiSquared,
  5944. centerToleranceSquared
  5945. } = ellipsoid;
  5946. scratchVector$5.from(cartesian);
  5947. const positionX = cartesian.x;
  5948. const positionY = cartesian.y;
  5949. const positionZ = cartesian.z;
  5950. const oneOverRadiiX = oneOverRadii.x;
  5951. const oneOverRadiiY = oneOverRadii.y;
  5952. const oneOverRadiiZ = oneOverRadii.z;
  5953. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5954. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5955. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5956. const squaredNorm = x2 + y2 + z2;
  5957. const ratio = Math.sqrt(1.0 / squaredNorm);
  5958. if (!Number.isFinite(ratio)) {
  5959. return undefined;
  5960. }
  5961. const intersection = scaleToGeodeticSurfaceIntersection;
  5962. intersection.copy(cartesian).scale(ratio);
  5963. if (squaredNorm < centerToleranceSquared) {
  5964. return intersection.to(result);
  5965. }
  5966. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5967. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5968. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5969. const gradient = scaleToGeodeticSurfaceGradient;
  5970. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5971. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5972. let correction = 0.0;
  5973. let xMultiplier;
  5974. let yMultiplier;
  5975. let zMultiplier;
  5976. let func;
  5977. do {
  5978. lambda -= correction;
  5979. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5980. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5981. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5982. const xMultiplier2 = xMultiplier * xMultiplier;
  5983. const yMultiplier2 = yMultiplier * yMultiplier;
  5984. const zMultiplier2 = zMultiplier * zMultiplier;
  5985. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5986. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5987. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5988. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5989. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5990. const derivative = -2.0 * denominator;
  5991. correction = func / derivative;
  5992. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5993. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5994. }
  5995. const EPSILON14 = 1e-14;
  5996. const scratchOrigin = new Vector3();
  5997. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5998. up: {
  5999. south: 'east',
  6000. north: 'west',
  6001. west: 'south',
  6002. east: 'north'
  6003. },
  6004. down: {
  6005. south: 'west',
  6006. north: 'east',
  6007. west: 'north',
  6008. east: 'south'
  6009. },
  6010. south: {
  6011. up: 'west',
  6012. down: 'east',
  6013. west: 'down',
  6014. east: 'up'
  6015. },
  6016. north: {
  6017. up: 'east',
  6018. down: 'west',
  6019. west: 'up',
  6020. east: 'down'
  6021. },
  6022. west: {
  6023. up: 'north',
  6024. down: 'south',
  6025. north: 'down',
  6026. south: 'up'
  6027. },
  6028. east: {
  6029. up: 'south',
  6030. down: 'north',
  6031. north: 'up',
  6032. south: 'down'
  6033. }
  6034. };
  6035. const degeneratePositionLocalFrame = {
  6036. north: [-1, 0, 0],
  6037. east: [0, 1, 0],
  6038. up: [0, 0, 1],
  6039. south: [1, 0, 0],
  6040. west: [0, -1, 0],
  6041. down: [0, 0, -1]
  6042. };
  6043. const scratchAxisVectors = {
  6044. east: new Vector3(),
  6045. north: new Vector3(),
  6046. up: new Vector3(),
  6047. west: new Vector3(),
  6048. south: new Vector3(),
  6049. down: new Vector3()
  6050. };
  6051. const scratchVector1 = new Vector3();
  6052. const scratchVector2$1 = new Vector3();
  6053. const scratchVector3$1 = new Vector3();
  6054. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6055. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6056. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6057. let firstAxisVector;
  6058. let secondAxisVector;
  6059. let thirdAxisVector;
  6060. const origin = scratchOrigin.copy(cartesianOrigin);
  6061. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6062. if (atPole) {
  6063. const sign = Math.sign(origin.z);
  6064. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6065. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6066. firstAxisVector.scale(sign);
  6067. }
  6068. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6069. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6070. secondAxisVector.scale(sign);
  6071. }
  6072. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6073. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6074. thirdAxisVector.scale(sign);
  6075. }
  6076. } else {
  6077. const {
  6078. up,
  6079. east,
  6080. north
  6081. } = scratchAxisVectors;
  6082. east.set(-origin.y, origin.x, 0.0).normalize();
  6083. ellipsoid.geodeticSurfaceNormal(origin, up);
  6084. north.copy(up).cross(east);
  6085. const {
  6086. down,
  6087. west,
  6088. south
  6089. } = scratchAxisVectors;
  6090. down.copy(up).scale(-1);
  6091. west.copy(east).scale(-1);
  6092. south.copy(north).scale(-1);
  6093. firstAxisVector = scratchAxisVectors[firstAxis];
  6094. secondAxisVector = scratchAxisVectors[secondAxis];
  6095. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6096. }
  6097. result[0] = firstAxisVector.x;
  6098. result[1] = firstAxisVector.y;
  6099. result[2] = firstAxisVector.z;
  6100. result[3] = 0.0;
  6101. result[4] = secondAxisVector.x;
  6102. result[5] = secondAxisVector.y;
  6103. result[6] = secondAxisVector.z;
  6104. result[7] = 0.0;
  6105. result[8] = thirdAxisVector.x;
  6106. result[9] = thirdAxisVector.y;
  6107. result[10] = thirdAxisVector.z;
  6108. result[11] = 0.0;
  6109. result[12] = origin.x;
  6110. result[13] = origin.y;
  6111. result[14] = origin.z;
  6112. result[15] = 1.0;
  6113. return result;
  6114. }
  6115. const scratchVector$4 = new Vector3();
  6116. const scratchNormal$2 = new Vector3();
  6117. const scratchK = new Vector3();
  6118. const scratchPosition$2 = new Vector3();
  6119. const scratchHeight = new Vector3();
  6120. const scratchCartesian = new Vector3();
  6121. let wgs84;
  6122. class Ellipsoid {
  6123. static get WGS84() {
  6124. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6125. return wgs84;
  6126. }
  6127. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6128. assert$4(x >= 0.0);
  6129. assert$4(y >= 0.0);
  6130. assert$4(z >= 0.0);
  6131. this.radii = new Vector3(x, y, z);
  6132. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6133. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6134. 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);
  6135. 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));
  6136. this.minimumRadius = Math.min(x, y, z);
  6137. this.maximumRadius = Math.max(x, y, z);
  6138. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6139. if (this.radiiSquared.z !== 0) {
  6140. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6141. }
  6142. Object.freeze(this);
  6143. }
  6144. equals(right) {
  6145. return this === right || Boolean(right && this.radii.equals(right.radii));
  6146. }
  6147. toString() {
  6148. return this.radii.toString();
  6149. }
  6150. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6151. const normal = scratchNormal$2;
  6152. const k = scratchK;
  6153. const [,, height] = cartographic;
  6154. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6155. k.copy(this.radiiSquared).scale(normal);
  6156. const gamma = Math.sqrt(normal.dot(k));
  6157. k.scale(1 / gamma);
  6158. normal.scale(height);
  6159. k.add(normal);
  6160. return k.to(result);
  6161. }
  6162. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6163. scratchCartesian.from(cartesian);
  6164. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6165. if (!point) {
  6166. return undefined;
  6167. }
  6168. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6169. const h = scratchHeight;
  6170. h.copy(scratchCartesian).subtract(point);
  6171. const longitude = Math.atan2(normal.y, normal.x);
  6172. const latitude = Math.asin(normal.z);
  6173. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6174. return toCartographicFromRadians([longitude, latitude, height], result);
  6175. }
  6176. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6177. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6178. }
  6179. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6180. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6181. }
  6182. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6183. return scratchVector$4.from(cartesian).normalize().to(result);
  6184. }
  6185. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6186. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6187. const longitude = cartographicVectorRadians[0];
  6188. const latitude = cartographicVectorRadians[1];
  6189. const cosLatitude = Math.cos(latitude);
  6190. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6191. return scratchVector$4.to(result);
  6192. }
  6193. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6194. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6195. }
  6196. scaleToGeodeticSurface(cartesian, result) {
  6197. return scaleToGeodeticSurface(cartesian, this, result);
  6198. }
  6199. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6200. scratchPosition$2.from(cartesian);
  6201. const positionX = scratchPosition$2.x;
  6202. const positionY = scratchPosition$2.y;
  6203. const positionZ = scratchPosition$2.z;
  6204. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6205. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6206. return scratchPosition$2.multiplyScalar(beta).to(result);
  6207. }
  6208. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6209. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6210. }
  6211. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6212. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6213. }
  6214. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6215. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6216. assert$4(this.radii.z > 0);
  6217. scratchPosition$2.from(position);
  6218. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6219. if (Math.abs(z) >= this.radii.z - buffer) {
  6220. return undefined;
  6221. }
  6222. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6223. }
  6224. }
  6225. class DoublyLinkedListNode {
  6226. constructor(item, previous, next) {
  6227. _defineProperty(this, "item", void 0);
  6228. _defineProperty(this, "previous", void 0);
  6229. _defineProperty(this, "next", void 0);
  6230. this.item = item;
  6231. this.previous = previous;
  6232. this.next = next;
  6233. }
  6234. }
  6235. class DoublyLinkedList {
  6236. constructor() {
  6237. _defineProperty(this, "head", null);
  6238. _defineProperty(this, "tail", null);
  6239. _defineProperty(this, "_length", 0);
  6240. }
  6241. get length() {
  6242. return this._length;
  6243. }
  6244. add(item) {
  6245. const node = new DoublyLinkedListNode(item, this.tail, null);
  6246. if (this.tail) {
  6247. this.tail.next = node;
  6248. this.tail = node;
  6249. } else {
  6250. this.head = node;
  6251. this.tail = node;
  6252. }
  6253. ++this._length;
  6254. return node;
  6255. }
  6256. remove(node) {
  6257. if (!node) {
  6258. return;
  6259. }
  6260. if (node.previous && node.next) {
  6261. node.previous.next = node.next;
  6262. node.next.previous = node.previous;
  6263. } else if (node.previous) {
  6264. node.previous.next = null;
  6265. this.tail = node.previous;
  6266. } else if (node.next) {
  6267. node.next.previous = null;
  6268. this.head = node.next;
  6269. } else {
  6270. this.head = null;
  6271. this.tail = null;
  6272. }
  6273. node.next = null;
  6274. node.previous = null;
  6275. --this._length;
  6276. }
  6277. splice(node, nextNode) {
  6278. if (node === nextNode) {
  6279. return;
  6280. }
  6281. this.remove(nextNode);
  6282. this._insert(node, nextNode);
  6283. }
  6284. _insert(node, nextNode) {
  6285. const oldNodeNext = node.next;
  6286. node.next = nextNode;
  6287. if (this.tail === node) {
  6288. this.tail = nextNode;
  6289. } else {
  6290. oldNodeNext.previous = nextNode;
  6291. }
  6292. nextNode.next = oldNodeNext;
  6293. nextNode.previous = node;
  6294. ++this._length;
  6295. }
  6296. }
  6297. function defined$5(x) {
  6298. return x !== undefined && x !== null;
  6299. }
  6300. class TilesetCache {
  6301. constructor() {
  6302. _defineProperty(this, "_list", void 0);
  6303. _defineProperty(this, "_sentinel", void 0);
  6304. _defineProperty(this, "_trimTiles", void 0);
  6305. this._list = new DoublyLinkedList();
  6306. this._sentinel = this._list.add('sentinel');
  6307. this._trimTiles = false;
  6308. }
  6309. reset() {
  6310. this._list.splice(this._list.tail, this._sentinel);
  6311. }
  6312. touch(tile) {
  6313. const node = tile._cacheNode;
  6314. if (defined$5(node)) {
  6315. this._list.splice(this._sentinel, node);
  6316. }
  6317. }
  6318. add(tileset, tile, addCallback) {
  6319. if (!defined$5(tile._cacheNode)) {
  6320. tile._cacheNode = this._list.add(tile);
  6321. if (addCallback) {
  6322. addCallback(tileset, tile);
  6323. }
  6324. }
  6325. }
  6326. unloadTile(tileset, tile, unloadCallback) {
  6327. const node = tile._cacheNode;
  6328. if (!defined$5(node)) {
  6329. return;
  6330. }
  6331. this._list.remove(node);
  6332. tile._cacheNode = undefined;
  6333. if (unloadCallback) {
  6334. unloadCallback(tileset, tile);
  6335. }
  6336. }
  6337. unloadTiles(tileset, unloadCallback) {
  6338. const trimTiles = this._trimTiles;
  6339. this._trimTiles = false;
  6340. const list = this._list;
  6341. const maximumMemoryUsageInBytes = (Potree.settings.tiles3DMaxMemory || tileset.maximumMemoryUsage) * 1024 * 1024;
  6342. const sentinel = this._sentinel;
  6343. let node = list.head;
  6344. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6345. const tile = node.item;
  6346. node = node.next;
  6347. this.unloadTile(tileset, tile, unloadCallback);
  6348. } */
  6349. //改
  6350. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  6351. const tile = node.item;
  6352. node = node.next;
  6353. this.unloadTile(tileset, tile, unloadCallback);
  6354. }
  6355. }
  6356. trim() {
  6357. this._trimTiles = true;
  6358. }
  6359. }
  6360. function calculateTransformProps(tileHeader, tile) {
  6361. assert$7(tileHeader);
  6362. assert$7(tile);
  6363. const {
  6364. rtcCenter,
  6365. gltfUpAxis
  6366. } = tile;
  6367. const {
  6368. computedTransform,
  6369. boundingVolume: {
  6370. center
  6371. }
  6372. } = tileHeader;
  6373. let modelMatrix = new Matrix4(computedTransform);
  6374. if (rtcCenter) {
  6375. modelMatrix.translate(rtcCenter);
  6376. }
  6377. switch (gltfUpAxis) {
  6378. case 'Z':
  6379. break;
  6380. case 'Y':
  6381. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6382. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6383. break;
  6384. case 'X':
  6385. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6386. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6387. break;
  6388. }
  6389. if (tile.isQuantized) {
  6390. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6391. }
  6392. const cartesianOrigin = new Vector3(center);
  6393. tile.cartesianModelMatrix = modelMatrix;
  6394. tile.cartesianOrigin = cartesianOrigin;
  6395. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6396. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6397. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6398. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6399. tile.cartographicOrigin = cartographicOrigin;
  6400. if (!tile.coordinateSystem) {
  6401. tile.modelMatrix = tile.cartographicModelMatrix;
  6402. }
  6403. }
  6404. const INTERSECTION = Object.freeze({
  6405. OUTSIDE: -1,
  6406. INTERSECTING: 0,
  6407. INSIDE: 1
  6408. });
  6409. new Vector3();
  6410. new Vector3();
  6411. const scratchVector$3 = new Vector3();
  6412. const scratchVector2 = new Vector3();
  6413. class BoundingSphere {
  6414. constructor(center = [0, 0, 0], radius = 0.0) {
  6415. this.radius = -0;
  6416. this.center = new Vector3();
  6417. this.fromCenterRadius(center, radius);
  6418. }
  6419. fromCenterRadius(center, radius) {
  6420. this.center.from(center);
  6421. this.radius = radius;
  6422. return this;
  6423. }
  6424. fromCornerPoints(corner, oppositeCorner) {
  6425. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6426. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6427. this.radius = this.center.distance(oppositeCorner);
  6428. return this;
  6429. }
  6430. equals(right) {
  6431. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6432. }
  6433. clone() {
  6434. return new BoundingSphere(this.center, this.radius);
  6435. }
  6436. union(boundingSphere) {
  6437. const leftCenter = this.center;
  6438. const leftRadius = this.radius;
  6439. const rightCenter = boundingSphere.center;
  6440. const rightRadius = boundingSphere.radius;
  6441. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6442. const centerSeparation = toRightCenter.magnitude();
  6443. if (leftRadius >= centerSeparation + rightRadius) {
  6444. return this.clone();
  6445. }
  6446. if (rightRadius >= centerSeparation + leftRadius) {
  6447. return boundingSphere.clone();
  6448. }
  6449. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6450. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6451. this.center.copy(scratchVector2);
  6452. this.radius = halfDistanceBetweenTangentPoints;
  6453. return this;
  6454. }
  6455. expand(point) {
  6456. point = scratchVector$3.from(point);
  6457. const radius = point.subtract(this.center).magnitude();
  6458. if (radius > this.radius) {
  6459. this.radius = radius;
  6460. }
  6461. return this;
  6462. }
  6463. transform(transform) {
  6464. this.center.transform(transform);
  6465. const scale = getScaling(scratchVector$3, transform);
  6466. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6467. return this;
  6468. }
  6469. distanceSquaredTo(point) {
  6470. const d = this.distanceTo(point);
  6471. return d * d;
  6472. }
  6473. distanceTo(point) {
  6474. point = scratchVector$3.from(point);
  6475. const delta = point.subtract(this.center);
  6476. return Math.max(0, delta.len() - this.radius);
  6477. }
  6478. intersectPlane(plane) {
  6479. const center = this.center;
  6480. const radius = this.radius;
  6481. const normal = plane.normal;
  6482. const distanceToPlane = normal.dot(center) + plane.distance;
  6483. if (distanceToPlane < -radius) {
  6484. return INTERSECTION.OUTSIDE;
  6485. }
  6486. if (distanceToPlane < radius) {
  6487. return INTERSECTION.INTERSECTING;
  6488. }
  6489. return INTERSECTION.INSIDE;
  6490. }
  6491. }
  6492. const scratchVector3 = new Vector3();
  6493. const scratchOffset = new Vector3();
  6494. const scratchVectorU = new Vector3();
  6495. const scratchVectorV = new Vector3();
  6496. const scratchVectorW = new Vector3();
  6497. const scratchCorner = new Vector3();
  6498. const scratchToCenter = new Vector3();
  6499. const MATRIX3 = {
  6500. COLUMN0ROW0: 0,
  6501. COLUMN0ROW1: 1,
  6502. COLUMN0ROW2: 2,
  6503. COLUMN1ROW0: 3,
  6504. COLUMN1ROW1: 4,
  6505. COLUMN1ROW2: 5,
  6506. COLUMN2ROW0: 6,
  6507. COLUMN2ROW1: 7,
  6508. COLUMN2ROW2: 8
  6509. };
  6510. class OrientedBoundingBox {
  6511. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6512. this.center = new Vector3().from(center);
  6513. this.halfAxes = new Matrix3(halfAxes);
  6514. }
  6515. get halfSize() {
  6516. const xAxis = this.halfAxes.getColumn(0);
  6517. const yAxis = this.halfAxes.getColumn(1);
  6518. const zAxis = this.halfAxes.getColumn(2);
  6519. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6520. }
  6521. get quaternion() {
  6522. const xAxis = this.halfAxes.getColumn(0);
  6523. const yAxis = this.halfAxes.getColumn(1);
  6524. const zAxis = this.halfAxes.getColumn(2);
  6525. const normXAxis = new Vector3(xAxis).normalize();
  6526. const normYAxis = new Vector3(yAxis).normalize();
  6527. const normZAxis = new Vector3(zAxis).normalize();
  6528. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6529. }
  6530. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6531. const quaternionObject = new Quaternion(quaternion);
  6532. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6533. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6534. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6535. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6536. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6537. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6538. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6539. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6540. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6541. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6542. this.center = new Vector3().from(center);
  6543. this.halfAxes = directionsMatrix;
  6544. return this;
  6545. }
  6546. clone() {
  6547. return new OrientedBoundingBox(this.center, this.halfAxes);
  6548. }
  6549. equals(right) {
  6550. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6551. }
  6552. getBoundingSphere(result = new BoundingSphere()) {
  6553. const halfAxes = this.halfAxes;
  6554. const u = halfAxes.getColumn(0, scratchVectorU);//前三个
  6555. const v = halfAxes.getColumn(1, scratchVectorV);
  6556. const w = halfAxes.getColumn(2, scratchVectorW);
  6557. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6558. result.center.copy(this.center);
  6559. result.radius = cornerVector.magnitude();
  6560. return result;
  6561. }
  6562. intersectPlane(plane) {
  6563. const center = this.center;
  6564. const normal = plane.normal;
  6565. const halfAxes = this.halfAxes;
  6566. const normalX = normal.x;
  6567. const normalY = normal.y;
  6568. const normalZ = normal.z;
  6569. 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]);
  6570. const distanceToPlane = normal.dot(center) + plane.distance;
  6571. if (distanceToPlane <= -radEffective) {
  6572. return INTERSECTION.OUTSIDE;
  6573. } else if (distanceToPlane >= radEffective) {
  6574. return INTERSECTION.INSIDE;
  6575. }
  6576. return INTERSECTION.INTERSECTING; //在相机frustum内
  6577. }
  6578. distanceTo(point) {
  6579. return Math.sqrt(this.distanceSquaredTo(point));
  6580. }
  6581. /* distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6582. let center = this.center.clone()
  6583. center.z *= -1
  6584. const offset = scratchOffset.from(point).subtract(center);
  6585. const halfAxes = this.halfAxes;
  6586. const u = halfAxes.getColumn(0, scratchVectorU);
  6587. const v = halfAxes.getColumn(1, scratchVectorV);
  6588. const w = halfAxes.getColumn(2, scratchVectorW);
  6589. u.z *= -1
  6590. v.z *= -1
  6591. w.z *= -1
  6592. const uHalf = u.magnitude();
  6593. const vHalf = v.magnitude();
  6594. const wHalf = w.magnitude();
  6595. u.normalize();
  6596. v.normalize();
  6597. w.normalize();
  6598. let distanceSquared = 0.0;
  6599. let d;
  6600. d = Math.abs(offset.dot(u)) - uHalf;
  6601. if (d > 0) {
  6602. distanceSquared += d * d;
  6603. }
  6604. d = Math.abs(offset.dot(v)) - vHalf;
  6605. if (d > 0) {
  6606. distanceSquared += d * d;
  6607. }
  6608. d = Math.abs(offset.dot(w)) - wHalf;
  6609. if (d > 0) {
  6610. distanceSquared += d * d;
  6611. }
  6612. return distanceSquared;
  6613. } */
  6614. distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6615. const offset = scratchOffset.from(point).subtract(this.center);
  6616. const halfAxes = this.halfAxes;
  6617. const u = halfAxes.getColumn(0, scratchVectorU);
  6618. const v = halfAxes.getColumn(1, scratchVectorV);
  6619. const w = halfAxes.getColumn(2, scratchVectorW);
  6620. const uHalf = u.magnitude();
  6621. const vHalf = v.magnitude();
  6622. const wHalf = w.magnitude();
  6623. u.normalize();
  6624. v.normalize();
  6625. w.normalize();
  6626. let distanceSquared = 0.0;
  6627. let d;
  6628. d = Math.abs(offset.dot(u)) - uHalf;
  6629. if (d > 0) {
  6630. distanceSquared += d * d;
  6631. }
  6632. d = Math.abs(offset.dot(v)) - vHalf;
  6633. if (d > 0) {
  6634. distanceSquared += d * d;
  6635. }
  6636. d = Math.abs(offset.dot(w)) - wHalf;
  6637. if (d > 0) {
  6638. distanceSquared += d * d;
  6639. }
  6640. return distanceSquared;
  6641. }
  6642. computePlaneDistances(position, direction, result = [-0, -0]) {
  6643. let minDist = Number.POSITIVE_INFINITY;
  6644. let maxDist = Number.NEGATIVE_INFINITY;
  6645. const center = this.center;
  6646. const halfAxes = this.halfAxes;
  6647. const u = halfAxes.getColumn(0, scratchVectorU);
  6648. const v = halfAxes.getColumn(1, scratchVectorV);
  6649. const w = halfAxes.getColumn(2, scratchVectorW);
  6650. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6651. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6652. let mag = direction.dot(toCenter);
  6653. minDist = Math.min(mag, minDist);
  6654. maxDist = Math.max(mag, maxDist);
  6655. corner.copy(center).add(u).add(v).subtract(w);
  6656. toCenter.copy(corner).subtract(position);
  6657. mag = direction.dot(toCenter);
  6658. minDist = Math.min(mag, minDist);
  6659. maxDist = Math.max(mag, maxDist);
  6660. corner.copy(center).add(u).subtract(v).add(w);
  6661. toCenter.copy(corner).subtract(position);
  6662. mag = direction.dot(toCenter);
  6663. minDist = Math.min(mag, minDist);
  6664. maxDist = Math.max(mag, maxDist);
  6665. corner.copy(center).add(u).subtract(v).subtract(w);
  6666. toCenter.copy(corner).subtract(position);
  6667. mag = direction.dot(toCenter);
  6668. minDist = Math.min(mag, minDist);
  6669. maxDist = Math.max(mag, maxDist);
  6670. center.copy(corner).subtract(u).add(v).add(w);
  6671. toCenter.copy(corner).subtract(position);
  6672. mag = direction.dot(toCenter);
  6673. minDist = Math.min(mag, minDist);
  6674. maxDist = Math.max(mag, maxDist);
  6675. center.copy(corner).subtract(u).add(v).subtract(w);
  6676. toCenter.copy(corner).subtract(position);
  6677. mag = direction.dot(toCenter);
  6678. minDist = Math.min(mag, minDist);
  6679. maxDist = Math.max(mag, maxDist);
  6680. center.copy(corner).subtract(u).subtract(v).add(w);
  6681. toCenter.copy(corner).subtract(position);
  6682. mag = direction.dot(toCenter);
  6683. minDist = Math.min(mag, minDist);
  6684. maxDist = Math.max(mag, maxDist);
  6685. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6686. toCenter.copy(corner).subtract(position);
  6687. mag = direction.dot(toCenter);
  6688. minDist = Math.min(mag, minDist);
  6689. maxDist = Math.max(mag, maxDist);
  6690. result[0] = minDist;
  6691. result[1] = maxDist;
  6692. return result;
  6693. }
  6694. transform(transformation) {
  6695. this.center.transformAsPoint(transformation);
  6696. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6697. xAxis.transformAsPoint(transformation);
  6698. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6699. yAxis.transformAsPoint(transformation);
  6700. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6701. zAxis.transformAsPoint(transformation);
  6702. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6703. return this;
  6704. }
  6705. getTransform() {
  6706. throw new Error('not implemented');
  6707. }
  6708. }
  6709. const scratchPosition$1 = new Vector3();
  6710. const scratchNormal$1 = new Vector3();
  6711. class Plane {
  6712. constructor(normal = [0, 0, 1], distance = 0) {
  6713. this.normal = new Vector3();
  6714. this.distance = -0;
  6715. this.fromNormalDistance(normal, distance);
  6716. }
  6717. fromNormalDistance(normal, distance) {
  6718. assert$4(Number.isFinite(distance));
  6719. this.normal.from(normal).normalize();
  6720. this.distance = distance;
  6721. return this;
  6722. }
  6723. fromPointNormal(point, normal) {
  6724. point = scratchPosition$1.from(point);
  6725. this.normal.from(normal).normalize();
  6726. const distance = -this.normal.dot(point);
  6727. this.distance = distance;
  6728. return this;
  6729. }
  6730. fromCoefficients(a, b, c, d) {
  6731. this.normal.set(a, b, c);
  6732. assert$4(equals(this.normal.len(), 1));
  6733. this.distance = d;
  6734. return this;
  6735. }
  6736. clone(plane) {
  6737. return new Plane(this.normal, this.distance);
  6738. }
  6739. equals(right) {
  6740. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6741. }
  6742. getPointDistance(point) {
  6743. return this.normal.dot(point) + this.distance;
  6744. }
  6745. transform(matrix4) {
  6746. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6747. const point = this.normal.scale(-this.distance).transform(matrix4);
  6748. return this.fromPointNormal(point, normal);
  6749. }
  6750. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6751. point = scratchPosition$1.from(point);
  6752. const pointDistance = this.getPointDistance(point);
  6753. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6754. return point.subtract(scaledNormal).to(result);
  6755. }
  6756. }
  6757. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6758. const scratchPlaneCenter = new Vector3();
  6759. const scratchPlaneNormal$1 = new Vector3();
  6760. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6761. class CullingVolume {
  6762. static get MASK_OUTSIDE() {
  6763. return 0xffffffff;
  6764. }
  6765. static get MASK_INSIDE() {
  6766. return 0x00000000;
  6767. }
  6768. static get MASK_INDETERMINATE() {
  6769. return 0x7fffffff;
  6770. }
  6771. constructor(planes = []) {
  6772. this.planes = planes;
  6773. assert$4(this.planes.every(plane => plane instanceof Plane));
  6774. }
  6775. fromBoundingSphere(boundingSphere) {
  6776. this.planes.length = 2 * faces.length;
  6777. const center = boundingSphere.center;
  6778. const radius = boundingSphere.radius;
  6779. let planeIndex = 0;
  6780. for (const faceNormal of faces) {
  6781. let plane0 = this.planes[planeIndex];
  6782. let plane1 = this.planes[planeIndex + 1];
  6783. if (!plane0) {
  6784. plane0 = this.planes[planeIndex] = new Plane();
  6785. }
  6786. if (!plane1) {
  6787. plane1 = this.planes[planeIndex + 1] = new Plane();
  6788. }
  6789. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6790. -faceNormal.dot(plane0Center);
  6791. plane0.fromPointNormal(plane0Center, faceNormal);
  6792. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6793. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6794. -negatedFaceNormal.dot(plane1Center);
  6795. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6796. planeIndex += 2;
  6797. }
  6798. return this;
  6799. }
  6800. computeVisibility(boundingVolume) {
  6801. assert$4(boundingVolume);
  6802. let intersect = INTERSECTION.INSIDE;
  6803. for (const plane of this.planes) {
  6804. const result = boundingVolume.intersectPlane(plane);
  6805. switch (result) {
  6806. case INTERSECTION.OUTSIDE:
  6807. return INTERSECTION.OUTSIDE;
  6808. case INTERSECTION.INTERSECTING:
  6809. intersect = INTERSECTION.INTERSECTING;
  6810. break;
  6811. }
  6812. }
  6813. return intersect;
  6814. }
  6815. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6816. assert$4(boundingVolume, 'boundingVolume is required.');
  6817. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6818. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6819. return parentPlaneMask;
  6820. }
  6821. let mask = CullingVolume.MASK_INSIDE;
  6822. const planes = this.planes;
  6823. for (let k = 0; k < this.planes.length; ++k) {
  6824. const flag = k < 31 ? 1 << k : 0;
  6825. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6826. continue;
  6827. }
  6828. const plane = planes[k];
  6829. const result = boundingVolume.intersectPlane(plane);
  6830. if (result === INTERSECTION.OUTSIDE) {
  6831. return CullingVolume.MASK_OUTSIDE;
  6832. } else if (result === INTERSECTION.INTERSECTING) {
  6833. mask |= flag;
  6834. }
  6835. }
  6836. return mask;
  6837. }
  6838. }
  6839. const scratchPlaneUpVector = new Vector3();
  6840. const scratchPlaneRightVector = new Vector3();
  6841. const scratchPlaneNearCenter = new Vector3();
  6842. const scratchPlaneFarCenter = new Vector3();
  6843. const scratchPlaneNormal = new Vector3();
  6844. class PerspectiveOffCenterFrustum {
  6845. constructor(options = {}) {
  6846. options = {
  6847. near: 1.0,
  6848. far: 500000000.0,
  6849. ...options
  6850. };
  6851. this.left = options.left;
  6852. this._left = undefined;
  6853. this.right = options.right;
  6854. this._right = undefined;
  6855. this.top = options.top;
  6856. this._top = undefined;
  6857. this.bottom = options.bottom;
  6858. this._bottom = undefined;
  6859. this.near = options.near;
  6860. this._near = this.near;
  6861. this.far = options.far;
  6862. this._far = this.far;
  6863. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6864. this._perspectiveMatrix = new Matrix4();
  6865. this._infinitePerspective = new Matrix4();
  6866. }
  6867. clone() {
  6868. return new PerspectiveOffCenterFrustum({
  6869. right: this.right,
  6870. left: this.left,
  6871. top: this.top,
  6872. bottom: this.bottom,
  6873. near: this.near,
  6874. far: this.far
  6875. });
  6876. }
  6877. equals(other) {
  6878. 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;
  6879. }
  6880. get projectionMatrix() {
  6881. update$1(this);
  6882. return this._perspectiveMatrix;
  6883. }
  6884. get infiniteProjectionMatrix() {
  6885. update$1(this);
  6886. return this._infinitePerspective;
  6887. }
  6888. computeCullingVolume(position, direction, up) {
  6889. assert$4(position, 'position is required.');
  6890. assert$4(direction, 'direction is required.');
  6891. assert$4(up, 'up is required.');
  6892. const planes = this._cullingVolume.planes;
  6893. up = scratchPlaneUpVector.copy(up).normalize();
  6894. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6895. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6896. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6897. let normal = scratchPlaneNormal;
  6898. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6899. planes[0].fromPointNormal(position, normal);
  6900. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6901. planes[1].fromPointNormal(position, normal);
  6902. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6903. planes[2].fromPointNormal(position, normal);
  6904. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6905. planes[3].fromPointNormal(position, normal);
  6906. normal = new Vector3().copy(direction);
  6907. planes[4].fromPointNormal(nearCenter, normal);
  6908. normal.negate();
  6909. planes[5].fromPointNormal(farCenter, normal);
  6910. return this._cullingVolume;
  6911. }
  6912. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6913. update$1(this);
  6914. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6915. assert$4(drawingBufferWidth > 0);
  6916. assert$4(drawingBufferHeight > 0);
  6917. assert$4(distance > 0);
  6918. assert$4(result);
  6919. const inverseNear = 1.0 / this.near;
  6920. let tanTheta = this.top * inverseNear;
  6921. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6922. tanTheta = this.right * inverseNear;
  6923. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6924. result.x = pixelWidth;
  6925. result.y = pixelHeight;
  6926. return result;
  6927. }
  6928. }
  6929. function update$1(frustum) {
  6930. 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));
  6931. const {
  6932. top,
  6933. bottom,
  6934. right,
  6935. left,
  6936. near,
  6937. far
  6938. } = frustum;
  6939. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6940. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6941. frustum._left = left;
  6942. frustum._right = right;
  6943. frustum._top = top;
  6944. frustum._bottom = bottom;
  6945. frustum._near = near;
  6946. frustum._far = far;
  6947. frustum._perspectiveMatrix = new Matrix4().frustum({
  6948. left,
  6949. right,
  6950. bottom,
  6951. top,
  6952. near,
  6953. far
  6954. });
  6955. frustum._infinitePerspective = new Matrix4().frustum({
  6956. left,
  6957. right,
  6958. bottom,
  6959. top,
  6960. near,
  6961. far: Infinity
  6962. });
  6963. }
  6964. }
  6965. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6966. class PerspectiveFrustum {
  6967. constructor(options = {}) {
  6968. options = {
  6969. near: 1.0,
  6970. far: 500000000.0,
  6971. xOffset: 0.0,
  6972. yOffset: 0.0,
  6973. ...options
  6974. };
  6975. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6976. this.fov = options.fov;
  6977. this._fov = undefined;
  6978. this._fovy = undefined;
  6979. this._sseDenominator = undefined;
  6980. this.aspectRatio = options.aspectRatio;
  6981. this._aspectRatio = undefined;
  6982. this.near = options.near;
  6983. this._near = this.near;
  6984. this.far = options.far;
  6985. this._far = this.far;
  6986. this.xOffset = options.xOffset;
  6987. this._xOffset = this.xOffset;
  6988. this.yOffset = options.yOffset;
  6989. this._yOffset = this.yOffset;
  6990. }
  6991. clone() {
  6992. return new PerspectiveFrustum({
  6993. aspectRatio: this.aspectRatio,
  6994. fov: this.fov,
  6995. near: this.near,
  6996. far: this.far
  6997. });
  6998. }
  6999. equals(other) {
  7000. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  7001. return false;
  7002. }
  7003. update(this);
  7004. update(other);
  7005. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  7006. }
  7007. get projectionMatrix() {
  7008. update(this);
  7009. return this._offCenterFrustum.projectionMatrix;
  7010. }
  7011. get infiniteProjectionMatrix() {
  7012. update(this);
  7013. return this._offCenterFrustum.infiniteProjectionMatrix;
  7014. }
  7015. get fovy() {
  7016. update(this);
  7017. return this._fovy;
  7018. }
  7019. get sseDenominator() {
  7020. update(this);
  7021. return this._sseDenominator;
  7022. }
  7023. computeCullingVolume(position, direction, up) {
  7024. update(this);
  7025. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  7026. }
  7027. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7028. update(this);
  7029. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  7030. }
  7031. }
  7032. function update(frustum) {
  7033. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  7034. const f = frustum._offCenterFrustum;
  7035. 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) {
  7036. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  7037. //assert$4(frustum.aspectRatio > 0);
  7038. if(frustum.aspectRatio == 0){
  7039. console.log(1)
  7040. }
  7041. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  7042. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  7043. frustum._fov = frustum.fov;
  7044. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  7045. frustum._near = frustum.near;
  7046. frustum._far = frustum.far;
  7047. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  7048. frustum._xOffset = frustum.xOffset;
  7049. frustum._yOffset = frustum.yOffset;
  7050. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  7051. f.bottom = -f.top;
  7052. f.right = frustum._aspectRatio * f.top;
  7053. f.left = -f.right;
  7054. f.near = frustum.near;
  7055. f.far = frustum.far;
  7056. f.right += frustum.xOffset;
  7057. f.left += frustum.xOffset;
  7058. f.top += frustum.yOffset;
  7059. f.bottom += frustum.yOffset;
  7060. }
  7061. }
  7062. new Vector3();
  7063. new Vector3();
  7064. new Vector3();
  7065. new Vector3();
  7066. new Vector3();
  7067. new Vector3();
  7068. new Vector3();
  7069. new Vector3();
  7070. new Vector3();
  7071. new Vector3();
  7072. new Vector3();
  7073. new Vector3();
  7074. new Matrix3();
  7075. new Matrix3();
  7076. new Matrix3();
  7077. new Matrix3();
  7078. new Matrix3();
  7079. new Vector3();
  7080. new Vector3();
  7081. new Vector3();
  7082. new Vector3();
  7083. new Vector3();
  7084. new Matrix3();
  7085. ({
  7086. diagonal: new Matrix3(),
  7087. unitary: new Matrix3()
  7088. });
  7089. const scratchVector$2 = new Vector3();
  7090. const scratchPosition = new Vector3();
  7091. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7092. function getFrameState(viewport, frameNumber) {
  7093. const {
  7094. cameraDirection,
  7095. cameraUp,
  7096. height
  7097. } = viewport;
  7098. const {
  7099. metersPerUnit
  7100. } = viewport.distanceScales;
  7101. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7102. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7103. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7104. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7105. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7106. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7107. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7108. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7109. return {
  7110. camera: {
  7111. position: cameraPositionCartesian,
  7112. direction: cameraDirectionCartesian,
  7113. up: cameraUpCartesian
  7114. },
  7115. viewport,
  7116. height,
  7117. cullingVolume,
  7118. frameNumber,
  7119. sseDenominator: 1.15
  7120. };
  7121. }
  7122. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7123. const frustumPlanes = viewport.getFrustumPlanes();
  7124. let i = 0;
  7125. for (const dir in frustumPlanes) {
  7126. const plane = frustumPlanes[dir];
  7127. const distanceToCenter = plane.normal.dot(viewport.center);
  7128. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7129. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7130. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7131. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7132. }
  7133. }
  7134. const WGS84_RADIUS_X = 6378137.0;
  7135. const WGS84_RADIUS_Y = 6378137.0;
  7136. const WGS84_RADIUS_Z = 6356752.3142451793;
  7137. const scratchVector$1 = new Vector3();
  7138. function getZoomFromBoundingVolume(boundingVolume) {
  7139. const {
  7140. halfAxes,
  7141. radius,
  7142. width,
  7143. height
  7144. } = boundingVolume;
  7145. if (halfAxes) {
  7146. const obbSize = getObbSize(halfAxes);
  7147. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7148. } else if (radius) {
  7149. return Math.log2(WGS84_RADIUS_Z / radius);
  7150. } else if (height && width) {
  7151. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7152. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7153. return (zoomX + zoomY) / 2;
  7154. }
  7155. return 1;
  7156. }
  7157. function getObbSize(halfAxes) {
  7158. halfAxes.getColumn(0, scratchVector$1);
  7159. const axeY = halfAxes.getColumn(1);
  7160. const axeZ = halfAxes.getColumn(2);
  7161. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7162. const size = farthestVertex.len();
  7163. return size;
  7164. }
  7165. const TILE_CONTENT_STATE = {
  7166. UNLOADED: 0,
  7167. LOADING: 1,
  7168. PROCESSING: 2,
  7169. READY: 3,
  7170. EXPIRED: 4,
  7171. FAILED: 5
  7172. };
  7173. const TILE_REFINEMENT = {
  7174. ADD: 1,
  7175. REPLACE: 2
  7176. };
  7177. const TILE_TYPE = {
  7178. EMPTY: 'empty',
  7179. SCENEGRAPH: 'scenegraph',
  7180. POINTCLOUD: 'pointcloud',
  7181. MESH: 'mesh'
  7182. };
  7183. const TILESET_TYPE = {
  7184. I3S: 'I3S',
  7185. TILES3D: 'TILES3D'
  7186. };
  7187. const LOD_METRIC_TYPE = {
  7188. GEOMETRIC_ERROR: 'geometricError',
  7189. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7190. };
  7191. const TILE3D_OPTIMIZATION_HINT = {
  7192. NOT_COMPUTED: -1,
  7193. USE_OPTIMIZATION: 1,
  7194. SKIP_OPTIMIZATION: 0
  7195. };
  7196. function defined$3(x) {
  7197. return x !== undefined && x !== null;
  7198. }
  7199. const scratchScale = new Vector3();
  7200. const scratchNorthWest = new Vector3();
  7201. const scratchSouthEast = new Vector3();
  7202. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7203. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7204. if (boundingVolumeHeader.box) {
  7205. return createBox(boundingVolumeHeader.box, transform, result);
  7206. }
  7207. if (boundingVolumeHeader.region) {
  7208. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7209. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7210. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7211. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7212. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7213. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7214. }
  7215. if (boundingVolumeHeader.sphere) {
  7216. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7217. }
  7218. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7219. }
  7220. function createBox(box, transform, result) {
  7221. const center = new Vector3(box[0], box[1], box[2]);
  7222. result && (result.oriCenter = center)//add
  7223. transform.transform(center, center);
  7224. let origin = [];
  7225. if (box.length === 10) {
  7226. const halfSize = box.slice(3, 6);
  7227. const quaternion = new Quaternion();
  7228. quaternion.fromArray(box, 6);
  7229. const x = new Vector3([1, 0, 0]);
  7230. const y = new Vector3([0, 1, 0]);
  7231. const z = new Vector3([0, 0, 1]);
  7232. x.transformByQuaternion(quaternion);
  7233. x.scale(halfSize[0]);
  7234. y.transformByQuaternion(quaternion);
  7235. y.scale(halfSize[1]);
  7236. z.transformByQuaternion(quaternion);
  7237. z.scale(halfSize[2]);
  7238. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7239. } else {
  7240. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7241. }
  7242. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7243. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7244. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7245. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7246. //const halfAxes = new Matrix3([xAxis[0], xAxis[1], -xAxis[2], yAxis[0], yAxis[1], -yAxis[2], zAxis[0], zAxis[1], -zAxis[2]]);//改
  7247. //center.z *= -1//add
  7248. if (defined$3(result)) {
  7249. result.center = center;
  7250. result.halfAxes = halfAxes;
  7251. return result;
  7252. }
  7253. return new OrientedBoundingBox(center, halfAxes);
  7254. }
  7255. function createSphere(sphere, transform, result) {
  7256. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7257. transform.transform(center, center);
  7258. const scale = transform.getScale(scratchScale);
  7259. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7260. const radius = sphere[3] * uniformScale;
  7261. if (defined$3(result)) {
  7262. result.center = center;
  7263. result.radius = radius;
  7264. return result;
  7265. }
  7266. return new BoundingSphere(center, radius);
  7267. }
  7268. new Vector3();
  7269. new Vector3();
  7270. new Matrix4();
  7271. new Vector3();
  7272. new Vector3();
  7273. new Vector3();
  7274. function fog(distanceToCamera, density) {
  7275. const scalar = distanceToCamera * density;
  7276. return 1.0 - Math.exp(-(scalar * scalar));
  7277. }
  7278. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7279. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7280. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7281. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7282. const dynamicError = fog(distanceToCamera, density) * factor;
  7283. return dynamicError;
  7284. }
  7285. return 0;
  7286. }
  7287. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7288. const tileset = tile.tileset;
  7289. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7290. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7291. if (lodMetricValue === 0.0) {
  7292. return 0.0;
  7293. }
  7294. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7295. const {
  7296. height,
  7297. sseDenominator
  7298. } = frameState;
  7299. const {
  7300. viewDistanceScale
  7301. } = tileset.options;
  7302. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7303. error -= getDynamicScreenSpaceError(tileset, distance);
  7304. return error;
  7305. }
  7306. function getLodStatus(tile, frameState) {
  7307. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7308. return 'DIG';
  7309. }
  7310. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7311. if (screenSize < 2) {
  7312. return 'OUT';
  7313. }
  7314. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7315. return 'DRAW';
  7316. } else if (tile.header.children) {
  7317. return 'DIG';
  7318. }
  7319. return 'OUT';
  7320. }
  7321. function getProjectedRadius(tile, frameState) {
  7322. const originalViewport = frameState.viewport;
  7323. const ViewportClass = originalViewport.constructor;
  7324. const {
  7325. longitude,
  7326. latitude,
  7327. height,
  7328. width,
  7329. bearing,
  7330. zoom
  7331. } = originalViewport;
  7332. const viewport = new ViewportClass({
  7333. longitude,
  7334. latitude,
  7335. height,
  7336. width,
  7337. bearing,
  7338. zoom,
  7339. pitch: 0
  7340. });
  7341. const mbsLat = tile.header.mbs[1];
  7342. const mbsLon = tile.header.mbs[0];
  7343. const mbsZ = tile.header.mbs[2];
  7344. const mbsR = tile.header.mbs[3];
  7345. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7346. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7347. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7348. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7349. const enuToCartesianMatrix = new Matrix4();
  7350. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7351. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7352. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7353. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7354. const extraZ = projection * projection / cameraPositionEnu[2];
  7355. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7356. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7357. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7358. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7359. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7360. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7361. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7362. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7363. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7364. return projectedRadius;
  7365. }
  7366. function get3dTilesOptions(tileset) {
  7367. return {
  7368. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7369. };
  7370. }
  7371. class ManagedArray {
  7372. constructor(length = 0) {
  7373. _defineProperty(this, "_map", new Map());
  7374. _defineProperty(this, "_array", void 0);
  7375. _defineProperty(this, "_length", void 0);
  7376. this._array = new Array(length);
  7377. this._length = length;
  7378. }
  7379. get length() {
  7380. return this._length;
  7381. }
  7382. set length(length) {
  7383. this._length = length;
  7384. if (length > this._array.length) {
  7385. this._array.length = length;
  7386. }
  7387. }
  7388. get values() {
  7389. return this._array;
  7390. }
  7391. get(index) {
  7392. assert$7(index < this._array.length);
  7393. return this._array[index];
  7394. }
  7395. set(index, element) {
  7396. assert$7(index >= 0);
  7397. if (index >= this.length) {
  7398. this.length = index + 1;
  7399. }
  7400. if (this._map.has(this._array[index])) {
  7401. this._map.delete(this._array[index]);
  7402. }
  7403. this._array[index] = element;
  7404. this._map.set(element, index);
  7405. }
  7406. delete(element) {
  7407. const index = this._map.get(element);
  7408. if (index >= 0) {
  7409. this._array.splice(index, 1);
  7410. this._map.delete(element);
  7411. this.length--;
  7412. }
  7413. }
  7414. peek() {
  7415. return this._array[this._length - 1];
  7416. }
  7417. push(element) {
  7418. if (!this._map.has(element)) {
  7419. const index = this.length++;
  7420. this._array[index] = element;
  7421. this._map.set(element, index);
  7422. }
  7423. }
  7424. pop() {
  7425. const element = this._array[--this.length];
  7426. this._map.delete(element);
  7427. return element;
  7428. }
  7429. reserve(length) {
  7430. assert$7(length >= 0);
  7431. if (length > this._array.length) {
  7432. this._array.length = length;
  7433. }
  7434. }
  7435. resize(length) {
  7436. assert$7(length >= 0);
  7437. this.length = length;
  7438. }
  7439. trim(length) {
  7440. if (length === null || length === undefined) {
  7441. length = this.length;
  7442. }
  7443. this._array.length = length;
  7444. }
  7445. reset() {
  7446. this._array = [];
  7447. this._map = new Map();
  7448. this._length = 0;
  7449. }
  7450. find(target) {
  7451. return this._map.has(target);
  7452. }
  7453. }
  7454. const DEFAULT_PROPS$1 = {
  7455. loadSiblings: false,
  7456. skipLevelOfDetail: false,
  7457. maximumScreenSpaceError: 2,
  7458. updateTransforms: true,
  7459. onTraversalEnd: () => {},
  7460. viewportTraversersMap: {},
  7461. basePath: ''
  7462. };
  7463. class TilesetTraverser {
  7464. constructor(options) {
  7465. _defineProperty(this, "options", void 0);
  7466. _defineProperty(this, "root", void 0);
  7467. _defineProperty(this, "requestedTiles", void 0);
  7468. _defineProperty(this, "selectedTiles", void 0);
  7469. _defineProperty(this, "emptyTiles", void 0);
  7470. _defineProperty(this, "_traversalStack", void 0);
  7471. _defineProperty(this, "_emptyTraversalStack", void 0);
  7472. _defineProperty(this, "_frameNumber", void 0);
  7473. this.options = { ...DEFAULT_PROPS$1,
  7474. ...options
  7475. };
  7476. this._traversalStack = new ManagedArray();
  7477. this._emptyTraversalStack = new ManagedArray();
  7478. this._frameNumber = null;
  7479. this.root = null;
  7480. this.selectedTiles = {};
  7481. this.requestedTiles = {};
  7482. this.emptyTiles = {};
  7483. }
  7484. traverse(root, frameState, options) {
  7485. this.root = root;
  7486. this.options = { ...this.options,
  7487. ...options
  7488. };
  7489. this.reset();
  7490. this.updateTile(root, frameState);
  7491. this._frameNumber = frameState.frameNumber;
  7492. this.executeTraversal(root, frameState);
  7493. }
  7494. reset() {
  7495. this.requestedTiles = {};
  7496. this.selectedTiles = {};
  7497. this.emptyTiles = {};
  7498. this._traversalStack.reset();
  7499. this._emptyTraversalStack.reset();
  7500. }
  7501. executeTraversal(root, frameState) {// 遍历root
  7502. const stack = this._traversalStack;
  7503. root._selectionDepth = 1;
  7504. stack.push(root);
  7505. while (stack.length > 0) {
  7506. const tile = stack.pop();
  7507. let shouldRefine = false;
  7508. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7509. if (this.canTraverse(tile, frameState) && (tile.depth < /* this.options. */maxDepth || tile.type != 'scenegraph' )) {//add maxDepth 是否继续遍历子集
  7510. this.updateChildTiles(tile, frameState);
  7511. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7512. }
  7513. const parent = tile.parent;
  7514. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7515. const stoppedRefining = !shouldRefine;
  7516. if (!tile.hasRenderContent) {
  7517. this.emptyTiles[tile.id] = tile;
  7518. this.loadTile(tile, frameState);
  7519. if (stoppedRefining) {
  7520. this.selectTile(tile, frameState);
  7521. }
  7522. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7523. this.loadTile(tile, frameState);
  7524. this.selectTile(tile, frameState);
  7525. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7526. this.loadTile(tile, frameState);
  7527. if (stoppedRefining) {
  7528. this.selectTile(tile, frameState);
  7529. }
  7530. }
  7531. this.touchTile(tile, frameState);
  7532. tile._shouldRefine = shouldRefine && parentRefines;
  7533. }
  7534. this.options.onTraversalEnd(frameState);
  7535. }
  7536. updateChildTiles(tile, frameState) {
  7537. const children = tile.children;
  7538. for (const child of children) {
  7539. this.updateTile(child, frameState);
  7540. }
  7541. return true;
  7542. }
  7543. updateAndPushChildren(tile, frameState, stack, depth) {
  7544. const {
  7545. loadSiblings,
  7546. skipLevelOfDetail
  7547. } = this.options;
  7548. const children = tile.children;
  7549. children.sort(this.compareDistanceToCamera.bind(this));
  7550. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7551. let hasVisibleChild = false;
  7552. let refines = true;
  7553. for (const child of children) {
  7554. child._selectionDepth = depth;
  7555. if (child.isVisibleAndInRequestVolume) {
  7556. if (stack.find(child)) {
  7557. stack.delete(child);
  7558. }
  7559. stack.push(child);
  7560. hasVisibleChild = true;
  7561. } else if (checkRefines || loadSiblings) {
  7562. this.loadTile(child, frameState);
  7563. this.touchTile(child, frameState);
  7564. }
  7565. if (checkRefines) {
  7566. let childRefines;
  7567. if (!child._inRequestVolume) {
  7568. childRefines = false;
  7569. } else if (!child.hasRenderContent) {
  7570. childRefines = this.executeEmptyTraversal(child, frameState);
  7571. } else {
  7572. childRefines = child.contentAvailable;
  7573. }
  7574. refines = refines && childRefines;
  7575. if (!refines) {
  7576. return false;
  7577. }
  7578. }
  7579. }
  7580. if (!hasVisibleChild) {
  7581. refines = false;
  7582. }
  7583. return refines;
  7584. }
  7585. updateTile(tile, frameState) {
  7586. this.updateTileVisibility(tile, frameState);
  7587. }
  7588. selectTile(tile, frameState) {
  7589. if (this.shouldSelectTile(tile)) {
  7590. tile._selectedFrame = frameState.frameNumber;
  7591. this.selectedTiles[tile.id] = tile;
  7592. }
  7593. }
  7594. loadTile(tile, frameState) {
  7595. if (this.shouldLoadTile(tile)) {
  7596. tile._requestedFrame = frameState.frameNumber;
  7597. tile._priority = tile._getPriority();
  7598. this.requestedTiles[tile.id] = tile;
  7599. }
  7600. }
  7601. touchTile(tile, frameState) {
  7602. tile.tileset._cache.touch(tile);
  7603. tile._touchedFrame = frameState.frameNumber;
  7604. }
  7605. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7606. if (!tile.hasChildren) {
  7607. return false;
  7608. }
  7609. if (tile.hasTilesetContent) {
  7610. return !tile.contentExpired;
  7611. }
  7612. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7613. return false;
  7614. }
  7615. return this.shouldRefine(tile, frameState, useParentMetric);
  7616. }
  7617. shouldLoadTile(tile) {
  7618. return tile.hasUnloadedContent || tile.contentExpired;
  7619. }
  7620. shouldSelectTile(tile) {
  7621. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7622. }
  7623. shouldRefine(tile, frameState, useParentMetric) {
  7624. let screenSpaceError = tile._screenSpaceError;
  7625. if (useParentMetric) {
  7626. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7627. }
  7628. return screenSpaceError > this.options.maximumScreenSpaceError;
  7629. }
  7630. updateTileVisibility(tile, frameState) {
  7631. const viewportIds = [];
  7632. if (this.options.viewportTraversersMap) {
  7633. for (const key in this.options.viewportTraversersMap) {
  7634. const value = this.options.viewportTraversersMap[key];
  7635. if (value === frameState.viewport.id) {
  7636. viewportIds.push(key);
  7637. }
  7638. }
  7639. } else {
  7640. viewportIds.push(frameState.viewport.id);
  7641. }
  7642. tile.updateVisibility(frameState, viewportIds);
  7643. }
  7644. compareDistanceToCamera(b, a) {
  7645. return b._distanceToCamera - a._distanceToCamera;
  7646. }
  7647. anyChildrenVisible(tile, frameState) {
  7648. let anyVisible = false;
  7649. for (const child of tile.children) {
  7650. child.updateVisibility(frameState);
  7651. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7652. }
  7653. return anyVisible;
  7654. }
  7655. executeEmptyTraversal(root, frameState) {
  7656. let allDescendantsLoaded = true;
  7657. const stack = this._emptyTraversalStack;
  7658. stack.push(root);
  7659. while (stack.length > 0 && allDescendantsLoaded) {
  7660. const tile = stack.pop();
  7661. this.updateTile(tile, frameState);
  7662. if (!tile.isVisibleAndInRequestVolume) {
  7663. this.loadTile(tile, frameState);
  7664. }
  7665. this.touchTile(tile, frameState);
  7666. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7667. if (traverse) {
  7668. const children = tile.children;
  7669. for (const child of children) {
  7670. if (stack.find(child)) {
  7671. stack.delete(child);
  7672. }
  7673. stack.push(child);
  7674. }
  7675. } else if (!tile.contentAvailable) {
  7676. allDescendantsLoaded = false;
  7677. }
  7678. }
  7679. return allDescendantsLoaded;
  7680. }
  7681. }
  7682. const scratchVector = new Vector3();
  7683. function defined$2(x) {
  7684. return x !== undefined && x !== null;
  7685. }
  7686. class TileHeader {
  7687. constructor(tileset, header, parentHeader, extendedId = '') {
  7688. _defineProperty(this, "tileset", void 0);
  7689. _defineProperty(this, "header", void 0);
  7690. _defineProperty(this, "id", void 0);
  7691. _defineProperty(this, "url", void 0);
  7692. _defineProperty(this, "parent", void 0);
  7693. _defineProperty(this, "refine", void 0);
  7694. _defineProperty(this, "type", void 0);
  7695. _defineProperty(this, "contentUrl", void 0);
  7696. _defineProperty(this, "lodMetricType", void 0);
  7697. _defineProperty(this, "lodMetricValue", void 0);
  7698. _defineProperty(this, "boundingVolume", void 0);
  7699. _defineProperty(this, "content", void 0);
  7700. _defineProperty(this, "contentState", void 0);
  7701. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7702. _defineProperty(this, "children", void 0);
  7703. _defineProperty(this, "depth", void 0);
  7704. _defineProperty(this, "viewportIds", void 0);
  7705. _defineProperty(this, "transform", void 0);
  7706. _defineProperty(this, "extensions", void 0);
  7707. _defineProperty(this, "userData", void 0);
  7708. _defineProperty(this, "computedTransform", void 0);
  7709. _defineProperty(this, "hasEmptyContent", void 0);
  7710. _defineProperty(this, "hasTilesetContent", void 0);
  7711. _defineProperty(this, "traverser", void 0);
  7712. _defineProperty(this, "_cacheNode", void 0);
  7713. _defineProperty(this, "_frameNumber", void 0);
  7714. _defineProperty(this, "_lodJudge", void 0);
  7715. _defineProperty(this, "_expireDate", void 0);
  7716. _defineProperty(this, "_expiredContent", void 0);
  7717. _defineProperty(this, "_shouldRefine", void 0);
  7718. _defineProperty(this, "_distanceToCamera", void 0);
  7719. _defineProperty(this, "_centerZDepth", void 0);
  7720. _defineProperty(this, "_screenSpaceError", void 0);
  7721. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7722. _defineProperty(this, "_visible", void 0);
  7723. _defineProperty(this, "_inRequestVolume", void 0);
  7724. _defineProperty(this, "_stackLength", void 0);
  7725. _defineProperty(this, "_selectionDepth", void 0);
  7726. _defineProperty(this, "_touchedFrame", void 0);
  7727. _defineProperty(this, "_visitedFrame", void 0);
  7728. _defineProperty(this, "_selectedFrame", void 0);
  7729. _defineProperty(this, "_requestedFrame", void 0);
  7730. _defineProperty(this, "_priority", void 0);
  7731. _defineProperty(this, "_contentBoundingVolume", void 0);
  7732. _defineProperty(this, "_viewerRequestVolume", void 0);
  7733. _defineProperty(this, "_initialTransform", void 0);
  7734. _defineProperty(this, "tilesetMatrix", void 0);//add
  7735. _defineProperty(this, "tileContent", void 0);//add
  7736. _defineProperty(this, "contentTransform", void 0);//add
  7737. _defineProperty(this, "volumeBox", void 0);//add
  7738. _defineProperty(this, "boundUntransformed", void 0);//add
  7739. _defineProperty(this, "rtcCenterState", rtcCenterGlobal);//add 初始时的状态,当mesh加载完检查下
  7740. _defineProperty(this, "posCount", 0);//add
  7741. _defineProperty(this, "texArea", 0);//add
  7742. this.header = header;
  7743. this.tileset = tileset;
  7744. this.id = extendedId || header.id;
  7745. this.url = header.url;
  7746. this.parent = parentHeader;
  7747. this.refine = this._getRefine(header.refine);
  7748. this.type = header.type;
  7749. this.contentUrl = header.contentUrl;
  7750. this.lodMetricType = 'geometricError';
  7751. this.lodMetricValue = 0;
  7752. this.boundingVolume = null;
  7753. this.content = null;
  7754. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7755. this.gpuMemoryUsageInBytes = 0;
  7756. this.children = [];
  7757. this.hasEmptyContent = false;
  7758. this.hasTilesetContent = false;
  7759. this.depth = 0;
  7760. this.viewportIds = [];
  7761. this.userData = {};
  7762. this.extensions = null;
  7763. this._priority = 0;
  7764. this._touchedFrame = 0;
  7765. this._visitedFrame = 0;
  7766. this._selectedFrame = 0;
  7767. this._requestedFrame = 0;
  7768. this._screenSpaceError = 0;
  7769. this._cacheNode = null;
  7770. this._frameNumber = null;
  7771. this._cacheNode = null;
  7772. this.traverser = new TilesetTraverser({});
  7773. this._shouldRefine = false;
  7774. this._distanceToCamera = 0;
  7775. this._centerZDepth = 0;
  7776. this._visible = undefined;
  7777. this._inRequestVolume = false;
  7778. this._stackLength = 0;
  7779. this._selectionDepth = 0;
  7780. this._initialTransform = new Matrix4();
  7781. this.transform = new Matrix4();
  7782. this._initializeLodMetric(header);
  7783. this._initializeTransforms(header);
  7784. this._initializeBoundingVolumes(header);
  7785. this._initializeContent(header);
  7786. this._initializeRenderingState(header);
  7787. this._lodJudge = null;
  7788. this._expireDate = null;
  7789. this._expiredContent = null;
  7790. Object.seal(this);
  7791. }
  7792. destroy() {
  7793. this.header = null;
  7794. }
  7795. isDestroyed() {
  7796. return this.header === null;
  7797. }
  7798. get selected() {
  7799. return this._selectedFrame === this.tileset._frameNumber;
  7800. }
  7801. get isVisible() {
  7802. return this._visible;
  7803. }
  7804. get isVisibleAndInRequestVolume() {
  7805. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  7806. if(window.tileVisi2)v = this._visible && v
  7807. return v
  7808. }
  7809. get hasRenderContent() {
  7810. return !this.hasEmptyContent && !this.hasTilesetContent;
  7811. }
  7812. get hasChildren() {
  7813. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7814. }
  7815. get contentReady() {
  7816. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7817. }
  7818. get contentAvailable() {
  7819. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7820. }
  7821. get hasUnloadedContent() {
  7822. return this.hasRenderContent && this.contentUnloaded;
  7823. }
  7824. get contentUnloaded() {
  7825. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7826. }
  7827. get contentExpired() {
  7828. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7829. }
  7830. get contentFailed() {
  7831. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7832. }
  7833. getScreenSpaceError(frameState, useParentLodMetric) {
  7834. switch (this.tileset.type) {
  7835. case TILESET_TYPE.I3S:
  7836. return getProjectedRadius(this, frameState);
  7837. case TILESET_TYPE.TILES3D:
  7838. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7839. default:
  7840. throw new Error('Unsupported tileset type');
  7841. }
  7842. }
  7843. get byteLength(){//add
  7844. let len = this.content?.byteLength || this.content?.gltf?.buffers[0].byteLength || 0 // 后者为glTF型的tile
  7845. if(len == 0 && this.tileContent)console.log('tile.byteLength == 0???') //url为json的话确实为0, 模型被删除后mesh没了也为0
  7846. return len
  7847. }
  7848. _getPriority() {
  7849. const traverser = this.tileset._traverser;
  7850. const {
  7851. skipLevelOfDetail
  7852. } = traverser.options;
  7853. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7854. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7855. return -1;
  7856. }
  7857. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7858. return -1;
  7859. }
  7860. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7861. return -1;
  7862. }
  7863. const parent = this.parent;
  7864. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7865. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7866. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7867. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7868. if(!this._visible){
  7869. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  7870. }
  7871. return v
  7872. }
  7873. async loadContent() {
  7874. if (this.hasEmptyContent) {
  7875. return false;
  7876. }
  7877. if (this.content) {
  7878. return true;
  7879. }
  7880. const expired = this.contentExpired;
  7881. if (expired) {
  7882. this._expireDate = null;
  7883. }
  7884. this.contentState = TILE_CONTENT_STATE.LOADING;
  7885. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7886. if (!requestToken) {
  7887. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7888. return false;
  7889. }
  7890. try {
  7891. const contentUrl = this.tileset.getTileUrl(this.contentUrl)+ `?_=${this.tileset.options.updateTime}` // !zeg改 添加version后缀 原:imageVersion
  7892. const loader = this.tileset.loader;
  7893. const options = { ...this.tileset.loadOptions,
  7894. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7895. isTileset: this.type === 'json',
  7896. ...this._getLoaderSpecificOptions(loader.id)
  7897. }
  7898. };
  7899. this.content = await load(contentUrl, loader, options);
  7900. // !zeg改
  7901. if (/* this.tileset.options. */maxDepth < this.depth && this.type == 'scenegraph') {//有的场景depth为1的不是mesh,只是json,即实际最低depth>1
  7902. this.unloadContent()
  7903. return false
  7904. }
  7905. if (this.tileset.options.contentLoader) {
  7906. await this.tileset.options.contentLoader(this);
  7907. }
  7908. if (this._isTileset()) {
  7909. this.tileset._initializeTileHeaders(this.content, this);
  7910. }
  7911. this.contentState = TILE_CONTENT_STATE.READY;
  7912. this._onContentLoaded();
  7913. return true;
  7914. } catch (error) {
  7915. this.contentState = TILE_CONTENT_STATE.FAILED;
  7916. throw error;
  7917. } finally {
  7918. requestToken.done();
  7919. }
  7920. }
  7921. unloadContent() {
  7922. if (this.content && this.content.destroy) {
  7923. this.content.destroy();
  7924. }
  7925. this.content = null;
  7926. if (this.header.content && this.header.content.destroy) {
  7927. this.header.content.destroy();
  7928. }
  7929. this.header.content = null;
  7930. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7931. return true;
  7932. }
  7933. updateVisibility(frameState, viewportIds) {
  7934. if (this._frameNumber === frameState.frameNumber) {
  7935. return;
  7936. }
  7937. const parent = this.parent;
  7938. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7939. if (this.tileset._traverser.options.updateTransforms) {
  7940. const parentTransform = parent ? parent.computedTransform : new Matrix4().elements //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  7941. this._updateTransform(parentTransform);
  7942. }
  7943. this._distanceToCamera = this.distanceToTile(frameState);
  7944. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7945. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7946. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7947. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7948. this._frameNumber = frameState.frameNumber;
  7949. this.viewportIds = viewportIds;
  7950. }
  7951. visibility(frameState, parentVisibilityPlaneMask) {
  7952. const {
  7953. cullingVolume
  7954. } = frameState;
  7955. const {
  7956. boundingVolume
  7957. } = this;
  7958. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7959. }
  7960. contentVisibility() {
  7961. return true;
  7962. }
  7963. distanceToTile(frameState) {
  7964. const boundingVolume = this.boundingVolume;
  7965. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7966. }
  7967. cameraSpaceZDepth({
  7968. camera
  7969. }) {
  7970. const boundingVolume = this.boundingVolume;
  7971. scratchVector.subVectors(boundingVolume.center, camera.position);
  7972. return camera.direction.dot(scratchVector);
  7973. }
  7974. insideViewerRequestVolume(frameState) {
  7975. const viewerRequestVolume = this._viewerRequestVolume;
  7976. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7977. }
  7978. updateExpiration() {
  7979. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7980. const now = Date.now();
  7981. if (Date.lessThan(this._expireDate, now)) {
  7982. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7983. this._expiredContent = this.content;
  7984. }
  7985. }
  7986. }
  7987. get extras() {
  7988. return this.header.extras;
  7989. }
  7990. _initializeLodMetric(header) {
  7991. if ('lodMetricType' in header) {
  7992. this.lodMetricType = header.lodMetricType;
  7993. } else {
  7994. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7995. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7996. }
  7997. if ('lodMetricValue' in header) {
  7998. this.lodMetricValue = header.lodMetricValue;
  7999. } else {
  8000. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  8001. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  8002. }
  8003. }
  8004. _initializeTransforms(tileHeader) {
  8005. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  8006. const parent = this.parent;
  8007. const tileset = this.tileset;
  8008. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4().elements // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  8009. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  8010. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  8011. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  8012. }
  8013. _initializeBoundingVolumes(tileHeader) {
  8014. this._contentBoundingVolume = null;
  8015. this._viewerRequestVolume = null;
  8016. this._updateBoundingVolume(tileHeader);
  8017. }
  8018. _initializeContent(tileHeader) {
  8019. this.content = {
  8020. _tileset: this.tileset,
  8021. _tile: this
  8022. };
  8023. this.hasEmptyContent = true;
  8024. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8025. this.hasTilesetContent = false;
  8026. if (tileHeader.contentUrl) {
  8027. this.content = null;
  8028. this.hasEmptyContent = false;
  8029. }
  8030. }
  8031. _initializeRenderingState(header) {
  8032. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  8033. this._shouldRefine = false;
  8034. this._distanceToCamera = 0;
  8035. this._centerZDepth = 0;
  8036. this._screenSpaceError = 0;
  8037. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  8038. this._visible = undefined;
  8039. this._inRequestVolume = false;
  8040. this._stackLength = 0;
  8041. this._selectionDepth = 0;
  8042. this._frameNumber = 0;
  8043. this._touchedFrame = 0;
  8044. this._visitedFrame = 0;
  8045. this._selectedFrame = 0;
  8046. this._requestedFrame = 0;
  8047. this._priority = 0.0;
  8048. }
  8049. _getRefine(refine) {
  8050. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  8051. }
  8052. _isTileset() {
  8053. return this.contentUrl.indexOf('.json') !== -1;
  8054. }
  8055. _onContentLoaded() {
  8056. switch (this.content && this.content.type) {
  8057. case 'vctr':
  8058. case 'geom':
  8059. this.tileset._traverser.disableSkipLevelOfDetail = true;
  8060. break;
  8061. }
  8062. if (this._isTileset()) {
  8063. this.hasTilesetContent = true;
  8064. }
  8065. }
  8066. _updateBoundingVolume(header) {
  8067. let computedTransform
  8068. /* if(header.id == 'root_0' || !header.id){
  8069. console.log('root_0')
  8070. } */
  8071. if(!this.tileset.lastRootTransform){//没事过后会因_updateTransform重算
  8072. computedTransform = new Matrix4(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  8073. }else{
  8074. computedTransform = new Matrix4(new Matrix4$1().multiplyMatrices(this.tileset.lastRootTransform, this.getContentTransform()).elements)
  8075. }
  8076. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  8077. const content = header.content;
  8078. if (!content) {
  8079. return;
  8080. }
  8081. if (content.boundingVolume) {
  8082. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  8083. }
  8084. if (header.viewerRequestVolume) {
  8085. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  8086. }
  8087. }
  8088. getBoundUntransformed(){//add 这个会在mesh加载好后才会执行
  8089. if(!this.contentTransform){
  8090. console.error('?')
  8091. }
  8092. this.getContentTransform()
  8093. let computedTransform2 = new Matrix4(this.contentTransform.elements)
  8094. this.boundUntransformed = createBoundingVolume(this.header.boundingVolume, computedTransform2 , this.boundUntransformed);//add
  8095. return this.boundUntransformed
  8096. }
  8097. getContentTransform(force){ //add 获取该tile在创建boundingVolume时需要的matrix,不包含最外层对整体模型的变换.
  8098. let rtcCenter, contentTransform
  8099. if(this.contentTransform && !force){//无需更新
  8100. return this.contentTransform.clone()
  8101. }
  8102. if(!this.tileset.tileTransInvert){
  8103. this.tileset.tileTransInvert = new Matrix4()
  8104. }
  8105. this.contentTransform = new Matrix4$1().fromArray(this.computedTransform).premultiply(new Matrix4$1().fromArray(this.tileset.tileTransInvert))
  8106. if(this.tileContent){
  8107. rtcCenter = this.content.rtcCenter
  8108. }else{
  8109. rtcCenter = this.rtcCenterState
  8110. }
  8111. if(!rtcCenter) {
  8112. let tranM = new Matrix4$1()
  8113. tranM.makeScale(1,1,-1)//大部分是这种情况. 就是因为这个变换才加的这个函数,之前bounding没考虑这个不准。不知道为什么原生的代码不用scaleZ
  8114. this.contentTransform.premultiply(tranM)
  8115. }
  8116. //如果有rtcCenter的话一开始boundingVolume不准?会不会有显示问题?
  8117. return this.contentTransform.clone()
  8118. }
  8119. _updateTransform(parentTransform = new Matrix4()) {
  8120. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8121. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix) //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  8122. if (!didTransformChange) {
  8123. return;
  8124. }
  8125. this.tileset.modelMatrix
  8126. this.computedTransform = computedTransform;
  8127. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  8128. this._updateBoundingVolume(this.header);
  8129. }
  8130. _getLoaderSpecificOptions(loaderId) {
  8131. switch (loaderId) {
  8132. case 'i3s':
  8133. return { ...this.tileset.options.i3s,
  8134. tile: this.header,
  8135. tileset: this.tileset.tileset,
  8136. isTileHeader: false
  8137. };
  8138. case '3d-tiles':
  8139. case 'cesium-ion':
  8140. default:
  8141. return get3dTilesOptions(this.tileset.tileset);
  8142. }
  8143. }
  8144. }
  8145. class Tileset3DTraverser extends TilesetTraverser {
  8146. compareDistanceToCamera(a, b) {
  8147. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8148. }
  8149. updateTileVisibility(tile, frameState) {
  8150. super.updateTileVisibility(tile, frameState);
  8151. if (!tile.isVisibleAndInRequestVolume) {
  8152. return;
  8153. }
  8154. const hasChildren = tile.children.length > 0;
  8155. if (tile.hasTilesetContent && hasChildren) {
  8156. const firstChild = tile.children[0];
  8157. this.updateTileVisibility(firstChild, frameState);
  8158. tile._visible = firstChild._visible;
  8159. return;
  8160. }
  8161. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8162. tile._visible = false;
  8163. return;
  8164. }
  8165. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8166. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8167. if (replace && useOptimization && hasChildren) {
  8168. if (!this.anyChildrenVisible(tile, frameState)) {
  8169. tile._visible = false;
  8170. return;
  8171. }
  8172. }
  8173. }
  8174. meetsScreenSpaceErrorEarly(tile, frameState) {
  8175. const {
  8176. parent
  8177. } = tile;
  8178. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8179. return false;
  8180. }
  8181. return !this.shouldRefine(tile, frameState, true);
  8182. }
  8183. }
  8184. const STATUS = {
  8185. REQUESTED: 'REQUESTED',
  8186. COMPLETED: 'COMPLETED',
  8187. ERROR: 'ERROR'
  8188. };
  8189. class I3STileManager {
  8190. constructor() {
  8191. _defineProperty(this, "_statusMap", void 0);
  8192. this._statusMap = {};
  8193. }
  8194. add(request, key, callback, frameState) {
  8195. if (!this._statusMap[key]) {
  8196. this._statusMap[key] = {
  8197. request,
  8198. callback,
  8199. key,
  8200. frameState,
  8201. status: STATUS.REQUESTED
  8202. };
  8203. request().then(data => {
  8204. this._statusMap[key].status = STATUS.COMPLETED;
  8205. this._statusMap[key].callback(data, frameState);
  8206. }).catch(error => {
  8207. this._statusMap[key].status = STATUS.ERROR;
  8208. callback(error);
  8209. });
  8210. }
  8211. }
  8212. update(key, frameState) {
  8213. if (this._statusMap[key]) {
  8214. this._statusMap[key].frameState = frameState;
  8215. }
  8216. }
  8217. find(key) {
  8218. return this._statusMap[key];
  8219. }
  8220. }
  8221. class I3STilesetTraverser extends TilesetTraverser {
  8222. constructor(options) {
  8223. super(options);
  8224. _defineProperty(this, "_tileManager", void 0);
  8225. this._tileManager = new I3STileManager();
  8226. }
  8227. shouldRefine(tile, frameState) {
  8228. tile._lodJudge = getLodStatus(tile, frameState);
  8229. return tile._lodJudge === 'DIG';
  8230. }
  8231. updateChildTiles(tile, frameState) {
  8232. const children = tile.header.children || [];
  8233. const childTiles = tile.children;
  8234. const tileset = tile.tileset;
  8235. for (const child of children) {
  8236. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8237. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8238. if (!childTile) {
  8239. let request = () => this._loadTile(child.id, tileset);
  8240. const cachedRequest = this._tileManager.find(extendedId);
  8241. if (!cachedRequest) {
  8242. if (tileset.tileset.nodePages) {
  8243. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8244. }
  8245. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8246. } else {
  8247. this._tileManager.update(extendedId, frameState);
  8248. }
  8249. } else if (childTile) {
  8250. this.updateTile(childTile, frameState);
  8251. }
  8252. }
  8253. return false;
  8254. }
  8255. async _loadTile(nodeId, tileset) {
  8256. const {
  8257. loader
  8258. } = tileset;
  8259. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8260. const options = { ...tileset.loadOptions,
  8261. i3s: { ...tileset.loadOptions.i3s,
  8262. isTileHeader: true,
  8263. loadContent: false
  8264. }
  8265. };
  8266. return await load(nodeUrl, loader, options);
  8267. }
  8268. _onTileLoad(header, tile, extendedId) {
  8269. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8270. tile.children.push(childTile);
  8271. const frameState = this._tileManager.find(childTile.id).frameState;
  8272. this.updateTile(childTile, frameState);
  8273. if (this._frameNumber === frameState.frameNumber) {
  8274. this.executeTraversal(childTile, frameState);
  8275. }
  8276. }
  8277. }
  8278. const DEFAULT_PROPS = {
  8279. description: '',
  8280. ellipsoid: Ellipsoid.WGS84,
  8281. modelMatrix: new Matrix4(),
  8282. throttleRequests: true,
  8283. maxRequests: 64,
  8284. maximumMemoryUsage: 32,
  8285. onTileLoad: () => {},
  8286. onTileUnload: () => {},
  8287. onTileError: () => {},
  8288. onTraversalComplete: selectedTiles => selectedTiles,
  8289. contentLoader: undefined,
  8290. viewDistanceScale: 1.0,
  8291. maximumScreenSpaceError: 8,
  8292. loadTiles: true,
  8293. updateTransforms: true,
  8294. viewportTraversersMap: null,
  8295. loadOptions: {
  8296. fetch: {}
  8297. },
  8298. attributions: [],
  8299. basePath: '',
  8300. i3s: {}
  8301. };
  8302. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8303. const TILES_IN_MEMORY = 'Tiles In Memory';
  8304. const TILES_IN_VIEW = 'Tiles In View';
  8305. const TILES_RENDERABLE = 'Tiles To Render';
  8306. const TILES_LOADED = 'Tiles Loaded';
  8307. const TILES_LOADING = 'Tiles Loading';
  8308. const TILES_UNLOADED = 'Tiles Unloaded';
  8309. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8310. const POINTS_COUNT = 'Points';
  8311. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8312. let tilesetSid = 0//add
  8313. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8314. constructor(json, options) {
  8315. super()
  8316. viewer.visiVertexCount = viewer.visiVertexCount || 0
  8317. _defineProperty(this, "options", void 0);
  8318. _defineProperty(this, "loadOptions", void 0);
  8319. _defineProperty(this, "type", void 0);
  8320. _defineProperty(this, "tileset", void 0);
  8321. _defineProperty(this, "loader", void 0);
  8322. _defineProperty(this, "url", void 0);
  8323. _defineProperty(this, "basePath", void 0);
  8324. _defineProperty(this, "modelMatrix", void 0);
  8325. _defineProperty(this, "ellipsoid", void 0);
  8326. _defineProperty(this, "lodMetricType", void 0);
  8327. _defineProperty(this, "lodMetricValue", void 0);
  8328. _defineProperty(this, "refine", void 0);
  8329. _defineProperty(this, "root", void 0);
  8330. _defineProperty(this, "roots", void 0);
  8331. _defineProperty(this, "asset", void 0);
  8332. _defineProperty(this, "description", void 0);
  8333. _defineProperty(this, "properties", void 0);
  8334. _defineProperty(this, "extras", void 0);
  8335. _defineProperty(this, "attributions", void 0);
  8336. _defineProperty(this, "credits", void 0);
  8337. _defineProperty(this, "stats", void 0);
  8338. _defineProperty(this, "traverseCounter", void 0);
  8339. _defineProperty(this, "geometricError", void 0);
  8340. _defineProperty(this, "selectedTiles", void 0);
  8341. _defineProperty(this, "cartographicCenter", void 0);
  8342. _defineProperty(this, "cartesianCenter", void 0);
  8343. _defineProperty(this, "zoom", void 0);
  8344. _defineProperty(this, "boundingVolume", void 0);
  8345. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8346. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8347. _defineProperty(this, "_traverser", void 0);
  8348. _defineProperty(this, "_cache", void 0);
  8349. _defineProperty(this, "_requestScheduler", void 0);
  8350. _defineProperty(this, "_frameNumber", void 0);
  8351. _defineProperty(this, "_queryParamsString", void 0);
  8352. _defineProperty(this, "_queryParams", void 0);
  8353. _defineProperty(this, "_extensionsUsed", void 0);
  8354. _defineProperty(this, "_tiles", void 0);
  8355. _defineProperty(this, "_pendingCount", void 0);
  8356. _defineProperty(this, "lastUpdatedVieports", void 0);
  8357. _defineProperty(this, "_requestedTiles", void 0);
  8358. _defineProperty(this, "_emptyTiles", void 0);
  8359. _defineProperty(this, "frameStateData", void 0);
  8360. _defineProperty(this, "maximumMemoryUsage", void 0);
  8361. _defineProperty(this, "visible", true);//add
  8362. assert$7(json);
  8363. this.options = { ...DEFAULT_PROPS,
  8364. ...options
  8365. };
  8366. this.tileset = json;
  8367. this.loader = json.loader;
  8368. this.type = json.type;
  8369. this.url = json.url;
  8370. this.basePath = json.basePath || dirname(this.url);
  8371. this.modelMatrix = this.options.modelMatrix;
  8372. this.ellipsoid = this.options.ellipsoid;
  8373. this.lodMetricType = json.lodMetricType;
  8374. this.lodMetricValue = json.lodMetricValue;
  8375. this.refine = json.root.refine;
  8376. this.loadOptions = this.options.loadOptions || {};
  8377. this.root = null;
  8378. this.roots = {};
  8379. this.cartographicCenter = null;
  8380. this.cartesianCenter = null;
  8381. this.zoom = 1;
  8382. this.boundingVolume = null;
  8383. this.traverseCounter = 0;
  8384. this.geometricError = 0;
  8385. this._traverser = this._initializeTraverser();
  8386. this._cache = new TilesetCache();
  8387. this._requestScheduler = new RequestScheduler({
  8388. throttleRequests: this.options.throttleRequests,
  8389. maxRequests: this.options.maxRequests
  8390. });
  8391. this._frameNumber = 0;
  8392. this._pendingCount = 0;
  8393. this._tiles = {};
  8394. this.selectedTiles = [];
  8395. this._emptyTiles = [];
  8396. this._requestedTiles = [];
  8397. this.frameStateData = {};
  8398. this.lastUpdatedVieports = null;
  8399. this._queryParams = {};
  8400. this._queryParamsString = '';
  8401. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8402. this.gpuMemoryUsageInBytes = 0;
  8403. this.stats = new Stats({
  8404. id: this.url
  8405. });
  8406. this._initializeStats();
  8407. this._extensionsUsed = undefined;
  8408. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8409. this.extras = null;
  8410. this.asset = {};
  8411. this.credits = {};
  8412. this.description = this.options.description || '';
  8413. this._initializeTileSet(json);
  8414. }
  8415. destroy() {
  8416. this._destroy();
  8417. }
  8418. isLoaded() {
  8419. return this._pendingCount === 0 && this._frameNumber !== 0;
  8420. }
  8421. get tiles() {
  8422. return Object.values(this._tiles);
  8423. }
  8424. get frameNumber() {
  8425. return this._frameNumber;
  8426. }
  8427. get queryParams() {
  8428. if (!this._queryParamsString) {
  8429. this._queryParamsString = getQueryParamString(this._queryParams);
  8430. }
  8431. return this._queryParamsString;
  8432. }
  8433. setProps(props) {
  8434. this.options = { ...this.options,
  8435. ...props
  8436. };
  8437. }
  8438. setOptions(options) {
  8439. this.options = { ...this.options,
  8440. ...options
  8441. };
  8442. }
  8443. getTileUrl(tilePath) {
  8444. const isDataUrl = tilePath.startsWith('data:');
  8445. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8446. if (isDataUrl) {
  8447. return tilePath;
  8448. }
  8449. return "".concat(tilePath).concat(this.queryParams);
  8450. }
  8451. hasExtension(extensionName) {
  8452. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8453. }
  8454. update(viewports) {
  8455. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8456. return;
  8457. }
  8458. if (this.traverseCounter > 0) {
  8459. return;
  8460. }
  8461. if (!viewports && this.lastUpdatedVieports) {
  8462. viewports = this.lastUpdatedVieports;
  8463. } else {
  8464. this.lastUpdatedVieports = viewports;
  8465. }
  8466. if (!(viewports instanceof Array)) {
  8467. viewports = [viewports];
  8468. }
  8469. this._cache.reset();
  8470. this._frameNumber++;
  8471. this.traverseCounter = viewports.length;
  8472. const viewportsToTraverse = [];
  8473. for (const viewport of viewports) {
  8474. const id = viewport.id;
  8475. if (this._needTraverse(id)) {
  8476. viewportsToTraverse.push(id);
  8477. } else {
  8478. this.traverseCounter--;
  8479. }
  8480. }
  8481. for (const viewport of viewports) {
  8482. const id = viewport.id;
  8483. if (!this.roots[id]) {
  8484. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8485. }
  8486. if (!viewportsToTraverse.includes(id)) {
  8487. continue;
  8488. }
  8489. const frameState = getFrameState(viewport, this._frameNumber);
  8490. this._traverser.traverse(this.roots[id], frameState, this.options);
  8491. }
  8492. }
  8493. _needTraverse(viewportId) {
  8494. let traverserId = viewportId;
  8495. if (this.options.viewportTraversersMap) {
  8496. traverserId = this.options.viewportTraversersMap[viewportId];
  8497. }
  8498. if (traverserId !== viewportId) {
  8499. return false;
  8500. }
  8501. return true;
  8502. }
  8503. _onTraversalEnd(frameState) {
  8504. const id = frameState.viewport.id;
  8505. if (!this.frameStateData[id]) {
  8506. this.frameStateData[id] = {
  8507. selectedTiles: [],
  8508. _requestedTiles: [],
  8509. _emptyTiles: []
  8510. };
  8511. }
  8512. const currentFrameStateData = this.frameStateData[id];
  8513. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8514. currentFrameStateData.selectedTiles = selectedTiles;
  8515. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8516. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8517. this.traverseCounter--;
  8518. if (this.traverseCounter > 0) {
  8519. return;
  8520. }
  8521. this._updateTiles();
  8522. }
  8523. _updateTiles() {
  8524. this.selectedTiles = [];
  8525. this._requestedTiles = [];
  8526. this._emptyTiles = [];
  8527. for (const frameStateKey in this.frameStateData) {
  8528. const frameStateDataValue = this.frameStateData[frameStateKey];
  8529. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8530. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8531. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8532. }
  8533. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8534. for (const tile of this.selectedTiles) {
  8535. this._tiles[tile.id] = tile;
  8536. }
  8537. this._loadTiles();
  8538. this._unloadTiles();
  8539. this._updateStats();
  8540. }
  8541. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8542. if (oldSelectedTiles.length !== selectedTiles.length) {
  8543. return true;
  8544. }
  8545. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8546. const set2 = new Set(selectedTiles.map(t => t.id));
  8547. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8548. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8549. return changed;
  8550. }
  8551. _loadTiles() {
  8552. for (const tile of this._requestedTiles) {
  8553. if (tile.contentUnloaded) {
  8554. this._loadTile(tile);
  8555. }
  8556. }
  8557. }
  8558. _unloadTiles() {
  8559. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8560. }
  8561. _updateStats() {
  8562. let tilesRenderable = 0;
  8563. let pointsRenderable = 0;
  8564. for (const tile of this.selectedTiles) {
  8565. if (tile.contentAvailable && tile.content) {
  8566. tilesRenderable++;
  8567. if (tile.content.pointCount) {
  8568. pointsRenderable += tile.content.pointCount;
  8569. }
  8570. }
  8571. }
  8572. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8573. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8574. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8575. }
  8576. _initializeTileSet(tilesetJson) {
  8577. this.root = this._initializeTileHeaders(tilesetJson, null);
  8578. if (this.type === TILESET_TYPE.TILES3D) {
  8579. this._initializeCesiumTileset(tilesetJson);
  8580. }
  8581. if (this.type === TILESET_TYPE.I3S) {
  8582. this._initializeI3STileset();
  8583. }
  8584. this._calculateViewProps();
  8585. }
  8586. _calculateViewProps() {
  8587. const root = this.root;
  8588. assert$7(root);
  8589. const {
  8590. center
  8591. } = root.boundingVolume;
  8592. if (!center) {
  8593. console.warn('center was not pre-calculated for the root tile');
  8594. this.cartographicCenter = new Vector3();
  8595. this.zoom = 1;
  8596. return;
  8597. }
  8598. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8599. this.cartesianCenter = center;
  8600. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8601. }
  8602. _initializeStats() {
  8603. this.stats.get(TILES_TOTAL);
  8604. this.stats.get(TILES_LOADING);
  8605. this.stats.get(TILES_IN_MEMORY);
  8606. this.stats.get(TILES_IN_VIEW);
  8607. this.stats.get(TILES_RENDERABLE);
  8608. this.stats.get(TILES_LOADED);
  8609. this.stats.get(TILES_UNLOADED);
  8610. this.stats.get(TILES_LOAD_FAILED);
  8611. this.stats.get(POINTS_COUNT, 'memory');
  8612. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8613. }
  8614. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8615. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8616. if (parentTileHeader) {
  8617. parentTileHeader.children.push(rootTile);
  8618. rootTile.depth = parentTileHeader.depth + 1;
  8619. }
  8620. if (this.type === TILESET_TYPE.TILES3D) {
  8621. const stack = [];
  8622. stack.push(rootTile);
  8623. while (stack.length > 0) {
  8624. const tile = stack.pop();
  8625. this.stats.get(TILES_TOTAL).incrementCount();
  8626. const children = tile.header.children || [];
  8627. // !zeg改
  8628. if(tile.depth < /* this.options. */maxDepth){
  8629. for (const childHeader of children) {
  8630. const childTile = new TileHeader(this, childHeader, tile);
  8631. tile.children.push(childTile);
  8632. childTile.depth = tile.depth + 1;
  8633. stack.push(childTile);
  8634. }
  8635. }
  8636. window.maxTileDepth = Math.max(window.maxTileDepth||0, tile.depth)
  8637. }
  8638. }
  8639. return rootTile;
  8640. }
  8641. _initializeTraverser() {
  8642. let TraverserClass;
  8643. const type = this.type;
  8644. switch (type) {
  8645. case TILESET_TYPE.TILES3D:
  8646. TraverserClass = Tileset3DTraverser;
  8647. break;
  8648. case TILESET_TYPE.I3S:
  8649. TraverserClass = I3STilesetTraverser;
  8650. break;
  8651. default:
  8652. TraverserClass = TilesetTraverser;
  8653. }
  8654. return new TraverserClass({
  8655. basePath: this.basePath,
  8656. onTraversalEnd: this._onTraversalEnd.bind(this)
  8657. });
  8658. }
  8659. _destroyTileHeaders(parentTile) {
  8660. this._destroySubtree(parentTile);
  8661. }
  8662. async _loadTile(tile) {
  8663. let loaded;
  8664. try {
  8665. this._onStartTileLoading();
  8666. loaded = await tile.loadContent();
  8667. } catch (error) {
  8668. this._onTileLoadError(tile, error);
  8669. } finally {
  8670. this._onEndTileLoading(tile);//
  8671. this._onTileLoad(tile, loaded);
  8672. }
  8673. }
  8674. _onTileLoadError(tile, error) {
  8675. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8676. const message = error.message || error.toString();
  8677. const url = tile.url;
  8678. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8679. this.options.onTileError(tile, message, url);
  8680. }
  8681. _onTileLoad(tile, loaded) {
  8682. if (!loaded) {
  8683. return;
  8684. }
  8685. if (tile && tile.content) {
  8686. calculateTransformProps(tile, tile.content);
  8687. }
  8688. this._addTileToCache(tile);
  8689. this.options.onTileLoad(tile);
  8690. }
  8691. _onStartTileLoading() {
  8692. this._pendingCount++;
  8693. this.stats.get(TILES_LOADING).incrementCount();
  8694. }
  8695. _onEndTileLoading(tile) {
  8696. this._pendingCount--;
  8697. this.stats.get(TILES_LOADING).decrementCount();
  8698. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8699. }
  8700. _addTileToCache(tile) {
  8701. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8702. }
  8703. _updateCacheStats(tile) {
  8704. this.stats.get(TILES_LOADED).incrementCount();
  8705. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8706. this.gpuMemoryUsageInBytes += tile.byteLength
  8707. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8708. }
  8709. _unloadTile(tile) {
  8710. this.gpuMemoryUsageInBytes -= tile.byteLength //
  8711. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8712. this.stats.get(TILES_UNLOADED).incrementCount();
  8713. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8714. this.options.onTileUnload(tile);
  8715. tile.unloadContent();
  8716. changeModelPointCount(tile, 'sub')
  8717. }
  8718. _destroy() {
  8719. const stack = [];
  8720. if (this.root) {
  8721. stack.push(this.root);
  8722. }
  8723. while (stack.length > 0) {
  8724. const tile = stack.pop();
  8725. for (const child of tile.children) {
  8726. stack.push(child);
  8727. }
  8728. this._destroyTile(tile);
  8729. }
  8730. getGpuMemoryUsage()
  8731. this.root = null;
  8732. }
  8733. _destroySubtree(tile) {
  8734. const root = tile;
  8735. const stack = [];
  8736. stack.push(root);
  8737. while (stack.length > 0) {
  8738. tile = stack.pop();
  8739. for (const child of tile.children) {
  8740. stack.push(child);
  8741. }
  8742. if (tile !== root) {
  8743. this._destroyTile(tile);
  8744. }
  8745. }
  8746. root.children = [];
  8747. }
  8748. _destroyTile(tile) {
  8749. this._cache.unloadTile(this, tile);
  8750. this._unloadTile(tile);
  8751. tile.destroy();
  8752. }
  8753. _initializeCesiumTileset(tilesetJson) {
  8754. this.asset = tilesetJson.asset;
  8755. if (!this.asset) {
  8756. throw new Error('Tileset must have an asset property.');
  8757. }
  8758. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8759. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8760. }
  8761. if ('tilesetVersion' in this.asset) {
  8762. this._queryParams.v = this.asset.tilesetVersion;
  8763. }
  8764. this.credits = {
  8765. attributions: this.options.attributions || []
  8766. };
  8767. this.description = this.options.description || '';
  8768. this.properties = tilesetJson.properties;
  8769. this.geometricError = tilesetJson.geometricError;
  8770. this._extensionsUsed = tilesetJson.extensionsUsed;
  8771. this.extras = tilesetJson.extras;
  8772. }
  8773. _initializeI3STileset() {
  8774. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8775. this._queryParams.token = this.loadOptions.i3s.token;
  8776. }
  8777. }
  8778. }
  8779. function getQueryParamString(queryParams) {
  8780. const queryParamStrings = [];
  8781. for (const key of Object.keys(queryParams)) {
  8782. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8783. }
  8784. switch (queryParamStrings.length) {
  8785. case 0:
  8786. return '';
  8787. case 1:
  8788. return "?".concat(queryParamStrings[0]);
  8789. default:
  8790. return "?".concat(queryParamStrings.join('&'));
  8791. }
  8792. }
  8793. const VERSION$5 = "3.1.4" ;
  8794. const TILE3D_TYPE = {
  8795. COMPOSITE: 'cmpt',
  8796. POINT_CLOUD: 'pnts',
  8797. BATCHED_3D_MODEL: 'b3dm',
  8798. INSTANCED_3D_MODEL: 'i3dm',
  8799. GEOMETRY: 'geom',
  8800. VECTOR: 'vect',
  8801. GLTF: 'glTF'
  8802. };
  8803. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8804. assert$7(arrayBuffer instanceof ArrayBuffer);
  8805. const textDecoder = new TextDecoder('utf8');
  8806. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8807. const string = textDecoder.decode(typedArray);
  8808. return string;
  8809. }
  8810. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8811. const dataView = new DataView(arrayBuffer);
  8812. 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)));
  8813. }
  8814. const VERSION$4 = "3.1.4" ;
  8815. const DEFAULT_DRACO_OPTIONS = {
  8816. draco: {
  8817. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8818. libraryPath: 'libs/',
  8819. extraAttributes: {},
  8820. attributeNameEntry: undefined
  8821. }
  8822. };
  8823. const DracoLoader$1 = {
  8824. name: 'Draco',
  8825. id: 'draco',
  8826. module: 'draco',
  8827. shapes: ['mesh'],
  8828. version: VERSION$4,
  8829. worker: true,
  8830. extensions: ['drc'],
  8831. mimeTypes: ['application/octet-stream'],
  8832. binary: true,
  8833. tests: ['DRACO'],
  8834. options: DEFAULT_DRACO_OPTIONS
  8835. };
  8836. function getMeshBoundingBox(attributes) {
  8837. let minX = Infinity;
  8838. let minY = Infinity;
  8839. let minZ = Infinity;
  8840. let maxX = -Infinity;
  8841. let maxY = -Infinity;
  8842. let maxZ = -Infinity;
  8843. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8844. const len = positions && positions.length;
  8845. for (let i = 0; i < len; i += 3) {
  8846. const x = positions[i];
  8847. const y = positions[i + 1];
  8848. const z = positions[i + 2];
  8849. minX = x < minX ? x : minX;
  8850. minY = y < minY ? y : minY;
  8851. minZ = z < minZ ? z : minZ;
  8852. maxX = x > maxX ? x : maxX;
  8853. maxY = y > maxY ? y : maxY;
  8854. maxZ = z > maxZ ? z : maxZ;
  8855. }
  8856. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8857. }
  8858. function assert$3(condition, message) {
  8859. if (!condition) {
  8860. throw new Error(message || 'loader assertion failed.');
  8861. }
  8862. }
  8863. class Schema {
  8864. constructor(fields, metadata) {
  8865. _defineProperty(this, "fields", void 0);
  8866. _defineProperty(this, "metadata", void 0);
  8867. assert$3(Array.isArray(fields));
  8868. checkNames(fields);
  8869. this.fields = fields;
  8870. this.metadata = metadata || new Map();
  8871. }
  8872. compareTo(other) {
  8873. if (this.metadata !== other.metadata) {
  8874. return false;
  8875. }
  8876. if (this.fields.length !== other.fields.length) {
  8877. return false;
  8878. }
  8879. for (let i = 0; i < this.fields.length; ++i) {
  8880. if (!this.fields[i].compareTo(other.fields[i])) {
  8881. return false;
  8882. }
  8883. }
  8884. return true;
  8885. }
  8886. select(...columnNames) {
  8887. const nameMap = Object.create(null);
  8888. for (const name of columnNames) {
  8889. nameMap[name] = true;
  8890. }
  8891. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8892. return new Schema(selectedFields, this.metadata);
  8893. }
  8894. selectAt(...columnIndices) {
  8895. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8896. return new Schema(selectedFields, this.metadata);
  8897. }
  8898. assign(schemaOrFields) {
  8899. let fields;
  8900. let metadata = this.metadata;
  8901. if (schemaOrFields instanceof Schema) {
  8902. const otherSchema = schemaOrFields;
  8903. fields = otherSchema.fields;
  8904. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8905. } else {
  8906. fields = schemaOrFields;
  8907. }
  8908. const fieldMap = Object.create(null);
  8909. for (const field of this.fields) {
  8910. fieldMap[field.name] = field;
  8911. }
  8912. for (const field of fields) {
  8913. fieldMap[field.name] = field;
  8914. }
  8915. const mergedFields = Object.values(fieldMap);
  8916. return new Schema(mergedFields, metadata);
  8917. }
  8918. }
  8919. function checkNames(fields) {
  8920. const usedNames = {};
  8921. for (const field of fields) {
  8922. if (usedNames[field.name]) {
  8923. console.warn('Schema: duplicated field name', field.name, field);
  8924. }
  8925. usedNames[field.name] = true;
  8926. }
  8927. }
  8928. function mergeMaps(m1, m2) {
  8929. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8930. }
  8931. class Field {
  8932. constructor(name, type, nullable = false, metadata = new Map()) {
  8933. _defineProperty(this, "name", void 0);
  8934. _defineProperty(this, "type", void 0);
  8935. _defineProperty(this, "nullable", void 0);
  8936. _defineProperty(this, "metadata", void 0);
  8937. this.name = name;
  8938. this.type = type;
  8939. this.nullable = nullable;
  8940. this.metadata = metadata;
  8941. }
  8942. get typeId() {
  8943. return this.type && this.type.typeId;
  8944. }
  8945. clone() {
  8946. return new Field(this.name, this.type, this.nullable, this.metadata);
  8947. }
  8948. compareTo(other) {
  8949. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8950. }
  8951. toString() {
  8952. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8953. }
  8954. }
  8955. let Type;
  8956. (function (Type) {
  8957. Type[Type["NONE"] = 0] = "NONE";
  8958. Type[Type["Null"] = 1] = "Null";
  8959. Type[Type["Int"] = 2] = "Int";
  8960. Type[Type["Float"] = 3] = "Float";
  8961. Type[Type["Binary"] = 4] = "Binary";
  8962. Type[Type["Utf8"] = 5] = "Utf8";
  8963. Type[Type["Bool"] = 6] = "Bool";
  8964. Type[Type["Decimal"] = 7] = "Decimal";
  8965. Type[Type["Date"] = 8] = "Date";
  8966. Type[Type["Time"] = 9] = "Time";
  8967. Type[Type["Timestamp"] = 10] = "Timestamp";
  8968. Type[Type["Interval"] = 11] = "Interval";
  8969. Type[Type["List"] = 12] = "List";
  8970. Type[Type["Struct"] = 13] = "Struct";
  8971. Type[Type["Union"] = 14] = "Union";
  8972. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8973. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8974. Type[Type["Map"] = 17] = "Map";
  8975. Type[Type["Dictionary"] = -1] = "Dictionary";
  8976. Type[Type["Int8"] = -2] = "Int8";
  8977. Type[Type["Int16"] = -3] = "Int16";
  8978. Type[Type["Int32"] = -4] = "Int32";
  8979. Type[Type["Int64"] = -5] = "Int64";
  8980. Type[Type["Uint8"] = -6] = "Uint8";
  8981. Type[Type["Uint16"] = -7] = "Uint16";
  8982. Type[Type["Uint32"] = -8] = "Uint32";
  8983. Type[Type["Uint64"] = -9] = "Uint64";
  8984. Type[Type["Float16"] = -10] = "Float16";
  8985. Type[Type["Float32"] = -11] = "Float32";
  8986. Type[Type["Float64"] = -12] = "Float64";
  8987. Type[Type["DateDay"] = -13] = "DateDay";
  8988. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8989. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8990. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8991. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8992. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8993. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8994. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8995. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8996. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8997. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8998. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8999. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  9000. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  9001. })(Type || (Type = {}));
  9002. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  9003. class DataType {
  9004. static isNull(x) {
  9005. return x && x.typeId === Type.Null;
  9006. }
  9007. static isInt(x) {
  9008. return x && x.typeId === Type.Int;
  9009. }
  9010. static isFloat(x) {
  9011. return x && x.typeId === Type.Float;
  9012. }
  9013. static isBinary(x) {
  9014. return x && x.typeId === Type.Binary;
  9015. }
  9016. static isUtf8(x) {
  9017. return x && x.typeId === Type.Utf8;
  9018. }
  9019. static isBool(x) {
  9020. return x && x.typeId === Type.Bool;
  9021. }
  9022. static isDecimal(x) {
  9023. return x && x.typeId === Type.Decimal;
  9024. }
  9025. static isDate(x) {
  9026. return x && x.typeId === Type.Date;
  9027. }
  9028. static isTime(x) {
  9029. return x && x.typeId === Type.Time;
  9030. }
  9031. static isTimestamp(x) {
  9032. return x && x.typeId === Type.Timestamp;
  9033. }
  9034. static isInterval(x) {
  9035. return x && x.typeId === Type.Interval;
  9036. }
  9037. static isList(x) {
  9038. return x && x.typeId === Type.List;
  9039. }
  9040. static isStruct(x) {
  9041. return x && x.typeId === Type.Struct;
  9042. }
  9043. static isUnion(x) {
  9044. return x && x.typeId === Type.Union;
  9045. }
  9046. static isFixedSizeBinary(x) {
  9047. return x && x.typeId === Type.FixedSizeBinary;
  9048. }
  9049. static isFixedSizeList(x) {
  9050. return x && x.typeId === Type.FixedSizeList;
  9051. }
  9052. static isMap(x) {
  9053. return x && x.typeId === Type.Map;
  9054. }
  9055. static isDictionary(x) {
  9056. return x && x.typeId === Type.Dictionary;
  9057. }
  9058. get typeId() {
  9059. return Type.NONE;
  9060. }
  9061. compareTo(other) {
  9062. return this === other;
  9063. }
  9064. }
  9065. _Symbol$toStringTag = Symbol.toStringTag;
  9066. class Int extends DataType {
  9067. constructor(isSigned, bitWidth) {
  9068. super();
  9069. _defineProperty(this, "isSigned", void 0);
  9070. _defineProperty(this, "bitWidth", void 0);
  9071. this.isSigned = isSigned;
  9072. this.bitWidth = bitWidth;
  9073. }
  9074. get typeId() {
  9075. return Type.Int;
  9076. }
  9077. get [_Symbol$toStringTag]() {
  9078. return 'Int';
  9079. }
  9080. toString() {
  9081. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  9082. }
  9083. }
  9084. class Int8 extends Int {
  9085. constructor() {
  9086. super(true, 8);
  9087. }
  9088. }
  9089. class Int16 extends Int {
  9090. constructor() {
  9091. super(true, 16);
  9092. }
  9093. }
  9094. class Int32 extends Int {
  9095. constructor() {
  9096. super(true, 32);
  9097. }
  9098. }
  9099. class Uint8 extends Int {
  9100. constructor() {
  9101. super(false, 8);
  9102. }
  9103. }
  9104. class Uint16 extends Int {
  9105. constructor() {
  9106. super(false, 16);
  9107. }
  9108. }
  9109. class Uint32 extends Int {
  9110. constructor() {
  9111. super(false, 32);
  9112. }
  9113. }
  9114. const Precision = {
  9115. HALF: 16,
  9116. SINGLE: 32,
  9117. DOUBLE: 64
  9118. };
  9119. _Symbol$toStringTag2 = Symbol.toStringTag;
  9120. class Float extends DataType {
  9121. constructor(precision) {
  9122. super();
  9123. _defineProperty(this, "precision", void 0);
  9124. this.precision = precision;
  9125. }
  9126. get typeId() {
  9127. return Type.Float;
  9128. }
  9129. get [_Symbol$toStringTag2]() {
  9130. return 'Float';
  9131. }
  9132. toString() {
  9133. return "Float".concat(this.precision);
  9134. }
  9135. }
  9136. class Float32 extends Float {
  9137. constructor() {
  9138. super(Precision.SINGLE);
  9139. }
  9140. }
  9141. class Float64 extends Float {
  9142. constructor() {
  9143. super(Precision.DOUBLE);
  9144. }
  9145. }
  9146. _Symbol$toStringTag7 = Symbol.toStringTag;
  9147. class FixedSizeList extends DataType {
  9148. constructor(listSize, child) {
  9149. super();
  9150. _defineProperty(this, "listSize", void 0);
  9151. _defineProperty(this, "children", void 0);
  9152. this.listSize = listSize;
  9153. this.children = [child];
  9154. }
  9155. get typeId() {
  9156. return Type.FixedSizeList;
  9157. }
  9158. get valueType() {
  9159. return this.children[0].type;
  9160. }
  9161. get valueField() {
  9162. return this.children[0];
  9163. }
  9164. get [_Symbol$toStringTag7]() {
  9165. return 'FixedSizeList';
  9166. }
  9167. toString() {
  9168. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9169. }
  9170. }
  9171. function getArrowTypeFromTypedArray(array) {
  9172. switch (array.constructor) {
  9173. case Int8Array:
  9174. return new Int8();
  9175. case Uint8Array:
  9176. return new Uint8();
  9177. case Int16Array:
  9178. return new Int16();
  9179. case Uint16Array:
  9180. return new Uint16();
  9181. case Int32Array:
  9182. return new Int32();
  9183. case Uint32Array:
  9184. return new Uint32();
  9185. case Float32Array:
  9186. return new Float32();
  9187. case Float64Array:
  9188. return new Float64();
  9189. default:
  9190. throw new Error('array type not supported');
  9191. }
  9192. }
  9193. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9194. const type = getArrowTypeFromTypedArray(attribute.value);
  9195. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9196. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9197. return field;
  9198. }
  9199. function makeMeshAttributeMetadata(attribute) {
  9200. const result = new Map();
  9201. if ('byteOffset' in attribute) {
  9202. result.set('byteOffset', attribute.byteOffset.toString(10));
  9203. }
  9204. if ('byteStride' in attribute) {
  9205. result.set('byteStride', attribute.byteStride.toString(10));
  9206. }
  9207. if ('normalized' in attribute) {
  9208. result.set('normalized', attribute.normalized.toString());
  9209. }
  9210. return result;
  9211. }
  9212. function getDracoSchema(attributes, loaderData, indices) {
  9213. const metadataMap = makeMetadata(loaderData.metadata);
  9214. const fields = [];
  9215. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9216. for (const attributeName in attributes) {
  9217. const attribute = attributes[attributeName];
  9218. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9219. fields.push(field);
  9220. }
  9221. if (indices) {
  9222. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9223. fields.push(indicesField);
  9224. }
  9225. return new Schema(fields, metadataMap);
  9226. }
  9227. function transformAttributesLoaderData(loaderData) {
  9228. const result = {};
  9229. for (const key in loaderData) {
  9230. const dracoAttribute = loaderData[key];
  9231. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9232. }
  9233. return result;
  9234. }
  9235. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9236. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9237. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9238. return field;
  9239. }
  9240. function makeMetadata(metadata) {
  9241. const metadataMap = new Map();
  9242. for (const key in metadata) {
  9243. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9244. }
  9245. return metadataMap;
  9246. }
  9247. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9248. POSITION: 'POSITION',
  9249. NORMAL: 'NORMAL',
  9250. COLOR: 'COLOR_0',
  9251. TEX_COORD: 'TEXCOORD_0'
  9252. };
  9253. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9254. 1: Int8Array,
  9255. 2: Uint8Array,
  9256. 3: Int16Array,
  9257. 4: Uint16Array,
  9258. 5: Int32Array,
  9259. 6: Uint32Array,
  9260. 9: Float32Array
  9261. };
  9262. const INDEX_ITEM_SIZE = 4;
  9263. class DracoParser {
  9264. constructor(draco) {
  9265. _defineProperty(this, "draco", void 0);
  9266. _defineProperty(this, "decoder", void 0);
  9267. _defineProperty(this, "metadataQuerier", void 0);
  9268. this.draco = draco;
  9269. this.decoder = new this.draco.Decoder();
  9270. this.metadataQuerier = new this.draco.MetadataQuerier();
  9271. }
  9272. destroy() {
  9273. this.draco.destroy(this.decoder);
  9274. this.draco.destroy(this.metadataQuerier);
  9275. }
  9276. parseSync(arrayBuffer, options = {}) {
  9277. const buffer = new this.draco.DecoderBuffer();
  9278. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9279. this._disableAttributeTransforms(options);
  9280. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9281. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9282. try {
  9283. let dracoStatus;
  9284. switch (geometry_type) {
  9285. case this.draco.TRIANGULAR_MESH:
  9286. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9287. break;
  9288. case this.draco.POINT_CLOUD:
  9289. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9290. break;
  9291. default:
  9292. throw new Error('DRACO: Unknown geometry type.');
  9293. }
  9294. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9295. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9296. throw new Error(message);
  9297. }
  9298. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9299. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9300. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9301. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9302. const data = {
  9303. loader: 'draco',
  9304. loaderData,
  9305. header: {
  9306. vertexCount: dracoGeometry.num_points(),
  9307. boundingBox
  9308. },
  9309. ...geometry,
  9310. schema
  9311. };
  9312. return data;
  9313. } finally {
  9314. this.draco.destroy(buffer);
  9315. if (dracoGeometry) {
  9316. this.draco.destroy(dracoGeometry);
  9317. }
  9318. }
  9319. }
  9320. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9321. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9322. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9323. return {
  9324. geometry_type,
  9325. num_attributes: dracoGeometry.num_attributes(),
  9326. num_points: dracoGeometry.num_points(),
  9327. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9328. metadata,
  9329. attributes
  9330. };
  9331. }
  9332. _getDracoAttributes(dracoGeometry, options) {
  9333. const dracoAttributes = {};
  9334. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9335. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9336. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9337. dracoAttributes[dracoAttribute.unique_id()] = {
  9338. unique_id: dracoAttribute.unique_id(),
  9339. attribute_type: dracoAttribute.attribute_type(),
  9340. data_type: dracoAttribute.data_type(),
  9341. num_components: dracoAttribute.num_components(),
  9342. byte_offset: dracoAttribute.byte_offset(),
  9343. byte_stride: dracoAttribute.byte_stride(),
  9344. normalized: dracoAttribute.normalized(),
  9345. attribute_index: attributeId,
  9346. metadata
  9347. };
  9348. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9349. if (quantization) {
  9350. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9351. }
  9352. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9353. if (octahedron) {
  9354. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9355. }
  9356. }
  9357. return dracoAttributes;
  9358. }
  9359. _getMeshData(dracoGeometry, loaderData, options) {
  9360. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9361. const positionAttribute = attributes.POSITION;
  9362. if (!positionAttribute) {
  9363. throw new Error('DRACO: No position attribute found.');
  9364. }
  9365. if (dracoGeometry instanceof this.draco.Mesh) {
  9366. switch (options.topology) {
  9367. case 'triangle-strip':
  9368. return {
  9369. topology: 'triangle-strip',
  9370. mode: 4,
  9371. attributes,
  9372. indices: {
  9373. value: this._getTriangleStripIndices(dracoGeometry),
  9374. size: 1
  9375. }
  9376. };
  9377. case 'triangle-list':
  9378. default:
  9379. return {
  9380. topology: 'triangle-list',
  9381. mode: 5,
  9382. attributes,
  9383. indices: {
  9384. value: this._getTriangleListIndices(dracoGeometry),
  9385. size: 1
  9386. }
  9387. };
  9388. }
  9389. }
  9390. return {
  9391. topology: 'point-list',
  9392. mode: 0,
  9393. attributes
  9394. };
  9395. }
  9396. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9397. const attributes = {};
  9398. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9399. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9400. loaderAttribute.name = attributeName;
  9401. const {
  9402. value,
  9403. size
  9404. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9405. attributes[attributeName] = {
  9406. value,
  9407. size,
  9408. byteOffset: loaderAttribute.byte_offset,
  9409. byteStride: loaderAttribute.byte_stride,
  9410. normalized: loaderAttribute.normalized
  9411. };
  9412. }
  9413. return attributes;
  9414. }
  9415. _getTriangleListIndices(dracoGeometry) {
  9416. const numFaces = dracoGeometry.num_faces();
  9417. const numIndices = numFaces * 3;
  9418. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9419. const ptr = this.draco._malloc(byteLength);
  9420. try {
  9421. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9422. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9423. } finally {
  9424. this.draco._free(ptr);
  9425. }
  9426. }
  9427. _getTriangleStripIndices(dracoGeometry) {
  9428. const dracoArray = new this.draco.DracoInt32Array();
  9429. try {
  9430. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9431. return getUint32Array(dracoArray);
  9432. } finally {
  9433. this.draco.destroy(dracoArray);
  9434. }
  9435. }
  9436. _getAttributeValues(dracoGeometry, attribute) {
  9437. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9438. const numComponents = attribute.num_components;
  9439. const numPoints = dracoGeometry.num_points();
  9440. const numValues = numPoints * numComponents;
  9441. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9442. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9443. let value;
  9444. const ptr = this.draco._malloc(byteLength);
  9445. try {
  9446. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9447. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9448. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9449. } finally {
  9450. this.draco._free(ptr);
  9451. }
  9452. return {
  9453. value,
  9454. size: numComponents
  9455. };
  9456. }
  9457. _deduceAttributeName(attribute, options) {
  9458. const uniqueId = attribute.unique_id;
  9459. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9460. if (attributeUniqueId === uniqueId) {
  9461. return attributeName;
  9462. }
  9463. }
  9464. const thisAttributeType = attribute.attribute_type;
  9465. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9466. const attributeType = this.draco[dracoAttributeConstant];
  9467. if (attributeType === thisAttributeType) {
  9468. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9469. }
  9470. }
  9471. const entryName = options.attributeNameEntry || 'name';
  9472. if (attribute.metadata[entryName]) {
  9473. return attribute.metadata[entryName].string;
  9474. }
  9475. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9476. }
  9477. _getTopLevelMetadata(dracoGeometry) {
  9478. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9479. return this._getDracoMetadata(dracoMetadata);
  9480. }
  9481. _getAttributeMetadata(dracoGeometry, attributeId) {
  9482. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9483. return this._getDracoMetadata(dracoMetadata);
  9484. }
  9485. _getDracoMetadata(dracoMetadata) {
  9486. if (!dracoMetadata || !dracoMetadata.ptr) {
  9487. return {};
  9488. }
  9489. const result = {};
  9490. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9491. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9492. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9493. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9494. }
  9495. return result;
  9496. }
  9497. _getDracoMetadataField(dracoMetadata, entryName) {
  9498. const dracoArray = new this.draco.DracoInt32Array();
  9499. try {
  9500. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9501. const intArray = getInt32Array(dracoArray);
  9502. return {
  9503. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9504. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9505. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9506. intArray
  9507. };
  9508. } finally {
  9509. this.draco.destroy(dracoArray);
  9510. }
  9511. }
  9512. _disableAttributeTransforms(options) {
  9513. const {
  9514. quantizedAttributes = [],
  9515. octahedronAttributes = []
  9516. } = options;
  9517. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9518. for (const dracoAttributeName of skipAttributes) {
  9519. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9520. }
  9521. }
  9522. _getQuantizationTransform(dracoAttribute, options) {
  9523. const {
  9524. quantizedAttributes = []
  9525. } = options;
  9526. const attribute_type = dracoAttribute.attribute_type();
  9527. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9528. if (skip) {
  9529. const transform = new this.draco.AttributeQuantizationTransform();
  9530. try {
  9531. if (transform.InitFromAttribute(dracoAttribute)) {
  9532. return {
  9533. quantization_bits: transform.quantization_bits(),
  9534. range: transform.range(),
  9535. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9536. };
  9537. }
  9538. } finally {
  9539. this.draco.destroy(transform);
  9540. }
  9541. }
  9542. return null;
  9543. }
  9544. _getOctahedronTransform(dracoAttribute, options) {
  9545. const {
  9546. octahedronAttributes = []
  9547. } = options;
  9548. const attribute_type = dracoAttribute.attribute_type();
  9549. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9550. if (octahedron) {
  9551. const transform = new this.draco.AttributeQuantizationTransform();
  9552. try {
  9553. if (transform.InitFromAttribute(dracoAttribute)) {
  9554. return {
  9555. quantization_bits: transform.quantization_bits()
  9556. };
  9557. }
  9558. } finally {
  9559. this.draco.destroy(transform);
  9560. }
  9561. }
  9562. return null;
  9563. }
  9564. }
  9565. function getDracoDataType(draco, attributeType) {
  9566. switch (attributeType) {
  9567. case Float32Array:
  9568. return draco.DT_FLOAT32;
  9569. case Int8Array:
  9570. return draco.DT_INT8;
  9571. case Int16Array:
  9572. return draco.DT_INT16;
  9573. case Int32Array:
  9574. return draco.DT_INT32;
  9575. case Uint8Array:
  9576. return draco.DT_UINT8;
  9577. case Uint16Array:
  9578. return draco.DT_UINT16;
  9579. case Uint32Array:
  9580. return draco.DT_UINT32;
  9581. default:
  9582. return draco.DT_INVALID;
  9583. }
  9584. }
  9585. function getInt32Array(dracoArray) {
  9586. const numValues = dracoArray.size();
  9587. const intArray = new Int32Array(numValues);
  9588. for (let i = 0; i < numValues; i++) {
  9589. intArray[i] = dracoArray.GetValue(i);
  9590. }
  9591. return intArray;
  9592. }
  9593. function getUint32Array(dracoArray) {
  9594. const numValues = dracoArray.size();
  9595. const intArray = new Int32Array(numValues);
  9596. for (let i = 0; i < numValues; i++) {
  9597. intArray[i] = dracoArray.GetValue(i);
  9598. }
  9599. return intArray;
  9600. }
  9601. const DRACO_VERSION = '1.4.1';
  9602. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9603. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9604. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9605. let loadDecoderPromise;
  9606. async function loadDracoDecoderModule(options) {
  9607. const modules = options.modules || {};
  9608. if (modules.draco3d) {
  9609. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9610. return {
  9611. draco
  9612. };
  9613. });
  9614. } else {
  9615. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9616. }
  9617. return await loadDecoderPromise;
  9618. }
  9619. async function loadDracoDecoder(options) {
  9620. let DracoDecoderModule;
  9621. let wasmBinary;
  9622. switch (options.draco && options.draco.decoderType) {
  9623. case 'js':
  9624. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9625. break;
  9626. case 'wasm':
  9627. default:
  9628. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9629. }
  9630. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9631. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9632. }
  9633. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9634. const options = {};
  9635. if (wasmBinary) {
  9636. options.wasmBinary = wasmBinary;
  9637. }
  9638. return new Promise(resolve => {
  9639. DracoDecoderModule({ ...options,
  9640. onModuleLoaded: draco => resolve({
  9641. draco
  9642. })
  9643. });
  9644. });
  9645. }
  9646. const DracoLoader = { ...DracoLoader$1,
  9647. parse: parse$2
  9648. };
  9649. async function parse$2(arrayBuffer, options) {
  9650. const {
  9651. draco
  9652. } = await loadDracoDecoderModule(options);
  9653. const dracoParser = new DracoParser(draco);
  9654. try {
  9655. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9656. } finally {
  9657. dracoParser.destroy();
  9658. }
  9659. }
  9660. const GL_PRIMITIVE_MODE = {
  9661. POINTS: 0x0000,
  9662. LINES: 0x0001,
  9663. LINE_LOOP: 0x0002,
  9664. LINE_STRIP: 0x0003,
  9665. TRIANGLES: 0x0004,
  9666. TRIANGLE_STRIP: 0x0005,
  9667. TRIANGLE_FAN: 0x0006
  9668. };
  9669. const GL_TYPE = {
  9670. BYTE: 5120,
  9671. UNSIGNED_BYTE: 5121,
  9672. SHORT: 5122,
  9673. UNSIGNED_SHORT: 5123,
  9674. INT: 5124,
  9675. UNSIGNED_INT: 5125,
  9676. FLOAT: 5126,
  9677. DOUBLE: 5130
  9678. };
  9679. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9680. ...GL_TYPE
  9681. };
  9682. const GL_TYPE_TO_ARRAY_TYPE = {
  9683. [GL_TYPE.DOUBLE]: Float64Array,
  9684. [GL_TYPE.FLOAT]: Float32Array,
  9685. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9686. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9687. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9688. [GL_TYPE.BYTE]: Int8Array,
  9689. [GL_TYPE.SHORT]: Int16Array,
  9690. [GL_TYPE.INT]: Int32Array
  9691. };
  9692. const NAME_TO_GL_TYPE = {
  9693. DOUBLE: GL_TYPE.DOUBLE,
  9694. FLOAT: GL_TYPE.FLOAT,
  9695. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9696. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9697. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9698. BYTE: GL_TYPE.BYTE,
  9699. SHORT: GL_TYPE.SHORT,
  9700. INT: GL_TYPE.INT
  9701. };
  9702. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9703. class GLType {
  9704. static fromTypedArray(arrayOrType) {
  9705. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9706. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9707. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9708. if (ArrayType === arrayOrType) {
  9709. return glType;
  9710. }
  9711. }
  9712. throw new Error(ERR_TYPE_CONVERSION);
  9713. }
  9714. static fromName(name) {
  9715. const glType = NAME_TO_GL_TYPE[name];
  9716. if (!glType) {
  9717. throw new Error(ERR_TYPE_CONVERSION);
  9718. }
  9719. return glType;
  9720. }
  9721. static getArrayType(glType) {
  9722. switch (glType) {
  9723. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9724. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9725. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9726. return Uint16Array;
  9727. default:
  9728. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9729. if (!ArrayType) {
  9730. throw new Error(ERR_TYPE_CONVERSION);
  9731. }
  9732. return ArrayType;
  9733. }
  9734. }
  9735. static getByteSize(glType) {
  9736. const ArrayType = GLType.getArrayType(glType);
  9737. return ArrayType.BYTES_PER_ELEMENT;
  9738. }
  9739. static validate(glType) {
  9740. return Boolean(GLType.getArrayType(glType));
  9741. }
  9742. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9743. if (length === undefined) {
  9744. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9745. }
  9746. const ArrayType = GLType.getArrayType(glType);
  9747. return new ArrayType(buffer, byteOffset, length);
  9748. }
  9749. }
  9750. function assert$2(condition, message) {
  9751. if (!condition) {
  9752. throw new Error("math.gl assertion failed. ".concat(message));
  9753. }
  9754. }
  9755. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9756. const r5 = rgb565 >> 11 & 31;
  9757. const g6 = rgb565 >> 5 & 63;
  9758. const b5 = rgb565 & 31;
  9759. target[0] = r5 << 3;
  9760. target[1] = g6 << 2;
  9761. target[2] = b5 << 3;
  9762. return target;
  9763. }
  9764. new Vector2();
  9765. new Vector3();
  9766. new Vector2();
  9767. new Vector2();
  9768. function fromSNorm(value, rangeMaximum = 255) {
  9769. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9770. }
  9771. function signNotZero(value) {
  9772. return value < 0.0 ? -1.0 : 1.0;
  9773. }
  9774. function octDecodeInRange(x, y, rangeMax, result) {
  9775. assert$2(result);
  9776. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9777. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9778. }
  9779. result.x = fromSNorm(x, rangeMax);
  9780. result.y = fromSNorm(y, rangeMax);
  9781. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9782. if (result.z < 0.0) {
  9783. const oldVX = result.x;
  9784. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9785. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9786. }
  9787. return result.normalize();
  9788. }
  9789. function octDecode(x, y, result) {
  9790. return octDecodeInRange(x, y, 255, result);
  9791. }
  9792. class Tile3DFeatureTable {
  9793. constructor(featureTableJson, featureTableBinary) {
  9794. _defineProperty(this, "json", void 0);
  9795. _defineProperty(this, "buffer", void 0);
  9796. _defineProperty(this, "featuresLength", 0);
  9797. _defineProperty(this, "_cachedTypedArrays", {});
  9798. this.json = featureTableJson;
  9799. this.buffer = featureTableBinary;
  9800. }
  9801. getExtension(extensionName) {
  9802. return this.json.extensions && this.json.extensions[extensionName];
  9803. }
  9804. hasProperty(propertyName) {
  9805. return Boolean(this.json[propertyName]);
  9806. }
  9807. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9808. const jsonValue = this.json[propertyName];
  9809. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9810. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9811. }
  9812. return jsonValue;
  9813. }
  9814. getPropertyArray(propertyName, componentType, componentLength) {
  9815. const jsonValue = this.json[propertyName];
  9816. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9817. if ('componentType' in jsonValue) {
  9818. componentType = GLType.fromName(jsonValue.componentType);
  9819. }
  9820. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9821. }
  9822. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9823. }
  9824. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9825. const jsonValue = this.json[propertyName];
  9826. if (!jsonValue) {
  9827. return jsonValue;
  9828. }
  9829. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9830. if (componentLength === 1) {
  9831. return typedArray[featureId];
  9832. }
  9833. for (let i = 0; i < componentLength; ++i) {
  9834. result[i] = typedArray[componentLength * featureId + i];
  9835. }
  9836. return result;
  9837. }
  9838. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9839. const cachedTypedArrays = this._cachedTypedArrays;
  9840. let typedArray = cachedTypedArrays[propertyName];
  9841. if (!typedArray) {
  9842. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9843. cachedTypedArrays[propertyName] = typedArray;
  9844. }
  9845. return typedArray;
  9846. }
  9847. _getTypedArrayFromArray(propertyName, componentType, array) {
  9848. const cachedTypedArrays = this._cachedTypedArrays;
  9849. let typedArray = cachedTypedArrays[propertyName];
  9850. if (!typedArray) {
  9851. typedArray = GLType.createTypedArray(componentType, array);
  9852. cachedTypedArrays[propertyName] = typedArray;
  9853. }
  9854. return typedArray;
  9855. }
  9856. }
  9857. const COMPONENTS_PER_ATTRIBUTE = {
  9858. SCALAR: 1,
  9859. VEC2: 2,
  9860. VEC3: 3,
  9861. VEC4: 4,
  9862. MAT2: 4,
  9863. MAT3: 9,
  9864. MAT4: 16
  9865. };
  9866. const UNPACKER = {
  9867. SCALAR: (values, i) => values[i],
  9868. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9869. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9870. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9871. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9872. 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]],
  9873. 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]]
  9874. };
  9875. const PACKER = {
  9876. SCALAR: (x, values, i) => {
  9877. values[i] = x;
  9878. },
  9879. VEC2: (x, values, i) => {
  9880. values[2 * i + 0] = x[0];
  9881. values[2 * i + 1] = x[1];
  9882. },
  9883. VEC3: (x, values, i) => {
  9884. values[3 * i + 0] = x[0];
  9885. values[3 * i + 1] = x[1];
  9886. values[3 * i + 2] = x[2];
  9887. },
  9888. VEC4: (x, values, i) => {
  9889. values[4 * i + 0] = x[0];
  9890. values[4 * i + 1] = x[1];
  9891. values[4 * i + 2] = x[2];
  9892. values[4 * i + 3] = x[3];
  9893. },
  9894. MAT2: (x, values, i) => {
  9895. values[4 * i + 0] = x[0];
  9896. values[4 * i + 1] = x[1];
  9897. values[4 * i + 2] = x[2];
  9898. values[4 * i + 3] = x[3];
  9899. },
  9900. MAT3: (x, values, i) => {
  9901. values[9 * i + 0] = x[0];
  9902. values[9 * i + 1] = x[1];
  9903. values[9 * i + 2] = x[2];
  9904. values[9 * i + 3] = x[3];
  9905. values[9 * i + 4] = x[4];
  9906. values[9 * i + 5] = x[5];
  9907. values[9 * i + 6] = x[6];
  9908. values[9 * i + 7] = x[7];
  9909. values[9 * i + 8] = x[8];
  9910. values[9 * i + 9] = x[9];
  9911. },
  9912. MAT4: (x, values, i) => {
  9913. values[16 * i + 0] = x[0];
  9914. values[16 * i + 1] = x[1];
  9915. values[16 * i + 2] = x[2];
  9916. values[16 * i + 3] = x[3];
  9917. values[16 * i + 4] = x[4];
  9918. values[16 * i + 5] = x[5];
  9919. values[16 * i + 6] = x[6];
  9920. values[16 * i + 7] = x[7];
  9921. values[16 * i + 8] = x[8];
  9922. values[16 * i + 9] = x[9];
  9923. values[16 * i + 10] = x[10];
  9924. values[16 * i + 11] = x[11];
  9925. values[16 * i + 12] = x[12];
  9926. values[16 * i + 13] = x[13];
  9927. values[16 * i + 14] = x[14];
  9928. values[16 * i + 15] = x[15];
  9929. }
  9930. };
  9931. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9932. const {
  9933. componentType
  9934. } = tile3DAccessor;
  9935. assert$7(tile3DAccessor.componentType);
  9936. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9937. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9938. const unpacker = UNPACKER[tile3DAccessor.type];
  9939. const packer = PACKER[tile3DAccessor.type];
  9940. byteOffset += tile3DAccessor.byteOffset;
  9941. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9942. return {
  9943. values,
  9944. type,
  9945. size,
  9946. unpacker,
  9947. packer
  9948. };
  9949. }
  9950. const defined$1 = x => x !== undefined;
  9951. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9952. if (!jsonHeader) {
  9953. return null;
  9954. }
  9955. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9956. const legacyHierarchy = jsonHeader.HIERARCHY;
  9957. if (legacyHierarchy) {
  9958. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9959. jsonHeader.extensions = jsonHeader.extensions || {};
  9960. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9961. hierarchy = legacyHierarchy;
  9962. }
  9963. if (!hierarchy) {
  9964. return null;
  9965. }
  9966. return initializeHierarchyValues(hierarchy, binaryBody);
  9967. }
  9968. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9969. let i;
  9970. let classId;
  9971. let binaryAccessor;
  9972. const instancesLength = hierarchyJson.instancesLength;
  9973. const classes = hierarchyJson.classes;
  9974. let classIds = hierarchyJson.classIds;
  9975. let parentCounts = hierarchyJson.parentCounts;
  9976. let parentIds = hierarchyJson.parentIds;
  9977. let parentIdsLength = instancesLength;
  9978. if (defined$1(classIds.byteOffset)) {
  9979. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9980. classIds.type = AttributeType.SCALAR;
  9981. binaryAccessor = getBinaryAccessor(classIds);
  9982. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9983. }
  9984. let parentIndexes;
  9985. if (defined$1(parentCounts)) {
  9986. if (defined$1(parentCounts.byteOffset)) {
  9987. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9988. parentCounts.type = AttributeType.SCALAR;
  9989. binaryAccessor = getBinaryAccessor(parentCounts);
  9990. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9991. }
  9992. parentIndexes = new Uint16Array(instancesLength);
  9993. parentIdsLength = 0;
  9994. for (i = 0; i < instancesLength; ++i) {
  9995. parentIndexes[i] = parentIdsLength;
  9996. parentIdsLength += parentCounts[i];
  9997. }
  9998. }
  9999. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  10000. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  10001. parentIds.type = AttributeType.SCALAR;
  10002. binaryAccessor = getBinaryAccessor(parentIds);
  10003. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  10004. }
  10005. const classesLength = classes.length;
  10006. for (i = 0; i < classesLength; ++i) {
  10007. const classInstancesLength = classes[i].length;
  10008. const properties = classes[i].instances;
  10009. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  10010. classes[i].instances = combine(binaryProperties, properties);
  10011. }
  10012. const classCounts = new Array(classesLength).fill(0);
  10013. const classIndexes = new Uint16Array(instancesLength);
  10014. for (i = 0; i < instancesLength; ++i) {
  10015. classId = classIds[i];
  10016. classIndexes[i] = classCounts[classId];
  10017. ++classCounts[classId];
  10018. }
  10019. const hierarchy = {
  10020. classes,
  10021. classIds,
  10022. classIndexes,
  10023. parentCounts,
  10024. parentIndexes,
  10025. parentIds
  10026. };
  10027. validateHierarchy(hierarchy);
  10028. return hierarchy;
  10029. }
  10030. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  10031. if (!hierarchy) {
  10032. return;
  10033. }
  10034. const parentCounts = hierarchy.parentCounts;
  10035. const parentIds = hierarchy.parentIds;
  10036. if (parentIds) {
  10037. return endConditionCallback(hierarchy, instanceIndex);
  10038. }
  10039. if (parentCounts > 0) {
  10040. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  10041. }
  10042. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  10043. }
  10044. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  10045. const classIds = hierarchy.classIds;
  10046. const parentCounts = hierarchy.parentCounts;
  10047. const parentIds = hierarchy.parentIds;
  10048. const parentIndexes = hierarchy.parentIndexes;
  10049. const instancesLength = classIds.length;
  10050. const visited = scratchVisited;
  10051. visited.length = Math.max(visited.length, instancesLength);
  10052. const visitedMarker = ++marker;
  10053. const stack = scratchStack;
  10054. stack.length = 0;
  10055. stack.push(instanceIndex);
  10056. while (stack.length > 0) {
  10057. instanceIndex = stack.pop();
  10058. if (visited[instanceIndex] === visitedMarker) {
  10059. continue;
  10060. }
  10061. visited[instanceIndex] = visitedMarker;
  10062. const result = endConditionCallback(hierarchy, instanceIndex);
  10063. if (defined$1(result)) {
  10064. return result;
  10065. }
  10066. const parentCount = parentCounts[instanceIndex];
  10067. const parentIndex = parentIndexes[instanceIndex];
  10068. for (let i = 0; i < parentCount; ++i) {
  10069. const parentId = parentIds[parentIndex + i];
  10070. if (parentId !== instanceIndex) {
  10071. stack.push(parentId);
  10072. }
  10073. }
  10074. }
  10075. return null;
  10076. }
  10077. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  10078. let hasParent = true;
  10079. while (hasParent) {
  10080. const result = endConditionCallback(hierarchy, instanceIndex);
  10081. if (defined$1(result)) {
  10082. return result;
  10083. }
  10084. const parentId = hierarchy.parentIds[instanceIndex];
  10085. hasParent = parentId !== instanceIndex;
  10086. instanceIndex = parentId;
  10087. }
  10088. throw new Error('traverseHierarchySingleParent');
  10089. }
  10090. function validateHierarchy(hierarchy) {
  10091. const classIds = hierarchy.classIds;
  10092. const instancesLength = classIds.length;
  10093. for (let i = 0; i < instancesLength; ++i) {
  10094. validateInstance(hierarchy, i, stack);
  10095. }
  10096. }
  10097. function validateInstance(hierarchy, instanceIndex, stack) {
  10098. const parentCounts = hierarchy.parentCounts;
  10099. const parentIds = hierarchy.parentIds;
  10100. const parentIndexes = hierarchy.parentIndexes;
  10101. const classIds = hierarchy.classIds;
  10102. const instancesLength = classIds.length;
  10103. if (!defined$1(parentIds)) {
  10104. return;
  10105. }
  10106. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  10107. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  10108. stack.push(instanceIndex);
  10109. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10110. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10111. for (let i = 0; i < parentCount; ++i) {
  10112. const parentId = parentIds[parentIndex + i];
  10113. if (parentId !== instanceIndex) {
  10114. validateInstance(hierarchy, parentId, stack);
  10115. }
  10116. }
  10117. stack.pop(instanceIndex);
  10118. }
  10119. function defined(x) {
  10120. return x !== undefined && x !== null;
  10121. }
  10122. const clone = (x, y) => x;
  10123. const IGNORED_PROPERTY_FIELDS = {
  10124. HIERARCHY: true,
  10125. extensions: true,
  10126. extras: true
  10127. };
  10128. class Tile3DBatchTableParser {
  10129. constructor(json, binary, featureCount, options = {}) {
  10130. var _this$json;
  10131. _defineProperty(this, "json", void 0);
  10132. _defineProperty(this, "binary", void 0);
  10133. _defineProperty(this, "featureCount", void 0);
  10134. _defineProperty(this, "_extensions", void 0);
  10135. _defineProperty(this, "_properties", void 0);
  10136. _defineProperty(this, "_binaryProperties", void 0);
  10137. _defineProperty(this, "_hierarchy", void 0);
  10138. assert$7(featureCount >= 0);
  10139. this.json = json || {};
  10140. this.binary = binary;
  10141. this.featureCount = featureCount;
  10142. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10143. this._properties = {};
  10144. for (const propertyName in this.json) {
  10145. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10146. this._properties[propertyName] = this.json[propertyName];
  10147. }
  10148. }
  10149. this._binaryProperties = this._initializeBinaryProperties();
  10150. if (options['3DTILES_batch_table_hierarchy']) {
  10151. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10152. }
  10153. }
  10154. getExtension(extensionName) {
  10155. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10156. }
  10157. memorySizeInBytes() {
  10158. return 0;
  10159. }
  10160. isClass(batchId, className) {
  10161. this._checkBatchId(batchId);
  10162. assert$7(typeof className === 'string', className);
  10163. if (this._hierarchy) {
  10164. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10165. const classId = hierarchy.classIds[instanceIndex];
  10166. const instanceClass = hierarchy.classes[classId];
  10167. return instanceClass.name === className;
  10168. });
  10169. return defined(result);
  10170. }
  10171. return false;
  10172. }
  10173. isExactClass(batchId, className) {
  10174. assert$7(typeof className === 'string', className);
  10175. return this.getExactClassName(batchId) === className;
  10176. }
  10177. getExactClassName(batchId) {
  10178. this._checkBatchId(batchId);
  10179. if (this._hierarchy) {
  10180. const classId = this._hierarchy.classIds[batchId];
  10181. const instanceClass = this._hierarchy.classes[classId];
  10182. return instanceClass.name;
  10183. }
  10184. return undefined;
  10185. }
  10186. hasProperty(batchId, name) {
  10187. this._checkBatchId(batchId);
  10188. assert$7(typeof name === 'string', name);
  10189. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10190. }
  10191. getPropertyNames(batchId, results) {
  10192. this._checkBatchId(batchId);
  10193. results = defined(results) ? results : [];
  10194. results.length = 0;
  10195. const propertyNames = Object.keys(this._properties);
  10196. results.push(...propertyNames);
  10197. if (this._hierarchy) {
  10198. this._getPropertyNamesInHierarchy(batchId, results);
  10199. }
  10200. return results;
  10201. }
  10202. getProperty(batchId, name) {
  10203. this._checkBatchId(batchId);
  10204. assert$7(typeof name === 'string', name);
  10205. if (this._binaryProperties) {
  10206. const binaryProperty = this._binaryProperties[name];
  10207. if (defined(binaryProperty)) {
  10208. return this._getBinaryProperty(binaryProperty, batchId);
  10209. }
  10210. }
  10211. const propertyValues = this._properties[name];
  10212. if (defined(propertyValues)) {
  10213. return clone(propertyValues[batchId]);
  10214. }
  10215. if (this._hierarchy) {
  10216. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10217. if (defined(hierarchyProperty)) {
  10218. return hierarchyProperty;
  10219. }
  10220. }
  10221. return undefined;
  10222. }
  10223. setProperty(batchId, name, value) {
  10224. const featureCount = this.featureCount;
  10225. this._checkBatchId(batchId);
  10226. assert$7(typeof name === 'string', name);
  10227. if (this._binaryProperties) {
  10228. const binaryProperty = this._binaryProperties[name];
  10229. if (binaryProperty) {
  10230. this._setBinaryProperty(binaryProperty, batchId, value);
  10231. return;
  10232. }
  10233. }
  10234. if (this._hierarchy) {
  10235. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10236. return;
  10237. }
  10238. }
  10239. let propertyValues = this._properties[name];
  10240. if (!defined(propertyValues)) {
  10241. this._properties[name] = new Array(featureCount);
  10242. propertyValues = this._properties[name];
  10243. }
  10244. propertyValues[batchId] = clone(value);
  10245. }
  10246. _checkBatchId(batchId) {
  10247. const valid = batchId >= 0 && batchId < this.featureCount;
  10248. if (!valid) {
  10249. throw new Error('batchId not in range [0, featureCount - 1].');
  10250. }
  10251. }
  10252. _getBinaryProperty(binaryProperty, index) {
  10253. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10254. }
  10255. _setBinaryProperty(binaryProperty, index, value) {
  10256. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10257. }
  10258. _initializeBinaryProperties() {
  10259. let binaryProperties = null;
  10260. for (const name in this._properties) {
  10261. const property = this._properties[name];
  10262. const binaryProperty = this._initializeBinaryProperty(name, property);
  10263. if (binaryProperty) {
  10264. binaryProperties = binaryProperties || {};
  10265. binaryProperties[name] = binaryProperty;
  10266. }
  10267. }
  10268. return binaryProperties;
  10269. }
  10270. _initializeBinaryProperty(name, property) {
  10271. if ('byteOffset' in property) {
  10272. const tile3DAccessor = property;
  10273. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10274. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10275. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10276. return {
  10277. typedArray: accessor.values,
  10278. componentCount: accessor.size,
  10279. unpack: accessor.unpacker,
  10280. pack: accessor.packer
  10281. };
  10282. }
  10283. return null;
  10284. }
  10285. _hasPropertyInHierarchy(batchId, name) {
  10286. if (!this._hierarchy) {
  10287. return false;
  10288. }
  10289. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10290. const classId = hierarchy.classIds[instanceIndex];
  10291. const instances = hierarchy.classes[classId].instances;
  10292. return defined(instances[name]);
  10293. });
  10294. return defined(result);
  10295. }
  10296. _getPropertyNamesInHierarchy(batchId, results) {
  10297. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10298. const classId = hierarchy.classIds[instanceIndex];
  10299. const instances = hierarchy.classes[classId].instances;
  10300. for (const name in instances) {
  10301. if (instances.hasOwnProperty(name)) {
  10302. if (results.indexOf(name) === -1) {
  10303. results.push(name);
  10304. }
  10305. }
  10306. }
  10307. });
  10308. }
  10309. _getHierarchyProperty(batchId, name) {
  10310. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10311. const classId = hierarchy.classIds[instanceIndex];
  10312. const instanceClass = hierarchy.classes[classId];
  10313. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10314. const propertyValues = instanceClass.instances[name];
  10315. if (defined(propertyValues)) {
  10316. if (defined(propertyValues.typedArray)) {
  10317. return this._getBinaryProperty(propertyValues, indexInClass);
  10318. }
  10319. return clone(propertyValues[indexInClass]);
  10320. }
  10321. return null;
  10322. });
  10323. }
  10324. _setHierarchyProperty(batchTable, batchId, name, value) {
  10325. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10326. const classId = hierarchy.classIds[instanceIndex];
  10327. const instanceClass = hierarchy.classes[classId];
  10328. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10329. const propertyValues = instanceClass.instances[name];
  10330. if (defined(propertyValues)) {
  10331. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10332. if (defined(propertyValues.typedArray)) {
  10333. this._setBinaryProperty(propertyValues, indexInClass, value);
  10334. } else {
  10335. propertyValues[indexInClass] = clone(value);
  10336. }
  10337. return true;
  10338. }
  10339. return false;
  10340. });
  10341. return defined(result);
  10342. }
  10343. }
  10344. const SIZEOF_UINT32$1 = 4;
  10345. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10346. const view = new DataView(arrayBuffer);
  10347. tile.magic = view.getUint32(byteOffset, true);
  10348. byteOffset += SIZEOF_UINT32$1;
  10349. tile.version = view.getUint32(byteOffset, true);
  10350. byteOffset += SIZEOF_UINT32$1;
  10351. tile.byteLength = view.getUint32(byteOffset, true);
  10352. byteOffset += SIZEOF_UINT32$1;
  10353. if (tile.version !== 1) {
  10354. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10355. }
  10356. return byteOffset;
  10357. }
  10358. const SIZEOF_UINT32 = 4;
  10359. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10360. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10361. const view = new DataView(arrayBuffer);
  10362. let batchLength;
  10363. tile.header = tile.header || {};
  10364. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10365. byteOffset += SIZEOF_UINT32;
  10366. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10367. byteOffset += SIZEOF_UINT32;
  10368. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10369. byteOffset += SIZEOF_UINT32;
  10370. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10371. byteOffset += SIZEOF_UINT32;
  10372. if (batchTableJsonByteLength >= 570425344) {
  10373. byteOffset -= SIZEOF_UINT32 * 2;
  10374. batchLength = featureTableJsonByteLength;
  10375. batchTableJsonByteLength = featureTableBinaryByteLength;
  10376. batchTableBinaryByteLength = 0;
  10377. featureTableJsonByteLength = 0;
  10378. featureTableBinaryByteLength = 0;
  10379. console.warn(DEPRECATION_WARNING);
  10380. } else if (batchTableBinaryByteLength >= 570425344) {
  10381. byteOffset -= SIZEOF_UINT32;
  10382. batchLength = batchTableJsonByteLength;
  10383. batchTableJsonByteLength = featureTableJsonByteLength;
  10384. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10385. featureTableJsonByteLength = 0;
  10386. featureTableBinaryByteLength = 0;
  10387. console.warn(DEPRECATION_WARNING);
  10388. }
  10389. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10390. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10391. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10392. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10393. tile.header.batchLength = batchLength;
  10394. return byteOffset;
  10395. }
  10396. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10397. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10398. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10399. return byteOffset;
  10400. }
  10401. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10402. const {
  10403. featureTableJsonByteLength,
  10404. featureTableBinaryByteLength,
  10405. batchLength
  10406. } = tile.header;
  10407. tile.featureTableJson = {
  10408. BATCH_LENGTH: batchLength || 0
  10409. };
  10410. if (featureTableJsonByteLength > 0) {
  10411. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10412. tile.featureTableJson = JSON.parse(featureTableString);
  10413. }
  10414. byteOffset += featureTableJsonByteLength;
  10415. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10416. byteOffset += featureTableBinaryByteLength;
  10417. return byteOffset;
  10418. }
  10419. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10420. const {
  10421. batchTableJsonByteLength,
  10422. batchTableBinaryByteLength
  10423. } = tile.header;
  10424. if (batchTableJsonByteLength > 0) {
  10425. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10426. tile.batchTableJson = JSON.parse(batchTableString);
  10427. byteOffset += batchTableJsonByteLength;
  10428. if (batchTableBinaryByteLength > 0) {
  10429. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10430. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10431. byteOffset += batchTableBinaryByteLength;
  10432. }
  10433. }
  10434. return byteOffset;
  10435. }
  10436. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10437. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10438. return null;
  10439. }
  10440. const {
  10441. batchIds,
  10442. isRGB565,
  10443. pointCount
  10444. } = tile;
  10445. if (batchIds && batchTable) {
  10446. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10447. for (let i = 0; i < pointCount; i++) {
  10448. const batchId = batchIds[i];
  10449. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10450. const color = dimensions.map(d => d * 255);
  10451. colorArray[i * 3] = color[0];
  10452. colorArray[i * 3 + 1] = color[1];
  10453. colorArray[i * 3 + 2] = color[2];
  10454. }
  10455. return {
  10456. type: GL$1.UNSIGNED_BYTE,
  10457. value: colorArray,
  10458. size: 3,
  10459. normalized: true
  10460. };
  10461. }
  10462. if (isRGB565) {
  10463. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10464. for (let i = 0; i < pointCount; i++) {
  10465. const color = decodeRGB565(colors[i]);
  10466. colorArray[i * 3] = color[0];
  10467. colorArray[i * 3 + 1] = color[1];
  10468. colorArray[i * 3 + 2] = color[2];
  10469. }
  10470. return {
  10471. type: GL$1.UNSIGNED_BYTE,
  10472. value: colorArray,
  10473. size: 3,
  10474. normalized: true
  10475. };
  10476. }
  10477. if (colors && colors.length === pointCount * 3) {
  10478. return {
  10479. type: GL$1.UNSIGNED_BYTE,
  10480. value: colors,
  10481. size: 3,
  10482. normalized: true
  10483. };
  10484. }
  10485. return {
  10486. type: GL$1.UNSIGNED_BYTE,
  10487. value: colors,
  10488. size: 4,
  10489. normalized: true
  10490. };
  10491. }
  10492. const scratchNormal = new Vector3();
  10493. function normalize3DTileNormalAttribute(tile, normals) {
  10494. if (!normals) {
  10495. return null;
  10496. }
  10497. if (tile.isOctEncoded16P) {
  10498. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10499. for (let i = 0; i < tile.pointsLength; i++) {
  10500. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10501. scratchNormal.toArray(decodedArray, i * 3);
  10502. }
  10503. return {
  10504. type: GL$1.FLOAT,
  10505. size: 2,
  10506. value: decodedArray
  10507. };
  10508. }
  10509. return {
  10510. type: GL$1.FLOAT,
  10511. size: 2,
  10512. value: normals
  10513. };
  10514. }
  10515. function normalize3DTilePositionAttribute(tile, positions, options) {
  10516. if (!tile.isQuantized) {
  10517. return positions;
  10518. }
  10519. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10520. tile.isQuantized = false;
  10521. return decodeQuantizedPositions(tile, positions);
  10522. }
  10523. return {
  10524. type: GL$1.UNSIGNED_SHORT,
  10525. value: positions,
  10526. size: 3,
  10527. normalized: true
  10528. };
  10529. }
  10530. function decodeQuantizedPositions(tile, positions) {
  10531. const scratchPosition = new Vector3();
  10532. const decodedArray = new Float32Array(tile.pointCount * 3);
  10533. for (let i = 0; i < tile.pointCount; i++) {
  10534. 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);
  10535. }
  10536. return decodedArray;
  10537. }
  10538. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10539. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10540. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10541. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10542. initializeTile(tile);
  10543. const {
  10544. featureTable,
  10545. batchTable
  10546. } = parsePointCloudTables(tile);
  10547. await parseDraco(tile, featureTable, batchTable, options, context);
  10548. parsePositions(tile, featureTable, options);
  10549. parseColors(tile, featureTable, batchTable);
  10550. parseNormals(tile, featureTable);
  10551. return byteOffset;
  10552. }
  10553. function initializeTile(tile) {
  10554. tile.attributes = {
  10555. positions: null,
  10556. colors: null,
  10557. normals: null,
  10558. batchIds: null
  10559. };
  10560. tile.isQuantized = false;
  10561. tile.isTranslucent = false;
  10562. tile.isRGB565 = false;
  10563. tile.isOctEncoded16P = false;
  10564. }
  10565. function parsePointCloudTables(tile) {
  10566. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10567. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10568. if (!Number.isFinite(pointsLength)) {
  10569. throw new Error('POINTS_LENGTH must be defined');
  10570. }
  10571. featureTable.featuresLength = pointsLength;
  10572. tile.featuresLength = pointsLength;
  10573. tile.pointsLength = pointsLength;
  10574. tile.pointCount = pointsLength;
  10575. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10576. const batchTable = parseBatchIds(tile, featureTable);
  10577. return {
  10578. featureTable,
  10579. batchTable
  10580. };
  10581. }
  10582. function parsePositions(tile, featureTable, options) {
  10583. if (!tile.attributes.positions) {
  10584. if (featureTable.hasProperty('POSITION')) {
  10585. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10586. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10587. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10588. tile.isQuantized = true;
  10589. tile.quantizedRange = (1 << 16) - 1;
  10590. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10591. if (!tile.quantizedVolumeScale) {
  10592. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10593. }
  10594. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10595. if (!tile.quantizedVolumeOffset) {
  10596. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10597. }
  10598. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10599. }
  10600. }
  10601. if (!tile.attributes.positions) {
  10602. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10603. }
  10604. }
  10605. function parseColors(tile, featureTable, batchTable) {
  10606. if (!tile.attributes.colors) {
  10607. let colors = null;
  10608. if (featureTable.hasProperty('RGBA')) {
  10609. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10610. tile.isTranslucent = true;
  10611. } else if (featureTable.hasProperty('RGB')) {
  10612. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10613. } else if (featureTable.hasProperty('RGB565')) {
  10614. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10615. tile.isRGB565 = true;
  10616. }
  10617. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10618. }
  10619. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10620. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10621. }
  10622. }
  10623. function parseNormals(tile, featureTable) {
  10624. if (!tile.attributes.normals) {
  10625. let normals = null;
  10626. if (featureTable.hasProperty('NORMAL')) {
  10627. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10628. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10629. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10630. tile.isOctEncoded16P = true;
  10631. }
  10632. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10633. }
  10634. }
  10635. function parseBatchIds(tile, featureTable) {
  10636. let batchTable = null;
  10637. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10638. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10639. if (tile.batchIds) {
  10640. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10641. if (!batchFeatureLength) {
  10642. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10643. }
  10644. const {
  10645. batchTableJson,
  10646. batchTableBinary
  10647. } = tile;
  10648. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10649. }
  10650. }
  10651. return batchTable;
  10652. }
  10653. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10654. let dracoBuffer;
  10655. let dracoFeatureTableProperties;
  10656. let dracoBatchTableProperties;
  10657. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10658. if (batchTableDraco) {
  10659. dracoBatchTableProperties = batchTableDraco.properties;
  10660. }
  10661. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10662. if (featureTableDraco) {
  10663. dracoFeatureTableProperties = featureTableDraco.properties;
  10664. const dracoByteOffset = featureTableDraco.byteOffset;
  10665. const dracoByteLength = featureTableDraco.byteLength;
  10666. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10667. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10668. }
  10669. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10670. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10671. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10672. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10673. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10674. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10675. }
  10676. if (!dracoBuffer) {
  10677. return true;
  10678. }
  10679. const dracoData = {
  10680. buffer: dracoBuffer,
  10681. properties: { ...dracoFeatureTableProperties,
  10682. ...dracoBatchTableProperties
  10683. },
  10684. featureTableProperties: dracoFeatureTableProperties,
  10685. batchTableProperties: dracoBatchTableProperties,
  10686. dequantizeInShader: false
  10687. };
  10688. return await loadDraco(tile, dracoData, options, context);
  10689. }
  10690. async function loadDraco(tile, dracoData, options, context) {
  10691. const {
  10692. parse
  10693. } = context;
  10694. const dracoOptions = { ...options,
  10695. draco: { ...options.draco,
  10696. extraAttributes: dracoData.batchTableProperties || {}
  10697. }
  10698. };
  10699. delete dracoOptions['3d-tiles'];
  10700. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10701. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10702. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10703. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10704. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10705. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10706. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10707. if (isQuantizedDraco) {
  10708. const quantization = data.POSITION.data.quantization;
  10709. const range = quantization.range;
  10710. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10711. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10712. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10713. tile.isQuantizedDraco = true;
  10714. }
  10715. if (isOctEncodedDraco) {
  10716. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10717. tile.isOctEncodedDraco = true;
  10718. }
  10719. const batchTableAttributes = {};
  10720. if (dracoData.batchTableProperties) {
  10721. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10722. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10723. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10724. }
  10725. }
  10726. }
  10727. tile.attributes = {
  10728. positions: decodedPositions,
  10729. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10730. normals: decodedNormals,
  10731. batchIds: decodedBatchIds,
  10732. ...batchTableAttributes
  10733. };
  10734. }
  10735. const VERSION$3 = "3.1.4" ;
  10736. const VERSION$2 = "3.1.4" ;
  10737. const VERSION$1 = "3.1.4" ;
  10738. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10739. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10740. let loadBasisTranscoderPromise;
  10741. async function loadBasisTrascoderModule(options) {
  10742. const modules = options.modules || {};
  10743. if (modules.basis) {
  10744. return modules.basis;
  10745. }
  10746. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10747. return await loadBasisTranscoderPromise;
  10748. }
  10749. async function loadBasisTrascoder(options) {
  10750. let BASIS = null;
  10751. let wasmBinary = null;
  10752. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10753. BASIS = BASIS || globalThis.BASIS;
  10754. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10755. }
  10756. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10757. const options = {};
  10758. if (wasmBinary) {
  10759. options.wasmBinary = wasmBinary;
  10760. }
  10761. return new Promise(resolve => {
  10762. BasisModule(options).then(module => {
  10763. const {
  10764. BasisFile,
  10765. initializeBasis
  10766. } = module;
  10767. initializeBasis();
  10768. resolve({
  10769. BasisFile
  10770. });
  10771. });
  10772. });
  10773. }
  10774. let loadBasisEncoderPromise;
  10775. async function loadBasisEncoderModule(options) {
  10776. const modules = options.modules || {};
  10777. if (modules.basisEncoder) {
  10778. return modules.basisEncoder;
  10779. }
  10780. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10781. return await loadBasisEncoderPromise;
  10782. }
  10783. async function loadBasisEncoder(options) {
  10784. let BASIS_ENCODER = null;
  10785. let wasmBinary = null;
  10786. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10787. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10788. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10789. }
  10790. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10791. const options = {};
  10792. if (wasmBinary) {
  10793. options.wasmBinary = wasmBinary;
  10794. }
  10795. return new Promise(resolve => {
  10796. BasisEncoderModule(options).then(module => {
  10797. const {
  10798. BasisFile,
  10799. KTX2File,
  10800. initializeBasis,
  10801. BasisEncoder
  10802. } = module;
  10803. initializeBasis();
  10804. resolve({
  10805. BasisFile,
  10806. KTX2File,
  10807. BasisEncoder
  10808. });
  10809. });
  10810. });
  10811. }
  10812. const GL_EXTENSIONS_CONSTANTS = {
  10813. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10814. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10815. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10816. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10817. COMPRESSED_R11_EAC: 0x9270,
  10818. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10819. COMPRESSED_RG11_EAC: 0x9272,
  10820. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10821. COMPRESSED_RGB8_ETC2: 0x9274,
  10822. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10823. COMPRESSED_SRGB8_ETC2: 0x9276,
  10824. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10825. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10826. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10827. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10828. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10829. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10830. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10831. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10832. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10833. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10834. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10835. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10836. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10837. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10838. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10839. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10840. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10841. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10842. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10843. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10844. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10845. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10846. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10847. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10848. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10849. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10850. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10851. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10852. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10853. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10854. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10855. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10856. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10857. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10858. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10859. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10860. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10861. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10862. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10863. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10864. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10865. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10866. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10867. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10868. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10869. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10870. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10871. };
  10872. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10873. const WEBGL_EXTENSIONS = {
  10874. WEBGL_compressed_texture_s3tc: 'dxt',
  10875. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10876. WEBGL_compressed_texture_etc1: 'etc1',
  10877. WEBGL_compressed_texture_etc: 'etc2',
  10878. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10879. WEBGL_compressed_texture_atc: 'atc',
  10880. WEBGL_compressed_texture_astc: 'astc',
  10881. EXT_texture_compression_rgtc: 'rgtc'
  10882. };
  10883. let formats = null;
  10884. function getSupportedGPUTextureFormats(gl) {
  10885. if (!formats) {
  10886. gl = gl || getWebGLContext() || undefined;
  10887. formats = new Set();
  10888. for (const prefix of BROWSER_PREFIXES) {
  10889. for (const extension in WEBGL_EXTENSIONS) {
  10890. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10891. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10892. formats.add(gpuTextureFormat);
  10893. }
  10894. }
  10895. }
  10896. }
  10897. return formats;
  10898. }
  10899. function getWebGLContext() {
  10900. try {
  10901. const canvas = document.createElement('canvas');
  10902. return canvas.getContext('webgl');
  10903. } catch (error) {
  10904. return null;
  10905. }
  10906. }
  10907. 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={}));
  10908. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10909. function isKTX(data) {
  10910. const id = new Uint8Array(data);
  10911. 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];
  10912. return !notKTX;
  10913. }
  10914. const OutputFormat = {
  10915. etc1: {
  10916. basisFormat: 0,
  10917. compressed: true,
  10918. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10919. },
  10920. etc2: {
  10921. basisFormat: 1,
  10922. compressed: true
  10923. },
  10924. bc1: {
  10925. basisFormat: 2,
  10926. compressed: true,
  10927. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10928. },
  10929. bc3: {
  10930. basisFormat: 3,
  10931. compressed: true,
  10932. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10933. },
  10934. bc4: {
  10935. basisFormat: 4,
  10936. compressed: true
  10937. },
  10938. bc5: {
  10939. basisFormat: 5,
  10940. compressed: true
  10941. },
  10942. 'bc7-m6-opaque-only': {
  10943. basisFormat: 6,
  10944. compressed: true
  10945. },
  10946. 'bc7-m5': {
  10947. basisFormat: 7,
  10948. compressed: true
  10949. },
  10950. 'pvrtc1-4-rgb': {
  10951. basisFormat: 8,
  10952. compressed: true,
  10953. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10954. },
  10955. 'pvrtc1-4-rgba': {
  10956. basisFormat: 9,
  10957. compressed: true,
  10958. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10959. },
  10960. 'astc-4x4': {
  10961. basisFormat: 10,
  10962. compressed: true,
  10963. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10964. },
  10965. 'atc-rgb': {
  10966. basisFormat: 11,
  10967. compressed: true
  10968. },
  10969. 'atc-rgba-interpolated-alpha': {
  10970. basisFormat: 12,
  10971. compressed: true
  10972. },
  10973. rgba32: {
  10974. basisFormat: 13,
  10975. compressed: false
  10976. },
  10977. rgb565: {
  10978. basisFormat: 14,
  10979. compressed: false
  10980. },
  10981. bgr565: {
  10982. basisFormat: 15,
  10983. compressed: false
  10984. },
  10985. rgba4444: {
  10986. basisFormat: 16,
  10987. compressed: false
  10988. }
  10989. };
  10990. async function parseBasis(data, options) {
  10991. if (options.basis.containerFormat === 'auto') {
  10992. if (isKTX(data)) {
  10993. const fileConstructors = await loadBasisEncoderModule(options);
  10994. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10995. }
  10996. const {
  10997. BasisFile
  10998. } = await loadBasisTrascoderModule(options);
  10999. return parseBasisFile(BasisFile, data, options);
  11000. }
  11001. switch (options.basis.module) {
  11002. case 'encoder':
  11003. const fileConstructors = await loadBasisEncoderModule(options);
  11004. switch (options.basis.containerFormat) {
  11005. case 'ktx2':
  11006. return parseKTX2File(fileConstructors.KTX2File, data, options);
  11007. case 'basis':
  11008. default:
  11009. return parseBasisFile(fileConstructors.BasisFile, data, options);
  11010. }
  11011. case 'transcoder':
  11012. default:
  11013. const {
  11014. BasisFile
  11015. } = await loadBasisTrascoderModule(options);
  11016. return parseBasisFile(BasisFile, data, options);
  11017. }
  11018. }
  11019. function parseBasisFile(BasisFile, data, options) {
  11020. const basisFile = new BasisFile(new Uint8Array(data));
  11021. try {
  11022. if (!basisFile.startTranscoding()) {
  11023. return null;
  11024. }
  11025. const imageCount = basisFile.getNumImages();
  11026. const images = [];
  11027. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  11028. const levelsCount = basisFile.getNumLevels(imageIndex);
  11029. const levels = [];
  11030. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11031. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  11032. }
  11033. images.push(levels);
  11034. }
  11035. return images;
  11036. } finally {
  11037. basisFile.close();
  11038. basisFile.delete();
  11039. }
  11040. }
  11041. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  11042. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  11043. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  11044. const hasAlpha = basisFile.getHasAlpha();
  11045. const {
  11046. compressed,
  11047. format,
  11048. basisFormat
  11049. } = getBasisOptions(options, hasAlpha);
  11050. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  11051. const decodedData = new Uint8Array(decodedSize);
  11052. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  11053. return null;
  11054. }
  11055. return {
  11056. width,
  11057. height,
  11058. data: decodedData,
  11059. compressed,
  11060. hasAlpha,
  11061. format
  11062. };
  11063. }
  11064. function parseKTX2File(KTX2File, data, options) {
  11065. const ktx2File = new KTX2File(new Uint8Array(data));
  11066. try {
  11067. if (!ktx2File.startTranscoding()) {
  11068. return null;
  11069. }
  11070. const levelsCount = ktx2File.getLevels();
  11071. const levels = [];
  11072. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11073. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  11074. break;
  11075. }
  11076. return levels;
  11077. } finally {
  11078. ktx2File.close();
  11079. ktx2File.delete();
  11080. }
  11081. }
  11082. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  11083. const {
  11084. alphaFlag,
  11085. height,
  11086. width
  11087. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  11088. const {
  11089. compressed,
  11090. format,
  11091. basisFormat
  11092. } = getBasisOptions(options, alphaFlag);
  11093. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  11094. const decodedData = new Uint8Array(decodedSize);
  11095. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  11096. return null;
  11097. }
  11098. return {
  11099. width,
  11100. height,
  11101. data: decodedData,
  11102. compressed,
  11103. alphaFlag,
  11104. format
  11105. };
  11106. }
  11107. function getBasisOptions(options, hasAlpha) {
  11108. let format = options && options.basis && options.basis.format;
  11109. if (format === 'auto') {
  11110. format = selectSupportedBasisFormat();
  11111. }
  11112. if (typeof format === 'object') {
  11113. format = hasAlpha ? format.alpha : format.noAlpha;
  11114. }
  11115. format = format.toLowerCase();
  11116. return OutputFormat[format];
  11117. }
  11118. function selectSupportedBasisFormat() {
  11119. const supportedFormats = getSupportedGPUTextureFormats();
  11120. if (supportedFormats.has('astc')) {
  11121. return 'astc-4x4';
  11122. } else if (supportedFormats.has('dxt')) {
  11123. return {
  11124. alpha: 'bc3',
  11125. noAlpha: 'bc1'
  11126. };
  11127. } else if (supportedFormats.has('pvrtc')) {
  11128. return {
  11129. alpha: 'pvrtc1-4-rgba',
  11130. noAlpha: 'pvrtc1-4-rgb'
  11131. };
  11132. } else if (supportedFormats.has('etc1')) {
  11133. return 'etc1';
  11134. } else if (supportedFormats.has('etc2')) {
  11135. return 'etc2';
  11136. }
  11137. return 'rgb565';
  11138. }
  11139. const BasisWorkerLoader = {
  11140. name: 'Basis',
  11141. id: 'basis',
  11142. module: 'textures',
  11143. version: VERSION$2,
  11144. worker: true,
  11145. extensions: ['basis', 'ktx2'],
  11146. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11147. tests: ['sB'],
  11148. binary: true,
  11149. options: {
  11150. basis: {
  11151. format: 'auto',
  11152. libraryPath: 'libs/',
  11153. containerFormat: 'auto',
  11154. module: 'transcoder'
  11155. }
  11156. }
  11157. };
  11158. const BasisLoader = { ...BasisWorkerLoader,
  11159. parse: parseBasis
  11160. };
  11161. const VERSION = "3.1.4" ;
  11162. const {
  11163. _parseImageNode
  11164. } = globalThis;
  11165. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11166. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11167. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11168. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11169. function isImageTypeSupported(type) {
  11170. switch (type) {
  11171. case 'auto':
  11172. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11173. case 'imagebitmap':
  11174. return IMAGE_BITMAP_SUPPORTED;
  11175. case 'image':
  11176. return IMAGE_SUPPORTED;
  11177. case 'data':
  11178. return DATA_SUPPORTED;
  11179. default:
  11180. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11181. }
  11182. }
  11183. function getDefaultImageType() {
  11184. if (IMAGE_BITMAP_SUPPORTED) {
  11185. return 'imagebitmap';
  11186. }
  11187. if (IMAGE_SUPPORTED) {
  11188. return 'image';
  11189. }
  11190. if (DATA_SUPPORTED) {
  11191. return 'data';
  11192. }
  11193. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11194. }
  11195. function getImageType(image) {
  11196. const format = getImageTypeOrNull(image);
  11197. if (!format) {
  11198. throw new Error('Not an image');
  11199. }
  11200. return format;
  11201. }
  11202. function getImageData(image) {
  11203. switch (getImageType(image)) {
  11204. case 'data':
  11205. return image;
  11206. case 'image':
  11207. case 'imagebitmap':
  11208. const canvas = document.createElement('canvas');
  11209. const context = canvas.getContext('2d');
  11210. if (!context) {
  11211. throw new Error('getImageData');
  11212. }
  11213. canvas.width = image.width;
  11214. canvas.height = image.height;
  11215. context.drawImage(image, 0, 0);
  11216. return context.getImageData(0, 0, image.width, image.height);
  11217. default:
  11218. throw new Error('getImageData');
  11219. }
  11220. }
  11221. function getImageTypeOrNull(image) {
  11222. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11223. return 'imagebitmap';
  11224. }
  11225. if (typeof Image !== 'undefined' && image instanceof Image) {
  11226. return 'image';
  11227. }
  11228. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11229. return 'data';
  11230. }
  11231. return null;
  11232. }
  11233. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11234. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11235. function isSVG(url) {
  11236. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11237. }
  11238. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11239. if (isSVG(url)) {
  11240. const textDecoder = new TextDecoder();
  11241. let xmlText = textDecoder.decode(arrayBuffer);
  11242. try {
  11243. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11244. xmlText = unescape(encodeURIComponent(xmlText));
  11245. }
  11246. } catch (error) {
  11247. throw new Error(error.message);
  11248. }
  11249. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11250. return src;
  11251. }
  11252. return getBlob(arrayBuffer, url);
  11253. }
  11254. function getBlob(arrayBuffer, url) {
  11255. if (isSVG(url)) {
  11256. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11257. }
  11258. return new Blob([new Uint8Array(arrayBuffer)]);
  11259. }
  11260. async function parseToImage(arrayBuffer, options, url) {
  11261. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11262. const URL = self.URL || self.webkitURL;
  11263. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11264. try {
  11265. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11266. } finally {
  11267. if (objectUrl) {
  11268. URL.revokeObjectURL(objectUrl);
  11269. }
  11270. }
  11271. }
  11272. async function loadToImage(url, options) {
  11273. const image = new Image();
  11274. image.src = url;
  11275. if (options.image && options.image.decode && image.decode) {
  11276. await image.decode();
  11277. return image;
  11278. }
  11279. return await new Promise((resolve, reject) => {
  11280. try {
  11281. image.onload = () => resolve(image);
  11282. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11283. } catch (error) {
  11284. reject(error);
  11285. }
  11286. });
  11287. }
  11288. const EMPTY_OBJECT = {};
  11289. let imagebitmapOptionsSupported = true;
  11290. async function parseToImageBitmap(arrayBuffer, options, url) {
  11291. let blob;
  11292. if (isSVG(url)) {
  11293. const image = await parseToImage(arrayBuffer, options, url);
  11294. blob = image;
  11295. } else {
  11296. blob = getBlob(arrayBuffer, url);
  11297. }
  11298. const imagebitmapOptions = options && options.imagebitmap;
  11299. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11300. }
  11301. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11302. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11303. imagebitmapOptions = null;
  11304. }
  11305. if (imagebitmapOptions) {
  11306. try {
  11307. return await createImageBitmap(blob, imagebitmapOptions);
  11308. } catch (error) {
  11309. console.warn(error);
  11310. imagebitmapOptionsSupported = false;
  11311. }
  11312. }
  11313. return await createImageBitmap(blob);
  11314. }
  11315. function isEmptyObject(object) {
  11316. for (const key in object || EMPTY_OBJECT) {
  11317. return false;
  11318. }
  11319. return true;
  11320. }
  11321. const BIG_ENDIAN = false;
  11322. const LITTLE_ENDIAN = true;
  11323. function getBinaryImageMetadata(binaryData) {
  11324. const dataView = toDataView(binaryData);
  11325. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11326. }
  11327. function getPngMetadata(binaryData) {
  11328. const dataView = toDataView(binaryData);
  11329. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11330. if (!isPng) {
  11331. return null;
  11332. }
  11333. return {
  11334. mimeType: 'image/png',
  11335. width: dataView.getUint32(16, BIG_ENDIAN),
  11336. height: dataView.getUint32(20, BIG_ENDIAN)
  11337. };
  11338. }
  11339. function getGifMetadata(binaryData) {
  11340. const dataView = toDataView(binaryData);
  11341. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11342. if (!isGif) {
  11343. return null;
  11344. }
  11345. return {
  11346. mimeType: 'image/gif',
  11347. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11348. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11349. };
  11350. }
  11351. function getBmpMetadata(binaryData) {
  11352. const dataView = toDataView(binaryData);
  11353. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11354. if (!isBmp) {
  11355. return null;
  11356. }
  11357. return {
  11358. mimeType: 'image/bmp',
  11359. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11360. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11361. };
  11362. }
  11363. function getJpegMetadata(binaryData) {
  11364. const dataView = toDataView(binaryData);
  11365. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11366. if (!isJpeg) {
  11367. return null;
  11368. }
  11369. const {
  11370. tableMarkers,
  11371. sofMarkers
  11372. } = getJpegMarkers();
  11373. let i = 2;
  11374. while (i + 9 < dataView.byteLength) {
  11375. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11376. if (sofMarkers.has(marker)) {
  11377. return {
  11378. mimeType: 'image/jpeg',
  11379. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11380. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11381. };
  11382. }
  11383. if (!tableMarkers.has(marker)) {
  11384. return null;
  11385. }
  11386. i += 2;
  11387. i += dataView.getUint16(i, BIG_ENDIAN);
  11388. }
  11389. return null;
  11390. }
  11391. function getJpegMarkers() {
  11392. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11393. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11394. tableMarkers.add(i);
  11395. }
  11396. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11397. return {
  11398. tableMarkers,
  11399. sofMarkers
  11400. };
  11401. }
  11402. function toDataView(data) {
  11403. if (data instanceof DataView) {
  11404. return data;
  11405. }
  11406. if (ArrayBuffer.isView(data)) {
  11407. return new DataView(data.buffer);
  11408. }
  11409. if (data instanceof ArrayBuffer) {
  11410. return new DataView(data);
  11411. }
  11412. throw new Error('toDataView');
  11413. }
  11414. async function parseToNodeImage(arrayBuffer, options) {
  11415. const {
  11416. mimeType
  11417. } = getBinaryImageMetadata(arrayBuffer) || {};
  11418. const _parseImageNode = globalThis._parseImageNode;
  11419. assert$7(_parseImageNode);
  11420. return await _parseImageNode(arrayBuffer, mimeType);
  11421. }
  11422. async function parseImage(arrayBuffer, options, context) {
  11423. options = options || {};
  11424. const imageOptions = options.image || {};
  11425. const imageType = imageOptions.type || 'auto';
  11426. const {
  11427. url
  11428. } = context || {};
  11429. const loadType = getLoadableImageType(imageType);
  11430. let image;
  11431. switch (loadType) {
  11432. case 'imagebitmap':
  11433. image = await parseToImageBitmap(arrayBuffer, options, url);
  11434. break;
  11435. case 'image':
  11436. image = await parseToImage(arrayBuffer, options, url);
  11437. break;
  11438. case 'data':
  11439. image = await parseToNodeImage(arrayBuffer);
  11440. break;
  11441. default:
  11442. assert$7(false);
  11443. }
  11444. if (imageType === 'data') {
  11445. image = getImageData(image);
  11446. }
  11447. return image;
  11448. }
  11449. function getLoadableImageType(type) {
  11450. switch (type) {
  11451. case 'auto':
  11452. case 'data':
  11453. return getDefaultImageType();
  11454. default:
  11455. isImageTypeSupported(type);
  11456. return type;
  11457. }
  11458. }
  11459. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11460. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11461. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11462. image: {
  11463. type: 'auto',
  11464. decode: true
  11465. }
  11466. };
  11467. const ImageLoader = {
  11468. id: 'image',
  11469. module: 'images',
  11470. name: 'Images',
  11471. version: VERSION,
  11472. mimeTypes: MIME_TYPES,
  11473. extensions: EXTENSIONS$1,
  11474. parse: parseImage,
  11475. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11476. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11477. };
  11478. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11479. const mimeTypeSupported = {};
  11480. function _isImageFormatSupported(mimeType) {
  11481. if (mimeTypeSupported[mimeType] === undefined) {
  11482. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11483. }
  11484. return mimeTypeSupported[mimeType];
  11485. }
  11486. function checkFormatSupport(mimeType) {
  11487. switch (mimeType) {
  11488. case 'image/webp':
  11489. return checkWebPSupport();
  11490. case 'image/svg':
  11491. return isBrowser$2;
  11492. default:
  11493. if (!isBrowser$2) {
  11494. const {
  11495. _parseImageNode
  11496. } = globalThis;
  11497. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11498. }
  11499. return true;
  11500. }
  11501. }
  11502. function checkWebPSupport() {
  11503. if (!isBrowser$2) {
  11504. return false;
  11505. }
  11506. try {
  11507. const element = document.createElement('canvas');
  11508. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11509. } catch {
  11510. return false;
  11511. }
  11512. }
  11513. function assert$1(condition, message) {
  11514. if (!condition) {
  11515. throw new Error(message || 'assert failed: gltf');
  11516. }
  11517. }
  11518. function resolveUrl(url, options) {
  11519. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11520. if (absolute) {
  11521. return url;
  11522. }
  11523. const baseUrl = options.baseUri || options.uri;
  11524. if (!baseUrl) {
  11525. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11526. }
  11527. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11528. }
  11529. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11530. const bufferView = json.bufferViews[bufferViewIndex];
  11531. assert$1(bufferView);
  11532. const bufferIndex = bufferView.buffer;
  11533. const binChunk = buffers[bufferIndex];
  11534. assert$1(binChunk);
  11535. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11536. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11537. }
  11538. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11539. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11540. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11541. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11542. SCALAR: 1,
  11543. VEC2: 2,
  11544. VEC3: 3,
  11545. VEC4: 4,
  11546. MAT2: 4,
  11547. MAT3: 9,
  11548. MAT4: 16
  11549. };
  11550. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11551. 5120: 1,
  11552. 5121: 1,
  11553. 5122: 2,
  11554. 5123: 2,
  11555. 5125: 4,
  11556. 5126: 4
  11557. };
  11558. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11559. 5120: Int8Array,
  11560. 5121: Uint8Array,
  11561. 5122: Int16Array,
  11562. 5123: Uint16Array,
  11563. 5125: Uint32Array,
  11564. 5126: Float32Array
  11565. };
  11566. function getAccessorTypeFromSize(size) {
  11567. const type = TYPES[size - 1];
  11568. return type || TYPES[0];
  11569. }
  11570. function getComponentTypeFromArray(typedArray) {
  11571. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11572. if (!componentType) {
  11573. throw new Error('Illegal typed array');
  11574. }
  11575. return componentType;
  11576. }
  11577. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11578. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11579. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11580. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11581. const length = accessor.count * components;
  11582. const byteLength = accessor.count * components * bytesPerComponent;
  11583. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11584. return {
  11585. ArrayType,
  11586. length,
  11587. byteLength
  11588. };
  11589. }
  11590. const DEFAULT_GLTF_JSON = {
  11591. asset: {
  11592. version: '2.0',
  11593. generator: 'loaders.gl'
  11594. },
  11595. buffers: []
  11596. };
  11597. class GLTFScenegraph {
  11598. constructor(gltf) {
  11599. _defineProperty(this, "gltf", void 0);
  11600. _defineProperty(this, "sourceBuffers", void 0);
  11601. _defineProperty(this, "byteLength", void 0);
  11602. this.gltf = gltf || {
  11603. json: { ...DEFAULT_GLTF_JSON
  11604. },
  11605. buffers: []
  11606. };
  11607. this.sourceBuffers = [];
  11608. this.byteLength = 0;
  11609. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11610. this.byteLength = this.gltf.buffers[0].byteLength;
  11611. this.sourceBuffers = [this.gltf.buffers[0]];
  11612. }
  11613. }
  11614. get json() {
  11615. return this.gltf.json;
  11616. }
  11617. getApplicationData(key) {
  11618. const data = this.json[key];
  11619. return data;
  11620. }
  11621. getExtraData(key) {
  11622. const extras = this.json.extras || {};
  11623. return extras[key];
  11624. }
  11625. getExtension(extensionName) {
  11626. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11627. const extensions = this.json.extensions || {};
  11628. return isExtension ? extensions[extensionName] || true : null;
  11629. }
  11630. getRequiredExtension(extensionName) {
  11631. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11632. return isRequired ? this.getExtension(extensionName) : null;
  11633. }
  11634. getRequiredExtensions() {
  11635. return this.json.extensionsRequired || [];
  11636. }
  11637. getUsedExtensions() {
  11638. return this.json.extensionsUsed || [];
  11639. }
  11640. getObjectExtension(object, extensionName) {
  11641. const extensions = object.extensions || {};
  11642. return extensions[extensionName];
  11643. }
  11644. getScene(index) {
  11645. return this.getObject('scenes', index);
  11646. }
  11647. getNode(index) {
  11648. return this.getObject('nodes', index);
  11649. }
  11650. getSkin(index) {
  11651. return this.getObject('skins', index);
  11652. }
  11653. getMesh(index) {
  11654. return this.getObject('meshes', index);
  11655. }
  11656. getMaterial(index) {
  11657. return this.getObject('materials', index);
  11658. }
  11659. getAccessor(index) {
  11660. return this.getObject('accessors', index);
  11661. }
  11662. getTexture(index) {
  11663. return this.getObject('textures', index);
  11664. }
  11665. getSampler(index) {
  11666. return this.getObject('samplers', index);
  11667. }
  11668. getImage(index) {
  11669. return this.getObject('images', index);
  11670. }
  11671. getBufferView(index) {
  11672. return this.getObject('bufferViews', index);
  11673. }
  11674. getBuffer(index) {
  11675. return this.getObject('buffers', index);
  11676. }
  11677. getObject(array, index) {
  11678. if (typeof index === 'object') {
  11679. return index;
  11680. }
  11681. const object = this.json[array] && this.json[array][index];
  11682. if (!object) {
  11683. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11684. }
  11685. return object;
  11686. }
  11687. getTypedArrayForBufferView(bufferView) {
  11688. bufferView = this.getBufferView(bufferView);
  11689. const bufferIndex = bufferView.buffer;
  11690. const binChunk = this.gltf.buffers[bufferIndex];
  11691. assert$1(binChunk);
  11692. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11693. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11694. }
  11695. getTypedArrayForAccessor(accessor) {
  11696. accessor = this.getAccessor(accessor);
  11697. const bufferView = this.getBufferView(accessor.bufferView);
  11698. const buffer = this.getBuffer(bufferView.buffer);
  11699. const arrayBuffer = buffer.data;
  11700. const {
  11701. ArrayType,
  11702. length
  11703. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11704. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11705. return new ArrayType(arrayBuffer, byteOffset, length);
  11706. }
  11707. getTypedArrayForImageData(image) {
  11708. image = this.getAccessor(image);
  11709. const bufferView = this.getBufferView(image.bufferView);
  11710. const buffer = this.getBuffer(bufferView.buffer);
  11711. const arrayBuffer = buffer.data;
  11712. const byteOffset = bufferView.byteOffset || 0;
  11713. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11714. }
  11715. addApplicationData(key, data) {
  11716. this.json[key] = data;
  11717. return this;
  11718. }
  11719. addExtraData(key, data) {
  11720. this.json.extras = this.json.extras || {};
  11721. this.json.extras[key] = data;
  11722. return this;
  11723. }
  11724. addObjectExtension(object, extensionName, data) {
  11725. object.extensions = object.extensions || {};
  11726. object.extensions[extensionName] = data;
  11727. this.registerUsedExtension(extensionName);
  11728. return this;
  11729. }
  11730. setObjectExtension(object, extensionName, data) {
  11731. const extensions = object.extensions || {};
  11732. extensions[extensionName] = data;
  11733. }
  11734. removeObjectExtension(object, extensionName) {
  11735. const extensions = object.extensions || {};
  11736. const extension = extensions[extensionName];
  11737. delete extensions[extensionName];
  11738. return extension;
  11739. }
  11740. addExtension(extensionName, extensionData = {}) {
  11741. assert$1(extensionData);
  11742. this.json.extensions = this.json.extensions || {};
  11743. this.json.extensions[extensionName] = extensionData;
  11744. this.registerUsedExtension(extensionName);
  11745. return extensionData;
  11746. }
  11747. addRequiredExtension(extensionName, extensionData = {}) {
  11748. assert$1(extensionData);
  11749. this.addExtension(extensionName, extensionData);
  11750. this.registerRequiredExtension(extensionName);
  11751. return extensionData;
  11752. }
  11753. registerUsedExtension(extensionName) {
  11754. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11755. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11756. this.json.extensionsUsed.push(extensionName);
  11757. }
  11758. }
  11759. registerRequiredExtension(extensionName) {
  11760. this.registerUsedExtension(extensionName);
  11761. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11762. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11763. this.json.extensionsRequired.push(extensionName);
  11764. }
  11765. }
  11766. removeExtension(extensionName) {
  11767. if (this.json.extensionsRequired) {
  11768. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11769. }
  11770. if (this.json.extensionsUsed) {
  11771. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11772. }
  11773. if (this.json.extensions) {
  11774. delete this.json.extensions[extensionName];
  11775. }
  11776. }
  11777. setDefaultScene(sceneIndex) {
  11778. this.json.scene = sceneIndex;
  11779. }
  11780. addScene(scene) {
  11781. const {
  11782. nodeIndices
  11783. } = scene;
  11784. this.json.scenes = this.json.scenes || [];
  11785. this.json.scenes.push({
  11786. nodes: nodeIndices
  11787. });
  11788. return this.json.scenes.length - 1;
  11789. }
  11790. addNode(node) {
  11791. const {
  11792. meshIndex,
  11793. matrix
  11794. } = node;
  11795. this.json.nodes = this.json.nodes || [];
  11796. const nodeData = {
  11797. mesh: meshIndex
  11798. };
  11799. if (matrix) {
  11800. nodeData.matrix = matrix;
  11801. }
  11802. this.json.nodes.push(nodeData);
  11803. return this.json.nodes.length - 1;
  11804. }
  11805. addMesh(mesh) {
  11806. const {
  11807. attributes,
  11808. indices,
  11809. material,
  11810. mode = 4
  11811. } = mesh;
  11812. const accessors = this._addAttributes(attributes);
  11813. const glTFMesh = {
  11814. primitives: [{
  11815. attributes: accessors,
  11816. mode
  11817. }]
  11818. };
  11819. if (indices) {
  11820. const indicesAccessor = this._addIndices(indices);
  11821. glTFMesh.primitives[0].indices = indicesAccessor;
  11822. }
  11823. if (Number.isFinite(material)) {
  11824. glTFMesh.primitives[0].material = material;
  11825. }
  11826. this.json.meshes = this.json.meshes || [];
  11827. this.json.meshes.push(glTFMesh);
  11828. return this.json.meshes.length - 1;
  11829. }
  11830. addPointCloud(attributes) {
  11831. const accessorIndices = this._addAttributes(attributes);
  11832. const glTFMesh = {
  11833. primitives: [{
  11834. attributes: accessorIndices,
  11835. mode: 0
  11836. }]
  11837. };
  11838. this.json.meshes = this.json.meshes || [];
  11839. this.json.meshes.push(glTFMesh);
  11840. return this.json.meshes.length - 1;
  11841. }
  11842. addImage(imageData, mimeTypeOpt) {
  11843. const metadata = getBinaryImageMetadata(imageData);
  11844. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11845. const bufferViewIndex = this.addBufferView(imageData);
  11846. const glTFImage = {
  11847. bufferView: bufferViewIndex,
  11848. mimeType
  11849. };
  11850. this.json.images = this.json.images || [];
  11851. this.json.images.push(glTFImage);
  11852. return this.json.images.length - 1;
  11853. }
  11854. addBufferView(buffer) {
  11855. const byteLength = buffer.byteLength;
  11856. assert$1(Number.isFinite(byteLength));
  11857. this.sourceBuffers = this.sourceBuffers || [];
  11858. this.sourceBuffers.push(buffer);
  11859. const glTFBufferView = {
  11860. buffer: 0,
  11861. byteOffset: this.byteLength,
  11862. byteLength
  11863. };
  11864. this.byteLength += padToNBytes(byteLength, 4);
  11865. this.json.bufferViews = this.json.bufferViews || [];
  11866. this.json.bufferViews.push(glTFBufferView);
  11867. return this.json.bufferViews.length - 1;
  11868. }
  11869. addAccessor(bufferViewIndex, accessor) {
  11870. const glTFAccessor = {
  11871. bufferView: bufferViewIndex,
  11872. type: getAccessorTypeFromSize(accessor.size),
  11873. componentType: accessor.componentType,
  11874. count: accessor.count,
  11875. max: accessor.max,
  11876. min: accessor.min
  11877. };
  11878. this.json.accessors = this.json.accessors || [];
  11879. this.json.accessors.push(glTFAccessor);
  11880. return this.json.accessors.length - 1;
  11881. }
  11882. addBinaryBuffer(sourceBuffer, accessor = {
  11883. size: 3
  11884. }) {
  11885. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11886. let minMax = {
  11887. min: accessor.min,
  11888. max: accessor.max
  11889. };
  11890. if (!minMax.min || !minMax.max) {
  11891. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11892. }
  11893. const accessorDefaults = {
  11894. size: accessor.size,
  11895. componentType: getComponentTypeFromArray(sourceBuffer),
  11896. count: Math.round(sourceBuffer.length / accessor.size),
  11897. min: minMax.min,
  11898. max: minMax.max
  11899. };
  11900. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11901. }
  11902. addTexture(texture) {
  11903. const {
  11904. imageIndex
  11905. } = texture;
  11906. const glTFTexture = {
  11907. source: imageIndex
  11908. };
  11909. this.json.textures = this.json.textures || [];
  11910. this.json.textures.push(glTFTexture);
  11911. return this.json.textures.length - 1;
  11912. }
  11913. addMaterial(pbrMaterialInfo) {
  11914. this.json.materials = this.json.materials || [];
  11915. this.json.materials.push(pbrMaterialInfo);
  11916. return this.json.materials.length - 1;
  11917. }
  11918. createBinaryChunk() {
  11919. var _this$json, _this$json$buffers;
  11920. this.gltf.buffers = [];
  11921. const totalByteLength = this.byteLength;
  11922. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11923. const targetArray = new Uint8Array(arrayBuffer);
  11924. let dstByteOffset = 0;
  11925. for (const sourceBuffer of this.sourceBuffers || []) {
  11926. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11927. }
  11928. 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]) {
  11929. this.json.buffers[0].byteLength = totalByteLength;
  11930. } else {
  11931. this.json.buffers = [{
  11932. byteLength: totalByteLength
  11933. }];
  11934. }
  11935. this.gltf.binary = arrayBuffer;
  11936. this.sourceBuffers = [arrayBuffer];
  11937. }
  11938. _removeStringFromArray(array, string) {
  11939. let found = true;
  11940. while (found) {
  11941. const index = array.indexOf(string);
  11942. if (index > -1) {
  11943. array.splice(index, 1);
  11944. } else {
  11945. found = false;
  11946. }
  11947. }
  11948. }
  11949. _addAttributes(attributes = {}) {
  11950. const result = {};
  11951. for (const attributeKey in attributes) {
  11952. const attributeData = attributes[attributeKey];
  11953. const attrName = this._getGltfAttributeName(attributeKey);
  11954. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11955. result[attrName] = accessor;
  11956. }
  11957. return result;
  11958. }
  11959. _addIndices(indices) {
  11960. return this.addBinaryBuffer(indices, {
  11961. size: 1
  11962. });
  11963. }
  11964. _getGltfAttributeName(attributeName) {
  11965. switch (attributeName.toLowerCase()) {
  11966. case 'position':
  11967. case 'positions':
  11968. case 'vertices':
  11969. return 'POSITION';
  11970. case 'normal':
  11971. case 'normals':
  11972. return 'NORMAL';
  11973. case 'color':
  11974. case 'colors':
  11975. return 'COLOR_0';
  11976. case 'texcoord':
  11977. case 'texcoords':
  11978. return 'TEXCOORD_0';
  11979. default:
  11980. return attributeName;
  11981. }
  11982. }
  11983. _getAccessorMinMax(buffer, size) {
  11984. const result = {
  11985. min: null,
  11986. max: null
  11987. };
  11988. if (buffer.length < size) {
  11989. return result;
  11990. }
  11991. result.min = [];
  11992. result.max = [];
  11993. const initValues = buffer.subarray(0, size);
  11994. for (const value of initValues) {
  11995. result.min.push(value);
  11996. result.max.push(value);
  11997. }
  11998. for (let index = size; index < buffer.length; index += size) {
  11999. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  12000. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  12001. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  12002. }
  12003. }
  12004. return result;
  12005. }
  12006. }
  12007. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  12008. 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';
  12009. 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';
  12010. 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]);
  12011. 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]);
  12012. const FILTERS = {
  12013. 0: '',
  12014. 1: 'meshopt_decodeFilterOct',
  12015. 2: 'meshopt_decodeFilterQuat',
  12016. 3: 'meshopt_decodeFilterExp',
  12017. NONE: '',
  12018. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  12019. QUATERNION: 'meshopt_decodeFilterQuat',
  12020. EXPONENTIAL: 'meshopt_decodeFilterExp'
  12021. };
  12022. const DECODERS = {
  12023. 0: 'meshopt_decodeVertexBuffer',
  12024. 1: 'meshopt_decodeIndexBuffer',
  12025. 2: 'meshopt_decodeIndexSequence',
  12026. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  12027. TRIANGLES: 'meshopt_decodeIndexBuffer',
  12028. INDICES: 'meshopt_decodeIndexSequence'
  12029. };
  12030. function isMeshoptSupported() {
  12031. return isWebAssemblySupported;
  12032. }
  12033. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  12034. const instance = await loadWasmInstance();
  12035. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  12036. }
  12037. let wasmPromise;
  12038. async function loadWasmInstance() {
  12039. if (!wasmPromise) {
  12040. wasmPromise = loadWasmModule();
  12041. }
  12042. return wasmPromise;
  12043. }
  12044. async function loadWasmModule() {
  12045. let wasm = wasm_base;
  12046. if (WebAssembly.validate(detector)) {
  12047. wasm = wasm_simd;
  12048. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  12049. }
  12050. const result = await WebAssembly.instantiate(unpack(wasm), {});
  12051. await result.instance.exports.__wasm_call_ctors();
  12052. return result.instance;
  12053. }
  12054. function unpack(data) {
  12055. const result = new Uint8Array(data.length);
  12056. for (let i = 0; i < data.length; ++i) {
  12057. const ch = data.charCodeAt(i);
  12058. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  12059. }
  12060. let write = 0;
  12061. for (let i = 0; i < data.length; ++i) {
  12062. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  12063. }
  12064. return result.buffer.slice(0, write);
  12065. }
  12066. function decode$5(instance, fun, target, count, size, source, filter) {
  12067. const sbrk = instance.exports.sbrk;
  12068. const count4 = count + 3 & ~3;
  12069. const tp = sbrk(count4 * size);
  12070. const sp = sbrk(source.length);
  12071. const heap = new Uint8Array(instance.exports.memory.buffer);
  12072. heap.set(source, sp);
  12073. const res = fun(tp, count, size, sp, source.length);
  12074. if (res === 0 && filter) {
  12075. filter(tp, count4, size);
  12076. }
  12077. target.set(heap.subarray(tp, tp + count * size));
  12078. sbrk(tp - sbrk(0));
  12079. if (res !== 0) {
  12080. throw new Error("Malformed buffer data: ".concat(res));
  12081. }
  12082. }
  12083. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  12084. const name$6 = EXT_MESHOPT_COMPRESSION;
  12085. function preprocess$4(gltfData) {
  12086. const scenegraph = new GLTFScenegraph(gltfData);
  12087. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  12088. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  12089. }
  12090. }
  12091. async function decode$4(gltfData, options) {
  12092. var _options$gltf;
  12093. const scenegraph = new GLTFScenegraph(gltfData);
  12094. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12095. return;
  12096. }
  12097. const promises = [];
  12098. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  12099. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  12100. }
  12101. await Promise.all(promises);
  12102. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  12103. }
  12104. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  12105. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  12106. if (meshoptExtension) {
  12107. const buffer = bufferView.buffer;
  12108. const {
  12109. byteOffset = 0,
  12110. byteLength = 0,
  12111. byteStride,
  12112. count,
  12113. mode,
  12114. filter = 'NONE'
  12115. } = meshoptExtension;
  12116. const source = new Uint8Array(buffer, byteOffset, byteLength);
  12117. const result = new ArrayBuffer(count * byteStride);
  12118. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  12119. return result;
  12120. }
  12121. return null;
  12122. }
  12123. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12124. __proto__: null,
  12125. name: name$6,
  12126. preprocess: preprocess$4,
  12127. decode: decode$4
  12128. });
  12129. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12130. const name$5 = EXT_TEXTURE_WEBP;
  12131. function preprocess$3(gltfData, options) {
  12132. const scenegraph = new GLTFScenegraph(gltfData);
  12133. if (!_isImageFormatSupported('image/webp')) {
  12134. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12135. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12136. }
  12137. return;
  12138. }
  12139. const {
  12140. json
  12141. } = scenegraph;
  12142. for (const texture of json.textures || []) {
  12143. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12144. if (extension) {
  12145. texture.source = extension.source;
  12146. }
  12147. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12148. }
  12149. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12150. }
  12151. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12152. __proto__: null,
  12153. name: name$5,
  12154. preprocess: preprocess$3
  12155. });
  12156. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12157. const name$4 = KHR_TEXTURE_BASISU;
  12158. function preprocess$2(gltfData, options) {
  12159. const scene = new GLTFScenegraph(gltfData);
  12160. const {
  12161. json
  12162. } = scene;
  12163. for (const texture of json.textures || []) {
  12164. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12165. if (extension) {
  12166. texture.source = extension.source;
  12167. }
  12168. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12169. }
  12170. scene.removeExtension(KHR_TEXTURE_BASISU);
  12171. }
  12172. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12173. __proto__: null,
  12174. name: name$4,
  12175. preprocess: preprocess$2
  12176. });
  12177. function getGLTFAccessors(attributes) {
  12178. const accessors = {};
  12179. for (const name in attributes) {
  12180. const attribute = attributes[name];
  12181. if (name !== 'indices') {
  12182. const glTFAccessor = getGLTFAccessor(attribute);
  12183. accessors[name] = glTFAccessor;
  12184. }
  12185. }
  12186. return accessors;
  12187. }
  12188. function getGLTFAccessor(attribute) {
  12189. const {
  12190. buffer,
  12191. size,
  12192. count
  12193. } = getAccessorData(attribute);
  12194. const glTFAccessor = {
  12195. value: buffer,
  12196. size,
  12197. byteOffset: 0,
  12198. count,
  12199. type: getAccessorTypeFromSize(size),
  12200. componentType: getComponentTypeFromArray(buffer)
  12201. };
  12202. return glTFAccessor;
  12203. }
  12204. function getAccessorData(attribute) {
  12205. let buffer = attribute;
  12206. let size = 1;
  12207. let count = 0;
  12208. if (attribute && attribute.value) {
  12209. buffer = attribute.value;
  12210. size = attribute.size || 1;
  12211. }
  12212. if (buffer) {
  12213. if (!ArrayBuffer.isView(buffer)) {
  12214. buffer = toTypedArray(buffer, Float32Array);
  12215. }
  12216. count = buffer.length / size;
  12217. }
  12218. return {
  12219. buffer,
  12220. size,
  12221. count
  12222. };
  12223. }
  12224. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12225. if (!array) {
  12226. return null;
  12227. }
  12228. if (Array.isArray(array)) {
  12229. return new ArrayType(array);
  12230. }
  12231. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12232. return new ArrayType(array);
  12233. }
  12234. return array;
  12235. }
  12236. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12237. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12238. function preprocess$1(gltfData, options, context) {
  12239. const scenegraph = new GLTFScenegraph(gltfData);
  12240. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12241. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12242. }
  12243. }
  12244. async function decode$3(gltfData, options, context) {
  12245. var _options$gltf;
  12246. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12247. return;
  12248. }
  12249. const scenegraph = new GLTFScenegraph(gltfData);
  12250. const promises = [];
  12251. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12252. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12253. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12254. }
  12255. }
  12256. await Promise.all(promises);
  12257. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12258. }
  12259. function encode$3(gltfData, options = {}) {
  12260. const scenegraph = new GLTFScenegraph(gltfData);
  12261. for (const mesh of scenegraph.json.meshes || []) {
  12262. compressMesh(mesh);
  12263. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12264. }
  12265. }
  12266. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12267. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12268. if (!dracoExtension) {
  12269. return;
  12270. }
  12271. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12272. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12273. const {
  12274. parse
  12275. } = context;
  12276. const dracoOptions = { ...options
  12277. };
  12278. delete dracoOptions['3d-tiles'];
  12279. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12280. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12281. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12282. if (attributeName in primitive.attributes) {
  12283. const accessorIndex = primitive.attributes[attributeName];
  12284. const accessor = scenegraph.getAccessor(accessorIndex);
  12285. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12286. decodedAttribute.min = accessor.min;
  12287. decodedAttribute.max = accessor.max;
  12288. }
  12289. }
  12290. }
  12291. primitive.attributes = decodedAttributes;
  12292. if (decodedData.indices) {
  12293. primitive.indices = getGLTFAccessor(decodedData.indices);
  12294. }
  12295. checkPrimitive(primitive);
  12296. }
  12297. function compressMesh(attributes, indices, mode = 4, options, context) {
  12298. var _context$parseSync;
  12299. if (!options.DracoWriter) {
  12300. throw new Error('options.gltf.DracoWriter not provided');
  12301. }
  12302. const compressedData = options.DracoWriter.encodeSync({
  12303. attributes
  12304. });
  12305. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12306. attributes
  12307. });
  12308. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12309. const bufferViewIndex = options.addBufferView(compressedData);
  12310. const glTFMesh = {
  12311. primitives: [{
  12312. attributes: fauxAccessors,
  12313. mode,
  12314. extensions: {
  12315. [KHR_DRACO_MESH_COMPRESSION]: {
  12316. bufferView: bufferViewIndex,
  12317. attributes: fauxAccessors
  12318. }
  12319. }
  12320. }]
  12321. };
  12322. return glTFMesh;
  12323. }
  12324. function checkPrimitive(primitive) {
  12325. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12326. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12327. }
  12328. }
  12329. function* makeMeshPrimitiveIterator(scenegraph) {
  12330. for (const mesh of scenegraph.json.meshes || []) {
  12331. for (const primitive of mesh.primitives) {
  12332. yield primitive;
  12333. }
  12334. }
  12335. }
  12336. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12337. __proto__: null,
  12338. name: name$3,
  12339. preprocess: preprocess$1,
  12340. decode: decode$3,
  12341. encode: encode$3
  12342. });
  12343. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12344. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12345. async function decode$2(gltfData) {
  12346. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12347. const {
  12348. json
  12349. } = gltfScenegraph;
  12350. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12351. if (extension) {
  12352. gltfScenegraph.json.lights = extension.lights;
  12353. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12354. }
  12355. for (const node of json.nodes || []) {
  12356. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12357. if (nodeExtension) {
  12358. node.light = nodeExtension.light;
  12359. }
  12360. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12361. }
  12362. }
  12363. async function encode$2(gltfData) {
  12364. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12365. const {
  12366. json
  12367. } = gltfScenegraph;
  12368. if (json.lights) {
  12369. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12370. assert$1(!extension.lights);
  12371. extension.lights = json.lights;
  12372. delete json.lights;
  12373. }
  12374. if (gltfScenegraph.json.lights) {
  12375. for (const light of gltfScenegraph.json.lights) {
  12376. const node = light.node;
  12377. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12378. }
  12379. delete gltfScenegraph.json.lights;
  12380. }
  12381. }
  12382. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12383. __proto__: null,
  12384. name: name$2,
  12385. decode: decode$2,
  12386. encode: encode$2
  12387. });
  12388. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12389. const name$1 = KHR_MATERIALS_UNLIT;
  12390. async function decode$1(gltfData) {
  12391. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12392. const {
  12393. json
  12394. } = gltfScenegraph;
  12395. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12396. for (const material of json.materials || []) {
  12397. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12398. if (extension) {
  12399. material.unlit = true;
  12400. }
  12401. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12402. }
  12403. }
  12404. function encode$1(gltfData) {
  12405. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12406. const {
  12407. json
  12408. } = gltfScenegraph;
  12409. if (gltfScenegraph.materials) {
  12410. for (const material of json.materials || []) {
  12411. if (material.unlit) {
  12412. delete material.unlit;
  12413. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12414. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12415. }
  12416. }
  12417. }
  12418. }
  12419. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12420. __proto__: null,
  12421. name: name$1,
  12422. decode: decode$1,
  12423. encode: encode$1
  12424. });
  12425. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12426. const name = KHR_TECHNIQUES_WEBGL;
  12427. async function decode(gltfData) {
  12428. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12429. const {
  12430. json
  12431. } = gltfScenegraph;
  12432. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12433. if (extension) {
  12434. const techniques = resolveTechniques(extension, gltfScenegraph);
  12435. for (const material of json.materials || []) {
  12436. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12437. if (materialExtension) {
  12438. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12439. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12440. }
  12441. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12442. }
  12443. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12444. }
  12445. }
  12446. async function encode(gltfData, options) {}
  12447. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12448. const {
  12449. programs = [],
  12450. shaders = [],
  12451. techniques = []
  12452. } = techniquesExtension;
  12453. const textDecoder = new TextDecoder();
  12454. shaders.forEach(shader => {
  12455. if (Number.isFinite(shader.bufferView)) {
  12456. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12457. } else {
  12458. throw new Error('KHR_techniques_webgl: no shader code');
  12459. }
  12460. });
  12461. programs.forEach(program => {
  12462. program.fragmentShader = shaders[program.fragmentShader];
  12463. program.vertexShader = shaders[program.vertexShader];
  12464. });
  12465. techniques.forEach(technique => {
  12466. technique.program = programs[technique.program];
  12467. });
  12468. return techniques;
  12469. }
  12470. function resolveValues(technique, gltfScenegraph) {
  12471. const values = Object.assign({}, technique.values);
  12472. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12473. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12474. values[uniform] = technique.uniforms[uniform].value;
  12475. }
  12476. });
  12477. Object.keys(values).forEach(uniform => {
  12478. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12479. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12480. }
  12481. });
  12482. return values;
  12483. }
  12484. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12485. __proto__: null,
  12486. name: name,
  12487. decode: decode,
  12488. encode: encode
  12489. });
  12490. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12491. function preprocessExtensions(gltf, options = {}, context) {
  12492. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12493. for (const extension of extensions) {
  12494. var _extension$preprocess;
  12495. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12496. }
  12497. }
  12498. async function decodeExtensions(gltf, options = {}, context) {
  12499. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12500. for (const extension of extensions) {
  12501. var _extension$decode;
  12502. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12503. }
  12504. }
  12505. function useExtension(extensionName, options) {
  12506. var _options$gltf;
  12507. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12508. const exclude = extensionName in excludes && !excludes[extensionName];
  12509. return !exclude;
  12510. }
  12511. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12512. function preprocess(gltfData) {
  12513. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12514. const {
  12515. json
  12516. } = gltfScenegraph;
  12517. for (const image of json.images || []) {
  12518. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12519. if (extension) {
  12520. Object.assign(image, extension);
  12521. }
  12522. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12523. }
  12524. if (json.buffers && json.buffers[0]) {
  12525. delete json.buffers[0].uri;
  12526. }
  12527. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12528. }
  12529. const GLTF_ARRAYS = {
  12530. accessors: 'accessor',
  12531. animations: 'animation',
  12532. buffers: 'buffer',
  12533. bufferViews: 'bufferView',
  12534. images: 'image',
  12535. materials: 'material',
  12536. meshes: 'mesh',
  12537. nodes: 'node',
  12538. samplers: 'sampler',
  12539. scenes: 'scene',
  12540. skins: 'skin',
  12541. textures: 'texture'
  12542. };
  12543. const GLTF_KEYS = {
  12544. accessor: 'accessors',
  12545. animations: 'animation',
  12546. buffer: 'buffers',
  12547. bufferView: 'bufferViews',
  12548. image: 'images',
  12549. material: 'materials',
  12550. mesh: 'meshes',
  12551. node: 'nodes',
  12552. sampler: 'samplers',
  12553. scene: 'scenes',
  12554. skin: 'skins',
  12555. texture: 'textures'
  12556. };
  12557. class GLTFV1Normalizer {
  12558. constructor() {
  12559. _defineProperty(this, "idToIndexMap", {
  12560. animations: {},
  12561. accessors: {},
  12562. buffers: {},
  12563. bufferViews: {},
  12564. images: {},
  12565. materials: {},
  12566. meshes: {},
  12567. nodes: {},
  12568. samplers: {},
  12569. scenes: {},
  12570. skins: {},
  12571. textures: {}
  12572. });
  12573. _defineProperty(this, "json", void 0);
  12574. }
  12575. normalize(gltf, options) {
  12576. this.json = gltf.json;
  12577. const json = gltf.json;
  12578. switch (json.asset && json.asset.version) {
  12579. case '2.0':
  12580. return;
  12581. case undefined:
  12582. case '1.0':
  12583. break;
  12584. default:
  12585. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12586. return;
  12587. }
  12588. if (!options.normalize) {
  12589. throw new Error('glTF v1 is not supported.');
  12590. }
  12591. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12592. this._addAsset(json);
  12593. this._convertTopLevelObjectsToArrays(json);
  12594. preprocess(gltf);
  12595. this._convertObjectIdsToArrayIndices(json);
  12596. this._updateObjects(json);
  12597. this._updateMaterial(json);
  12598. }
  12599. _addAsset(json) {
  12600. json.asset = json.asset || {};
  12601. json.asset.version = '2.0';
  12602. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12603. }
  12604. _convertTopLevelObjectsToArrays(json) {
  12605. for (const arrayName in GLTF_ARRAYS) {
  12606. this._convertTopLevelObjectToArray(json, arrayName);
  12607. }
  12608. }
  12609. _convertTopLevelObjectToArray(json, mapName) {
  12610. const objectMap = json[mapName];
  12611. if (!objectMap || Array.isArray(objectMap)) {
  12612. return;
  12613. }
  12614. json[mapName] = [];
  12615. for (const id in objectMap) {
  12616. const object = objectMap[id];
  12617. object.id = object.id || id;
  12618. const index = json[mapName].length;
  12619. json[mapName].push(object);
  12620. this.idToIndexMap[mapName][id] = index;
  12621. }
  12622. }
  12623. _convertObjectIdsToArrayIndices(json) {
  12624. for (const arrayName in GLTF_ARRAYS) {
  12625. this._convertIdsToIndices(json, arrayName);
  12626. }
  12627. if ('scene' in json) {
  12628. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12629. }
  12630. for (const texture of json.textures) {
  12631. this._convertTextureIds(texture);
  12632. }
  12633. for (const mesh of json.meshes) {
  12634. this._convertMeshIds(mesh);
  12635. }
  12636. for (const node of json.nodes) {
  12637. this._convertNodeIds(node);
  12638. }
  12639. for (const node of json.scenes) {
  12640. this._convertSceneIds(node);
  12641. }
  12642. }
  12643. _convertTextureIds(texture) {
  12644. if (texture.source) {
  12645. texture.source = this._convertIdToIndex(texture.source, 'image');
  12646. }
  12647. }
  12648. _convertMeshIds(mesh) {
  12649. for (const primitive of mesh.primitives) {
  12650. const {
  12651. attributes,
  12652. indices,
  12653. material
  12654. } = primitive;
  12655. for (const attributeName in attributes) {
  12656. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12657. }
  12658. if (indices) {
  12659. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12660. }
  12661. if (material) {
  12662. primitive.material = this._convertIdToIndex(material, 'material');
  12663. }
  12664. }
  12665. }
  12666. _convertNodeIds(node) {
  12667. if (node.children) {
  12668. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12669. }
  12670. if (node.meshes) {
  12671. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12672. }
  12673. }
  12674. _convertSceneIds(scene) {
  12675. if (scene.nodes) {
  12676. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12677. }
  12678. }
  12679. _convertIdsToIndices(json, topLevelArrayName) {
  12680. if (!json[topLevelArrayName]) {
  12681. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12682. json[topLevelArrayName] = [];
  12683. }
  12684. for (const object of json[topLevelArrayName]) {
  12685. for (const key in object) {
  12686. const id = object[key];
  12687. const index = this._convertIdToIndex(id, key);
  12688. object[key] = index;
  12689. }
  12690. }
  12691. }
  12692. _convertIdToIndex(id, key) {
  12693. const arrayName = GLTF_KEYS[key];
  12694. if (arrayName in this.idToIndexMap) {
  12695. const index = this.idToIndexMap[arrayName][id];
  12696. if (!Number.isFinite(index)) {
  12697. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12698. }
  12699. return index;
  12700. }
  12701. return id;
  12702. }
  12703. _updateObjects(json) {
  12704. for (const buffer of this.json.buffers) {
  12705. delete buffer.type;
  12706. }
  12707. }
  12708. _updateMaterial(json) {
  12709. for (const material of json.materials) {
  12710. material.pbrMetallicRoughness = {
  12711. baseColorFactor: [1, 1, 1, 1],
  12712. metallicFactor: 1,
  12713. roughnessFactor: 1
  12714. };
  12715. const textureId = material.values && material.values.tex;
  12716. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12717. if (textureIndex !== -1) {
  12718. material.pbrMetallicRoughness.baseColorTexture = {
  12719. index: textureIndex
  12720. };
  12721. }
  12722. }
  12723. }
  12724. }
  12725. function normalizeGLTFV1(gltf, options = {}) {
  12726. return new GLTFV1Normalizer().normalize(gltf, options);
  12727. }
  12728. const COMPONENTS = {
  12729. SCALAR: 1,
  12730. VEC2: 2,
  12731. VEC3: 3,
  12732. VEC4: 4,
  12733. MAT2: 4,
  12734. MAT3: 9,
  12735. MAT4: 16
  12736. };
  12737. const BYTES = {
  12738. 5120: 1,
  12739. 5121: 1,
  12740. 5122: 2,
  12741. 5123: 2,
  12742. 5125: 4,
  12743. 5126: 4
  12744. };
  12745. const GL_SAMPLER = {
  12746. TEXTURE_MAG_FILTER: 0x2800,
  12747. TEXTURE_MIN_FILTER: 0x2801,
  12748. TEXTURE_WRAP_S: 0x2802,
  12749. TEXTURE_WRAP_T: 0x2803,
  12750. REPEAT: 0x2901,
  12751. LINEAR: 0x2601,
  12752. NEAREST_MIPMAP_LINEAR: 0x2702
  12753. };
  12754. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12755. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12756. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12757. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12758. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12759. };
  12760. const DEFAULT_SAMPLER = {
  12761. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12762. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12763. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12764. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12765. };
  12766. function getBytesFromComponentType(componentType) {
  12767. return BYTES[componentType];
  12768. }
  12769. function getSizeFromAccessorType(type) {
  12770. return COMPONENTS[type];
  12771. }
  12772. class GLTFPostProcessor {
  12773. constructor() {
  12774. _defineProperty(this, "baseUri", '');
  12775. _defineProperty(this, "json", {});
  12776. _defineProperty(this, "buffers", []);
  12777. _defineProperty(this, "images", []);
  12778. }
  12779. postProcess(gltf, options = {}) {
  12780. const {
  12781. json,
  12782. buffers = [],
  12783. images = [],
  12784. baseUri = ''
  12785. } = gltf;
  12786. assert$1(json);
  12787. this.baseUri = baseUri;
  12788. this.json = json;
  12789. this.buffers = buffers;
  12790. this.images = images;
  12791. this._resolveTree(this.json, options);
  12792. return this.json;
  12793. }
  12794. _resolveTree(json, options = {}) {
  12795. if (json.bufferViews) {
  12796. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12797. }
  12798. if (json.images) {
  12799. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12800. }
  12801. if (json.samplers) {
  12802. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12803. }
  12804. if (json.textures) {
  12805. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12806. }
  12807. if (json.accessors) {
  12808. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12809. }
  12810. if (json.materials) {
  12811. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12812. }
  12813. if (json.meshes) {
  12814. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12815. }
  12816. if (json.nodes) {
  12817. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12818. }
  12819. if (json.skins) {
  12820. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12821. }
  12822. if (json.scenes) {
  12823. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12824. }
  12825. if (json.scene !== undefined) {
  12826. json.scene = json.scenes[this.json.scene];
  12827. }
  12828. }
  12829. getScene(index) {
  12830. return this._get('scenes', index);
  12831. }
  12832. getNode(index) {
  12833. return this._get('nodes', index);
  12834. }
  12835. getSkin(index) {
  12836. return this._get('skins', index);
  12837. }
  12838. getMesh(index) {
  12839. return this._get('meshes', index);
  12840. }
  12841. getMaterial(index) {
  12842. return this._get('materials', index);
  12843. }
  12844. getAccessor(index) {
  12845. return this._get('accessors', index);
  12846. }
  12847. getCamera(index) {
  12848. return null;
  12849. }
  12850. getTexture(index) {
  12851. return this._get('textures', index);
  12852. }
  12853. getSampler(index) {
  12854. return this._get('samplers', index);
  12855. }
  12856. getImage(index) {
  12857. return this._get('images', index);
  12858. }
  12859. getBufferView(index) {
  12860. return this._get('bufferViews', index);
  12861. }
  12862. getBuffer(index) {
  12863. return this._get('buffers', index);
  12864. }
  12865. _get(array, index) {
  12866. if (typeof index === 'object') {
  12867. return index;
  12868. }
  12869. const object = this.json[array] && this.json[array][index];
  12870. if (!object) {
  12871. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12872. }
  12873. return object;
  12874. }
  12875. _resolveScene(scene, index) {
  12876. scene.id = scene.id || "scene-".concat(index);
  12877. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12878. return scene;
  12879. }
  12880. _resolveNode(node, index) {
  12881. node.id = node.id || "node-".concat(index);
  12882. if (node.children) {
  12883. node.children = node.children.map(child => this.getNode(child));
  12884. }
  12885. if (node.mesh !== undefined) {
  12886. node.mesh = this.getMesh(node.mesh);
  12887. } else if (node.meshes !== undefined && node.meshes.length) {
  12888. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12889. const mesh = this.getMesh(meshIndex);
  12890. accum.id = mesh.id;
  12891. accum.primitives = accum.primitives.concat(mesh.primitives);
  12892. return accum;
  12893. }, {
  12894. primitives: []
  12895. });
  12896. }
  12897. if (node.camera !== undefined) {
  12898. node.camera = this.getCamera(node.camera);
  12899. }
  12900. if (node.skin !== undefined) {
  12901. node.skin = this.getSkin(node.skin);
  12902. }
  12903. return node;
  12904. }
  12905. _resolveSkin(skin, index) {
  12906. skin.id = skin.id || "skin-".concat(index);
  12907. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12908. return skin;
  12909. }
  12910. _resolveMesh(mesh, index) {
  12911. mesh.id = mesh.id || "mesh-".concat(index);
  12912. if (mesh.primitives) {
  12913. mesh.primitives = mesh.primitives.map(primitive => {
  12914. primitive = { ...primitive
  12915. };
  12916. const attributes = primitive.attributes;
  12917. primitive.attributes = {};
  12918. for (const attribute in attributes) {
  12919. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12920. }
  12921. if (primitive.indices !== undefined) {
  12922. primitive.indices = this.getAccessor(primitive.indices);
  12923. }
  12924. if (primitive.material !== undefined) {
  12925. primitive.material = this.getMaterial(primitive.material);
  12926. }
  12927. return primitive;
  12928. });
  12929. }
  12930. return mesh;
  12931. }
  12932. _resolveMaterial(material, index) {
  12933. material.id = material.id || "material-".concat(index);
  12934. if (material.normalTexture) {
  12935. material.normalTexture = { ...material.normalTexture
  12936. };
  12937. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12938. }
  12939. if (material.occlusionTexture) {
  12940. material.occlustionTexture = { ...material.occlustionTexture
  12941. };
  12942. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12943. }
  12944. if (material.emissiveTexture) {
  12945. material.emmisiveTexture = { ...material.emmisiveTexture
  12946. };
  12947. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12948. }
  12949. if (!material.emissiveFactor) {
  12950. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12951. }
  12952. if (material.pbrMetallicRoughness) {
  12953. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12954. };
  12955. const mr = material.pbrMetallicRoughness;
  12956. if (mr.baseColorTexture) {
  12957. mr.baseColorTexture = { ...mr.baseColorTexture
  12958. };
  12959. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12960. }
  12961. if (mr.metallicRoughnessTexture) {
  12962. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12963. };
  12964. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12965. }
  12966. }
  12967. return material;
  12968. }
  12969. _resolveAccessor(accessor, index) {
  12970. accessor.id = accessor.id || "accessor-".concat(index);
  12971. if (accessor.bufferView !== undefined) {
  12972. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12973. }
  12974. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12975. accessor.components = getSizeFromAccessorType(accessor.type);
  12976. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12977. if (accessor.bufferView) {
  12978. const buffer = accessor.bufferView.buffer;
  12979. const {
  12980. ArrayType,
  12981. byteLength
  12982. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12983. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12984. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12985. if (accessor.bufferView.byteStride) {
  12986. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12987. }
  12988. accessor.value = new ArrayType(cutBuffer);
  12989. }
  12990. return accessor;
  12991. }
  12992. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12993. const result = new Uint8Array(count * bytesPerElement);
  12994. for (let i = 0; i < count; i++) {
  12995. const elementOffset = byteOffset + i * byteStride;
  12996. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12997. }
  12998. return result.buffer;
  12999. }
  13000. _resolveTexture(texture, index) {
  13001. texture.id = texture.id || "texture-".concat(index);
  13002. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  13003. texture.source = this.getImage(texture.source);
  13004. return texture;
  13005. }
  13006. _resolveSampler(sampler, index) {
  13007. sampler.id = sampler.id || "sampler-".concat(index);
  13008. sampler.parameters = {};
  13009. for (const key in sampler) {
  13010. const glEnum = this._enumSamplerParameter(key);
  13011. if (glEnum !== undefined) {
  13012. sampler.parameters[glEnum] = sampler[key];
  13013. }
  13014. }
  13015. return sampler;
  13016. }
  13017. _enumSamplerParameter(key) {
  13018. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  13019. }
  13020. _resolveImage(image, index) {
  13021. image.id = image.id || "image-".concat(index);
  13022. if (image.bufferView !== undefined) {
  13023. image.bufferView = this.getBufferView(image.bufferView);
  13024. }
  13025. const preloadedImage = this.images[index];
  13026. if (preloadedImage) {
  13027. image.image = preloadedImage;
  13028. }
  13029. return image;
  13030. }
  13031. _resolveBufferView(bufferView, index) {
  13032. const bufferIndex = bufferView.buffer;
  13033. const result = {
  13034. id: "bufferView-".concat(index),
  13035. ...bufferView,
  13036. buffer: this.buffers[bufferIndex]
  13037. };
  13038. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  13039. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  13040. if ('byteOffset' in bufferView) {
  13041. byteOffset += bufferView.byteOffset;
  13042. }
  13043. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  13044. return result;
  13045. }
  13046. _resolveCamera(camera, index) {
  13047. camera.id = camera.id || "camera-".concat(index);
  13048. if (camera.perspective) ;
  13049. if (camera.orthographic) ;
  13050. return camera;
  13051. }
  13052. }
  13053. function postProcessGLTF(gltf, options) {
  13054. return new GLTFPostProcessor().postProcess(gltf, options);
  13055. }
  13056. const MAGIC_glTF = 0x676c5446;
  13057. const GLB_FILE_HEADER_SIZE = 12;
  13058. const GLB_CHUNK_HEADER_SIZE = 8;
  13059. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  13060. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  13061. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  13062. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  13063. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  13064. const LE = true;
  13065. function getMagicString(dataView, byteOffset = 0) {
  13066. 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)));
  13067. }
  13068. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  13069. const dataView = new DataView(arrayBuffer);
  13070. const {
  13071. magic = MAGIC_glTF
  13072. } = options;
  13073. const magic1 = dataView.getUint32(byteOffset, false);
  13074. return magic1 === magic || magic1 === MAGIC_glTF;
  13075. }
  13076. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  13077. const dataView = new DataView(arrayBuffer);
  13078. const type = getMagicString(dataView, byteOffset + 0);
  13079. const version = dataView.getUint32(byteOffset + 4, LE);
  13080. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  13081. Object.assign(glb, {
  13082. header: {
  13083. byteOffset,
  13084. byteLength,
  13085. hasBinChunk: false
  13086. },
  13087. type,
  13088. version,
  13089. json: {},
  13090. binChunks: []
  13091. });
  13092. byteOffset += GLB_FILE_HEADER_SIZE;
  13093. switch (glb.version) {
  13094. case 1:
  13095. return parseGLBV1(glb, dataView, byteOffset);
  13096. case 2:
  13097. return parseGLBV2(glb, dataView, byteOffset, options = {});
  13098. default:
  13099. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  13100. }
  13101. }
  13102. function parseGLBV1(glb, dataView, byteOffset) {
  13103. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13104. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  13105. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  13106. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13107. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  13108. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  13109. byteOffset += contentLength;
  13110. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13111. return byteOffset;
  13112. }
  13113. function parseGLBV2(glb, dataView, byteOffset, options) {
  13114. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13115. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13116. return byteOffset + glb.header.byteLength;
  13117. }
  13118. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13119. while (byteOffset + 8 <= glb.header.byteLength) {
  13120. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13121. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13122. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13123. switch (chunkFormat) {
  13124. case GLB_CHUNK_TYPE_JSON:
  13125. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13126. break;
  13127. case GLB_CHUNK_TYPE_BIN:
  13128. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13129. break;
  13130. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13131. if (!options.strict) {
  13132. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13133. }
  13134. break;
  13135. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13136. if (!options.strict) {
  13137. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13138. }
  13139. break;
  13140. }
  13141. byteOffset += padToNBytes(chunkLength, 4);
  13142. }
  13143. return byteOffset;
  13144. }
  13145. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13146. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13147. const textDecoder = new TextDecoder('utf8');
  13148. const jsonText = textDecoder.decode(jsonChunk);
  13149. glb.json = JSON.parse(jsonText);
  13150. return padToNBytes(chunkLength, 4);
  13151. }
  13152. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13153. glb.header.hasBinChunk = true;
  13154. glb.binChunks.push({
  13155. byteOffset,
  13156. byteLength: chunkLength,
  13157. arrayBuffer: dataView.buffer
  13158. });
  13159. return padToNBytes(chunkLength, 4);
  13160. }
  13161. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13162. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13163. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13164. normalizeGLTFV1(gltf, {
  13165. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13166. });
  13167. preprocessExtensions(gltf, options, context);
  13168. const promises = [];
  13169. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13170. await loadBuffers(gltf, options, context);
  13171. }
  13172. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13173. const promise = loadImages(gltf, options, context);
  13174. promises.push(promise);
  13175. }
  13176. const promise = decodeExtensions(gltf, options, context);
  13177. promises.push(promise);
  13178. await Promise.all(promises);
  13179. gltf.json.gltfArrayBuffer = arrayBufferOrString // !zeg add 兼容gltf
  13180. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13181. }
  13182. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13183. if (options.uri) {
  13184. gltf.baseUri = options.uri;
  13185. }
  13186. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13187. const textDecoder = new TextDecoder();
  13188. data = textDecoder.decode(data);
  13189. }
  13190. if (typeof data === 'string') {
  13191. gltf.json = parseJSON(data);
  13192. } else if (data instanceof ArrayBuffer) {
  13193. const glb = {};
  13194. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13195. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13196. gltf._glb = glb;
  13197. gltf.json = glb.json;
  13198. } else {
  13199. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13200. }
  13201. const buffers = gltf.json.buffers || [];
  13202. gltf.buffers = new Array(buffers.length).fill(null);
  13203. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13204. const {
  13205. binChunks
  13206. } = gltf._glb;
  13207. gltf.buffers[0] = {
  13208. arrayBuffer: binChunks[0].arrayBuffer,
  13209. byteOffset: binChunks[0].byteOffset,
  13210. byteLength: binChunks[0].byteLength
  13211. };
  13212. }
  13213. const images = gltf.json.images || [];
  13214. gltf.images = new Array(images.length).fill({});
  13215. }
  13216. async function loadBuffers(gltf, options, context) {
  13217. const buffers = gltf.json.buffers || [];
  13218. for (let i = 0; i < buffers.length; ++i) {
  13219. const buffer = buffers[i];
  13220. if (buffer.uri) {
  13221. var _context$fetch, _response$arrayBuffer;
  13222. const {
  13223. fetch
  13224. } = context;
  13225. assert$1(fetch);
  13226. const uri = resolveUrl(buffer.uri, options);
  13227. 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));
  13228. 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));
  13229. gltf.buffers[i] = {
  13230. arrayBuffer,
  13231. byteOffset: 0,
  13232. byteLength: arrayBuffer.byteLength
  13233. };
  13234. delete buffer.uri;
  13235. }
  13236. }
  13237. }
  13238. async function loadImages(gltf, options, context) {
  13239. const imageIndices = getReferencesImageIndices(gltf);
  13240. const images = gltf.json.images || [];
  13241. const promises = [];
  13242. for (const imageIndex of imageIndices) {
  13243. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13244. }
  13245. return await Promise.all(promises);
  13246. }
  13247. function getReferencesImageIndices(gltf) {
  13248. const imageIndices = new Set();
  13249. const textures = gltf.json.textures || [];
  13250. for (const texture of textures) {
  13251. if (texture.source !== undefined) {
  13252. imageIndices.add(texture.source);
  13253. }
  13254. }
  13255. return Array.from(imageIndices).sort();
  13256. }
  13257. async function loadImage(gltf, image, index, options, context) {
  13258. const {
  13259. fetch,
  13260. parse
  13261. } = context;
  13262. let arrayBuffer;
  13263. if (image.uri) {
  13264. const uri = resolveUrl(image.uri, options);
  13265. const response = await fetch(uri);
  13266. arrayBuffer = await response.arrayBuffer();
  13267. }
  13268. if (Number.isFinite(image.bufferView)) {
  13269. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13270. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13271. }
  13272. assert$1(arrayBuffer, 'glTF image has no data');
  13273. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13274. mimeType: image.mimeType,
  13275. basis: options.basis || {
  13276. format: selectSupportedBasisFormat()
  13277. }
  13278. }, context);
  13279. if (parsedImage && parsedImage[0]) {
  13280. parsedImage = {
  13281. compressed: true,
  13282. mipmaps: false,
  13283. width: parsedImage[0].width,
  13284. height: parsedImage[0].height,
  13285. data: parsedImage
  13286. };
  13287. }
  13288. gltf.images = gltf.images || [];
  13289. gltf.images[index] = parsedImage;
  13290. }
  13291. const GLTFLoader = {
  13292. name: 'glTF',
  13293. id: 'gltf',
  13294. module: 'gltf',
  13295. version: VERSION$3,
  13296. extensions: ['gltf', 'glb'],
  13297. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13298. text: true,
  13299. binary: true,
  13300. tests: ['glTF'],
  13301. parse: parse$1,
  13302. options: {
  13303. gltf: {
  13304. normalize: true,
  13305. loadBuffers: true,
  13306. loadImages: true,
  13307. decompressMeshes: true,
  13308. postProcess: true
  13309. },
  13310. log: console
  13311. },
  13312. deprecatedOptions: {
  13313. fetchImages: 'gltf.loadImages',
  13314. createImages: 'gltf.loadImages',
  13315. decompress: 'gltf.decompressMeshes',
  13316. postProcess: 'gltf.postProcess',
  13317. gltf: {
  13318. decompress: 'gltf.decompressMeshes'
  13319. }
  13320. }
  13321. };
  13322. async function parse$1(arrayBuffer, options = {}, context) {
  13323. options = { ...GLTFLoader.options,
  13324. ...options
  13325. };
  13326. options.gltf = { ...GLTFLoader.options.gltf,
  13327. ...options.gltf
  13328. };
  13329. const {
  13330. byteOffset = 0
  13331. } = options;
  13332. const gltf = {};
  13333. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13334. }
  13335. const GLTF_FORMAT = {
  13336. URI: 0,
  13337. EMBEDDED: 1
  13338. };
  13339. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13340. tile.rotateYtoZ = true;
  13341. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13342. if (gltfByteLength === 0) {
  13343. throw new Error('glTF byte length must be greater than 0.');
  13344. }
  13345. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13346. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13347. tile.gltfByteOffset = 0;
  13348. tile.gltfByteLength = gltfByteLength;
  13349. if (byteOffset % 4 === 0) ; else {
  13350. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13351. }
  13352. return tile.byteOffset + tile.byteLength;
  13353. }
  13354. async function extractGLTF(tile, gltfFormat, options, context) {
  13355. const tile3DOptions = options['3d-tiles'] || {};
  13356. extractGLTFBufferOrURL(tile, gltfFormat);
  13357. if (tile3DOptions.loadGLTF) {
  13358. const {
  13359. parse,
  13360. fetch
  13361. } = context;
  13362. if (tile.gltfUrl) {
  13363. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13364. tile.gltfByteOffset = 0;
  13365. }
  13366. if (tile.gltfArrayBuffer) {
  13367. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13368. delete tile.gltfArrayBuffer;
  13369. delete tile.gltfByteOffset;
  13370. delete tile.gltfByteLength;
  13371. }
  13372. }
  13373. }
  13374. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13375. switch (gltfFormat) {
  13376. case GLTF_FORMAT.URI:
  13377. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13378. const textDecoder = new TextDecoder();
  13379. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13380. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13381. delete tile.gltfArrayBuffer;
  13382. delete tile.gltfByteOffset;
  13383. delete tile.gltfByteLength;
  13384. break;
  13385. case GLTF_FORMAT.EMBEDDED:
  13386. break;
  13387. default:
  13388. throw new Error('b3dm: Illegal glTF format field');
  13389. }
  13390. }
  13391. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13392. var _tile$gltf;
  13393. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13394. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13395. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13396. if (extensions && extensions.CESIUM_RTC) {
  13397. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13398. }
  13399. return byteOffset;
  13400. }
  13401. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13402. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13403. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13404. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13405. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13406. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13407. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13408. return byteOffset;
  13409. }
  13410. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13411. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13412. await extractGLTF(tile, tile.gltfFormat, options, context);
  13413. return byteOffset;
  13414. }
  13415. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13416. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13417. if (tile.version !== 1) {
  13418. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13419. }
  13420. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13421. const view = new DataView(arrayBuffer);
  13422. tile.gltfFormat = view.getUint32(byteOffset, true);
  13423. byteOffset += 4;
  13424. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13425. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13426. if (tile.featureTableJsonByteLength === 0) {
  13427. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13428. }
  13429. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13430. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13431. featureTable.featuresLength = instancesLength;
  13432. if (!Number.isFinite(instancesLength)) {
  13433. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13434. }
  13435. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13436. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13437. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13438. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13439. return byteOffset;
  13440. }
  13441. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13442. const collectionOptions = {
  13443. instances: new Array(instancesLength),
  13444. batchTable: tile._batchTable,
  13445. cull: false,
  13446. url: undefined,
  13447. gltf: undefined,
  13448. basePath: undefined,
  13449. incrementallyLoadTextures: false,
  13450. forwardAxis: [1, 0, 0]
  13451. };
  13452. const instances = collectionOptions.instances;
  13453. const instancePosition = new Vector3();
  13454. new Vector3();
  13455. new Vector3();
  13456. new Vector3();
  13457. const instanceRotation = new Matrix3();
  13458. const instanceQuaternion = new Quaternion();
  13459. const instanceScale = new Vector3();
  13460. const instanceTranslationRotationScale = {};
  13461. const instanceTransform = new Matrix4();
  13462. const scratch1 = [];
  13463. const scratch2 = [];
  13464. const scratchVector1 = new Vector3();
  13465. const scratchVector2 = new Vector3();
  13466. for (let i = 0; i < instancesLength; i++) {
  13467. let position;
  13468. if (featureTable.hasProperty('POSITION')) {
  13469. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13470. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13471. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13472. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13473. if (!quantizedVolumeOffset) {
  13474. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13475. }
  13476. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13477. if (!quantizedVolumeScale) {
  13478. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13479. }
  13480. const MAX_UNSIGNED_SHORT = 65535.0;
  13481. for (let j = 0; j < 3; j++) {
  13482. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13483. }
  13484. }
  13485. if (!position) {
  13486. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13487. }
  13488. instancePosition.copy(position);
  13489. instanceTranslationRotationScale.translation = instancePosition;
  13490. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13491. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13492. if (tile.normalUp) {
  13493. if (!tile.normalRight) {
  13494. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13495. }
  13496. tile.hasCustomOrientation = true;
  13497. } else {
  13498. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13499. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13500. if (tile.octNormalUp) {
  13501. if (!tile.octNormalRight) {
  13502. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13503. }
  13504. throw new Error('i3dm: oct-encoded orientation not implemented');
  13505. } else if (tile.eastNorthUp) {
  13506. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13507. instanceTransform.getRotationMatrix3(instanceRotation);
  13508. } else {
  13509. instanceRotation.identity();
  13510. }
  13511. }
  13512. instanceQuaternion.fromMatrix3(instanceRotation);
  13513. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13514. instanceScale.set(1.0, 1.0, 1.0);
  13515. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13516. if (Number.isFinite(scale)) {
  13517. instanceScale.multiplyByScalar(scale);
  13518. }
  13519. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13520. if (nonUniformScale) {
  13521. instanceScale.scale(nonUniformScale);
  13522. }
  13523. instanceTranslationRotationScale.scale = instanceScale;
  13524. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13525. if (batchId === undefined) {
  13526. batchId = i;
  13527. }
  13528. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13529. instanceTransform.identity();
  13530. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13531. instanceTransform.multiplyRight(rotationMatrix);
  13532. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13533. const modelMatrix = instanceTransform.clone();
  13534. instances[i] = {
  13535. modelMatrix,
  13536. batchId
  13537. };
  13538. }
  13539. tile.instances = instances;
  13540. }
  13541. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13542. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13543. const view = new DataView(arrayBuffer);
  13544. tile.tilesLength = view.getUint32(byteOffset, true);
  13545. byteOffset += 4;
  13546. tile.tiles = [];
  13547. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13548. const subtile = {};
  13549. tile.tiles.push(subtile);
  13550. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13551. }
  13552. return byteOffset;
  13553. }
  13554. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13555. tile.rotateYtoZ = true;
  13556. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13557. const {
  13558. parse
  13559. } = context;
  13560. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13561. }
  13562. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13563. tile.byteOffset = byteOffset;
  13564. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13565. switch (tile.type) {
  13566. case TILE3D_TYPE.COMPOSITE:
  13567. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13568. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13569. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13570. case TILE3D_TYPE.GLTF:
  13571. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13572. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13573. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13574. case TILE3D_TYPE.POINT_CLOUD:
  13575. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13576. default:
  13577. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13578. }
  13579. }
  13580. const SUBTREE_FILE_MAGIC = 0x74627573;
  13581. const SUBTREE_FILE_VERSION = 1;
  13582. async function parse3DTilesSubtree(data) {
  13583. const magic = new Uint32Array(data.slice(0, 4));
  13584. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13585. throw new Error('Wrong subtree file magic number');
  13586. }
  13587. const version = new Uint32Array(data.slice(4, 8));
  13588. if (version[0] !== SUBTREE_FILE_VERSION) {
  13589. throw new Error('Wrong subtree file verson, must be 1');
  13590. }
  13591. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13592. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13593. const textDecoder = new TextDecoder('utf8');
  13594. const string = textDecoder.decode(stringAttribute);
  13595. const subtree = JSON.parse(string);
  13596. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13597. let internalBinaryBuffer = new ArrayBuffer(0);
  13598. if (binaryByteLength) {
  13599. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13600. }
  13601. if ('bufferView' in subtree.tileAvailability) {
  13602. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13603. }
  13604. if ('bufferView' in subtree.contentAvailability) {
  13605. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13606. }
  13607. if ('bufferView' in subtree.childSubtreeAvailability) {
  13608. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13609. }
  13610. return subtree;
  13611. }
  13612. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13613. const bufferViewIndex = subtree[name].bufferView;
  13614. const bufferView = subtree.bufferViews[bufferViewIndex];
  13615. const buffer = subtree.buffers[bufferView.buffer];
  13616. if (buffer.uri) {
  13617. const response = await fetchFile(buffer.uri);
  13618. const data = await response.arrayBuffer();
  13619. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13620. }
  13621. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13622. }
  13623. function parseUint64Value(buffer) {
  13624. const dataView = new DataView(buffer);
  13625. const left = dataView.getUint32(0, true);
  13626. const right = dataView.getUint32(4, true);
  13627. return left + 2 ** 32 * right;
  13628. }
  13629. const Tile3DSubtreeLoader = {
  13630. id: '3d-tiles-subtree',
  13631. name: '3D Tiles Subtree',
  13632. module: '3d-tiles',
  13633. version: VERSION$5,
  13634. extensions: ['subtree'],
  13635. mimeTypes: ['application/octet-stream'],
  13636. tests: ['subtree'],
  13637. parse: parse3DTilesSubtree,
  13638. options: {}
  13639. };
  13640. const QUADTREE_DEVISION_COUNT = 4;
  13641. const OCTREE_DEVISION_COUNT = 8;
  13642. const SUBDIVISION_COUNT_MAP = {
  13643. QUADTREE: QUADTREE_DEVISION_COUNT,
  13644. OCTREE: OCTREE_DEVISION_COUNT
  13645. };
  13646. async function parseImplicitTiles(subtree, options, parentData = {
  13647. mortonIndex: 0,
  13648. x: 0,
  13649. y: 0,
  13650. z: 0
  13651. }, childIndex = 0, level = 0, globalData = {
  13652. level: 0,
  13653. mortonIndex: 0,
  13654. x: 0,
  13655. y: 0,
  13656. z: 0
  13657. }) {
  13658. const {
  13659. subdivisionScheme,
  13660. subtreeLevels,
  13661. maximumLevel,
  13662. contentUrlTemplate,
  13663. subtreesUriTemplate,
  13664. basePath
  13665. } = options;
  13666. const tile = {
  13667. children: [],
  13668. lodMetricValue: 0,
  13669. contentUrl: ''
  13670. };
  13671. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13672. const childX = childIndex & 0b01;
  13673. const childY = childIndex >> 1 & 0b01;
  13674. const childZ = childIndex >> 2 & 0b01;
  13675. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13676. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13677. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13678. let childTileX = concatBits(parentData.x, childX);
  13679. let childTileY = concatBits(parentData.y, childY);
  13680. let childTileZ = concatBits(parentData.z, childZ);
  13681. let isChildSubtreeAvailable = false;
  13682. if (level + 1 > subtreeLevels) {
  13683. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13684. }
  13685. const x = concatBits(globalData.x, childTileX);
  13686. const y = concatBits(globalData.y, childTileY);
  13687. const z = concatBits(globalData.z, childTileZ);
  13688. const lev = level + globalData.level;
  13689. if (isChildSubtreeAvailable) {
  13690. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13691. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13692. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13693. subtree = childSubtree;
  13694. globalData.mortonIndex = childTileMortonIndex;
  13695. globalData.x = childTileX;
  13696. globalData.y = childTileY;
  13697. globalData.z = childTileZ;
  13698. globalData.level = level;
  13699. childTileMortonIndex = 0;
  13700. tileAvailabilityIndex = 0;
  13701. childTileX = 0;
  13702. childTileY = 0;
  13703. childTileZ = 0;
  13704. level = 0;
  13705. }
  13706. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13707. if (!isTileAvailable || level > maximumLevel) {
  13708. return tile;
  13709. }
  13710. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13711. if (isContentAvailable) {
  13712. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13713. }
  13714. const childTileLevel = level + 1;
  13715. const pData = {
  13716. mortonIndex: childTileMortonIndex,
  13717. x: childTileX,
  13718. y: childTileY,
  13719. z: childTileZ
  13720. };
  13721. for (let index = 0; index < childrenPerTile; index++) {
  13722. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13723. if (currentTile.contentUrl || currentTile.children.length) {
  13724. const globalLevel = lev + 1;
  13725. const childCoordinates = {
  13726. childTileX,
  13727. childTileY,
  13728. childTileZ
  13729. };
  13730. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13731. tile.children.push(formattedTile);
  13732. }
  13733. }
  13734. return tile;
  13735. }
  13736. function getAvailabilityResult(availabilityData, index) {
  13737. if ('constant' in availabilityData) {
  13738. return Boolean(availabilityData.constant);
  13739. }
  13740. if (availabilityData.explicitBitstream) {
  13741. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13742. }
  13743. return false;
  13744. }
  13745. function formatTileData(tile, level, childCoordinates, options) {
  13746. const {
  13747. basePath,
  13748. refine,
  13749. getRefine,
  13750. lodMetricType,
  13751. getTileType,
  13752. rootLodMetricValue,
  13753. rootBoundingVolume
  13754. } = options;
  13755. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13756. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13757. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13758. return {
  13759. children: tile.children,
  13760. contentUrl: tile.contentUrl,
  13761. content: {
  13762. uri
  13763. },
  13764. id: tile.contentUrl,
  13765. refine: getRefine(refine),
  13766. type: getTileType(tile),
  13767. lodMetricType,
  13768. lodMetricValue,
  13769. boundingVolume
  13770. };
  13771. }
  13772. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13773. if (rootBoundingVolume.region) {
  13774. const {
  13775. childTileX,
  13776. childTileY,
  13777. childTileZ
  13778. } = childCoordinates;
  13779. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13780. const boundingVolumesCount = 2 ** level;
  13781. const sizeX = (east - west) / boundingVolumesCount;
  13782. const sizeY = (north - south) / boundingVolumesCount;
  13783. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13784. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13785. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13786. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13787. return {
  13788. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13789. };
  13790. }
  13791. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13792. return null;
  13793. }
  13794. function concatBits(first, second) {
  13795. return parseInt(first.toString(2) + second.toString(2), 2);
  13796. }
  13797. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13798. const mapUrl = generateMapUrl({
  13799. level,
  13800. x,
  13801. y,
  13802. z
  13803. });
  13804. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13805. }
  13806. function generateMapUrl(items) {
  13807. const mapUrl = {};
  13808. for (const key in items) {
  13809. mapUrl["{".concat(key, "}")] = items[key];
  13810. }
  13811. return mapUrl;
  13812. }
  13813. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13814. const byteIndex = Math.floor(availabilityIndex / 8);
  13815. const bitIndex = availabilityIndex % 8;
  13816. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13817. return bitValue === 1;
  13818. }
  13819. function getTileType(tile) {
  13820. if (!tile.contentUrl) {
  13821. return TILE_TYPE.EMPTY;
  13822. }
  13823. const contentUrl = tile.contentUrl;
  13824. const fileExtension = contentUrl.split('.').pop();
  13825. switch (fileExtension) {
  13826. case 'pnts':
  13827. return TILE_TYPE.POINTCLOUD;
  13828. case 'i3dm':
  13829. case 'b3dm':
  13830. case 'glb':
  13831. case 'gltf':
  13832. return TILE_TYPE.SCENEGRAPH;
  13833. default:
  13834. return fileExtension;
  13835. }
  13836. }
  13837. function getRefine(refine) {
  13838. switch (refine) {
  13839. case 'REPLACE':
  13840. case 'replace':
  13841. return TILE_REFINEMENT.REPLACE;
  13842. case 'ADD':
  13843. case 'add':
  13844. return TILE_REFINEMENT.ADD;
  13845. default:
  13846. return refine;
  13847. }
  13848. }
  13849. function normalizeTileData(tile, options) {
  13850. if (!tile) {
  13851. return null;
  13852. }
  13853. if (tile.content) {
  13854. const contentUri = tile.content.uri || tile.content.url;
  13855. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13856. }
  13857. tile.id = tile.contentUrl;
  13858. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13859. tile.lodMetricValue = tile.geometricError;
  13860. tile.transformMatrix = tile.transform;
  13861. tile.type = getTileType(tile);
  13862. tile.refine = getRefine(tile.refine);
  13863. return tile;
  13864. }
  13865. function normalizeTileHeaders(tileset) {
  13866. const basePath = tileset.basePath;
  13867. const root = normalizeTileData(tileset.root, tileset);
  13868. const stack = [];
  13869. stack.push(root);
  13870. while (stack.length > 0) {
  13871. const tile = stack.pop() || {};
  13872. const children = tile.children || [];
  13873. for (const childHeader of children) {
  13874. normalizeTileData(childHeader, {
  13875. basePath
  13876. });
  13877. stack.push(childHeader);
  13878. }
  13879. }
  13880. return root;
  13881. }
  13882. async function normalizeImplicitTileHeaders(tileset) {
  13883. if (!tileset.root) {
  13884. return null;
  13885. }
  13886. const basePath = tileset.basePath;
  13887. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13888. const {
  13889. subdivisionScheme,
  13890. maximumLevel,
  13891. subtreeLevels,
  13892. subtrees: {
  13893. uri: subtreesUriTemplate
  13894. }
  13895. } = implicitTilingExtension;
  13896. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13897. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13898. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13899. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13900. const refine = tileset.root.refine;
  13901. const rootLodMetricValue = tileset.root.geometricError;
  13902. const rootBoundingVolume = tileset.root.boundingVolume;
  13903. const options = {
  13904. contentUrlTemplate,
  13905. subtreesUriTemplate,
  13906. subdivisionScheme,
  13907. subtreeLevels,
  13908. maximumLevel,
  13909. refine,
  13910. basePath,
  13911. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13912. rootLodMetricValue,
  13913. rootBoundingVolume,
  13914. getTileType,
  13915. getRefine
  13916. };
  13917. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13918. }
  13919. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13920. if (!tile) {
  13921. return null;
  13922. }
  13923. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13924. tile.lodMetricValue = tile.geometricError;
  13925. tile.transformMatrix = tile.transform;
  13926. const {
  13927. children,
  13928. contentUrl
  13929. } = await parseImplicitTiles(rootSubtree, options);
  13930. if (contentUrl) {
  13931. tile.contentUrl = contentUrl;
  13932. tile.content = {
  13933. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13934. };
  13935. }
  13936. tile.refine = getRefine(tile.refine);
  13937. tile.type = getTileType(tile);
  13938. tile.children = children;
  13939. tile.id = tile.contentUrl;
  13940. return tile;
  13941. }
  13942. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13943. const Tiles3DLoader = {
  13944. id: '3d-tiles',
  13945. name: '3D Tiles',
  13946. module: '3d-tiles',
  13947. version: VERSION$5,
  13948. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13949. mimeTypes: ['application/octet-stream'],
  13950. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13951. parse,
  13952. options: {
  13953. '3d-tiles': {
  13954. loadGLTF: true,
  13955. decodeQuantizedPositions: false,
  13956. isTileset: 'auto',
  13957. assetGltfUpAxis: null
  13958. }
  13959. }
  13960. };
  13961. function getBaseUri(tileset) {
  13962. return dirname(tileset.url);
  13963. }
  13964. async function parseTile(arrayBuffer, options, context) {
  13965. const tile = {
  13966. content: {
  13967. featureIds: null
  13968. }
  13969. };
  13970. const byteOffset = 0;
  13971. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13972. return tile.content;
  13973. }
  13974. async function parseTileset(data, options, context) {
  13975. var _tilesetJson$root;
  13976. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13977. tilesetJson.loader = options.loader || Tiles3DLoader;
  13978. tilesetJson.url = context.url;
  13979. tilesetJson.basePath = getBaseUri(tilesetJson);
  13980. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13981. tilesetJson.type = TILESET_TYPE.TILES3D;
  13982. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13983. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13984. return tilesetJson;
  13985. }
  13986. async function parse(data, options, context) {
  13987. const loaderOptions = options['3d-tiles'] || {};
  13988. let isTileset;
  13989. if (loaderOptions.isTileset === 'auto') {
  13990. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13991. } else {
  13992. isTileset = loaderOptions.isTileset;
  13993. }
  13994. if (isTileset) {
  13995. data = await parseTileset(data, options, context);
  13996. } else {
  13997. data = await parseTile(data, options, context);
  13998. }
  13999. return data;
  14000. }
  14001. function hasImplicitTilingExtension(tilesetJson) {
  14002. var _tilesetJson$extensio, _tilesetJson$extensio2;
  14003. 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));
  14004. }
  14005. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  14006. async function getIonTilesetMetadata(accessToken, assetId) {
  14007. if (!assetId) {
  14008. const assets = await getIonAssets(accessToken);
  14009. for (const item of assets.items) {
  14010. if (item.type === '3DTILES') {
  14011. assetId = item.id;
  14012. }
  14013. }
  14014. }
  14015. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  14016. const {
  14017. type,
  14018. url
  14019. } = ionAssetMetadata;
  14020. assert$7(type === '3DTILES' && url);
  14021. ionAssetMetadata.headers = {
  14022. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  14023. };
  14024. return ionAssetMetadata;
  14025. }
  14026. async function getIonAssets(accessToken) {
  14027. assert$7(accessToken);
  14028. const url = CESIUM_ION_URL;
  14029. const headers = {
  14030. Authorization: "Bearer ".concat(accessToken)
  14031. };
  14032. const response = await fetchFile(url, {
  14033. fetch: {
  14034. headers
  14035. }
  14036. });
  14037. if (!response.ok) {
  14038. throw new Error(response.statusText);
  14039. }
  14040. return await response.json();
  14041. }
  14042. async function getIonAssetMetadata(accessToken, assetId) {
  14043. assert$7(accessToken, assetId);
  14044. const headers = {
  14045. Authorization: "Bearer ".concat(accessToken)
  14046. };
  14047. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  14048. let response = await fetchFile("".concat(url), {
  14049. fetch: {
  14050. headers
  14051. }
  14052. });
  14053. if (!response.ok) {
  14054. throw new Error(response.statusText);
  14055. }
  14056. let metadata = await response.json();
  14057. response = await fetchFile("".concat(url, "/endpoint"), {
  14058. fetch: {
  14059. headers
  14060. }
  14061. });
  14062. if (!response.ok) {
  14063. throw new Error(response.statusText);
  14064. }
  14065. const tilesetInfo = await response.json();
  14066. metadata = { ...metadata,
  14067. ...tilesetInfo
  14068. };
  14069. return metadata;
  14070. }
  14071. async function preload(url, options = {}) {
  14072. options = options['cesium-ion'] || {};
  14073. const {
  14074. accessToken
  14075. } = options;
  14076. let assetId = options.assetId;
  14077. if (!Number.isFinite(assetId)) {
  14078. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  14079. assetId = matched && matched[1];
  14080. }
  14081. return getIonTilesetMetadata(accessToken, assetId);
  14082. }
  14083. const CesiumIonLoader = { ...Tiles3DLoader,
  14084. id: 'cesium-ion',
  14085. name: 'Cesium Ion',
  14086. preload,
  14087. parse: async (data, options, context) => {
  14088. options = { ...options
  14089. };
  14090. options['3d-tiles'] = options['cesium-ion'];
  14091. options.loader = CesiumIonLoader;
  14092. return Tiles3DLoader.parse(data, options, context);
  14093. },
  14094. options: {
  14095. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  14096. accessToken: null
  14097. }
  14098. }
  14099. };
  14100. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  14101. function generateGradientTexture(gradient) {
  14102. const size = 64;
  14103. // create canvas
  14104. const canvas = document.createElement('canvas');
  14105. canvas.width = size;
  14106. canvas.height = size;
  14107. // get context
  14108. const context = canvas.getContext('2d');
  14109. // draw gradient
  14110. context.rect(0, 0, size, size);
  14111. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14112. for (let i = 0; i < gradient.length; i++) {
  14113. const step = gradient[i];
  14114. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14115. }
  14116. context.fillStyle = ctxGradient;
  14117. context.fill();
  14118. //let texture = new THREE.Texture(canvas);
  14119. const texture = new CanvasTexture(canvas);
  14120. texture.needsUpdate = true;
  14121. texture.minFilter = LinearFilter;
  14122. texture.wrapS = RepeatWrapping;
  14123. texture.wrapT = RepeatWrapping;
  14124. texture.repeat.set(2, 2);
  14125. // textureImage = texture.image;
  14126. return texture;
  14127. }
  14128. function getCameraFrustum(camera) {
  14129. camera.updateMatrix(); // make sure camera's local matrix is updated
  14130. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14131. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14132. const frustum = new Frustum();
  14133. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14134. return frustum;
  14135. }
  14136. function loadersPlaneToMesh(plane) {
  14137. const group = new Group();
  14138. // Create a basic rectangle geometry from math.gl plane
  14139. const planeGeometry = new PlaneGeometry(10, 5);
  14140. // Align the geometry to the plane
  14141. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14142. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14143. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14144. planeGeometry.lookAt(focalPoint);
  14145. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14146. // Edges
  14147. /*
  14148. const edges = new EdgesGeometry(planeGeometry)
  14149. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14150. //plane
  14151. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14152. const mesh = new Mesh(planeGeometry, material);
  14153. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14154. group.add(arrowHelper);
  14155. group.add(mesh);
  14156. return group;
  14157. }
  14158. function loadersBoundingBoxToMesh(tile) {
  14159. // Create a basic rectangle geometry from math.gl half-axes
  14160. const boundUntransformed = tile.type == 'empty' ? tile.boundingVolume : tile.getBoundUntransformed() //empty时没创建好,直接给boundingVolume一样
  14161. /* let redColor = 0;
  14162. if (tile.content) {
  14163. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14164. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14165. } */
  14166. let hue = 0
  14167. if(tile.content){
  14168. hue = Math.min( tile.depth / 10 , 1.0); //改
  14169. }
  14170. const boxColor = new THREE.Color().setHSL(hue, 0.9, 0.85)
  14171. //const boxColor = new Color(redColor, 1.0, 0.0);
  14172. const boxGeometry = new BoxGeometry(1, 1, 1);
  14173. const boxTransform = new Matrix4$1();
  14174. if (boundUntransformed.halfAxes) {
  14175. boxTransform.copy(getMatrix4FromHalfAxes(boundUntransformed.halfAxes));
  14176. }
  14177. else if (boundUntransformed.radius) {
  14178. boxGeometry.scale(boundUntransformed.radius * 2, boundUntransformed.radius * 2, boundUntransformed.radius * 2);
  14179. }
  14180. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundUntransformed.center)) //add
  14181. /* if(tile.type != "empty"){ //root单独处理了
  14182. boxTransform.premultiply((new Matrix4$1()).makeScale(1,1,-1))//xzw 因为mesh倒转了所以box也
  14183. }else{
  14184. console.log('empty')
  14185. } */
  14186. boxGeometry.applyMatrix4(boxTransform);
  14187. const edges = new EdgesGeometry(boxGeometry);
  14188. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14189. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14190. dispPlane.matrixAutoUpdate = false //add
  14191. let label = new Potree.TextSprite({
  14192. mat: new THREE.MeshBasicMaterial({transparent:true }), //depthTest:false会导致经常显示不出
  14193. backgroundColor: {r: 0, g: 0, b: 0, a:0.1},
  14194. textColor: {r: boxColor.r*255, g: boxColor.g*255, b: boxColor.b*255, a:0.9},
  14195. fontsize:100,
  14196. //useDepth : true ,
  14197. renderOrder : 5,
  14198. text: tile.id.split('/').pop().split('.b3dm')[0], //Tile_+094_-010.b3dm'
  14199. name:'tile'
  14200. })
  14201. label.addEventListener('mouseover',()=>{
  14202. if(label.sprite.material.opacity < 1)return
  14203. window.hoverTile = tile
  14204. console.log('hoverLabel',tile.id, tile._distanceToCamera)
  14205. })
  14206. /* let s = 0.6
  14207. label.scale.set(s,s,s) */
  14208. let s = tile.tileset.options.maximumScreenSpaceError / 400
  14209. label.scale.set(s,s,s)
  14210. dispPlane.add(label)
  14211. label.position.set(...boundUntransformed.center)
  14212. //label.position.z *= -1
  14213. /* if(tile.content.byteLength == void 0){
  14214. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14215. dispPlane.updateMatrixWorld = (a,b)=>{
  14216. oldUpdate(a,b)
  14217. }
  14218. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14219. dispPlane.updateMatrix = (a,b)=>{
  14220. oldU(a,b)
  14221. }
  14222. } */
  14223. tile.volumeBox = dispPlane
  14224. return dispPlane;
  14225. }
  14226. function getMatrix4FromHalfAxes(halfAxes) {
  14227. const m = halfAxes;
  14228. const rotateMatrix = new Matrix4$1().fromArray([
  14229. m[0] * 2,
  14230. m[1] * 2,
  14231. m[2] * 2,
  14232. 0,
  14233. m[3] * 2,
  14234. m[4] * 2,
  14235. m[5] * 2,
  14236. 0,
  14237. m[6] * 2,
  14238. m[7] * 2,
  14239. m[8] * 2,
  14240. 0,
  14241. 0,
  14242. 0,
  14243. 0,
  14244. 1,
  14245. ]);
  14246. return rotateMatrix;
  14247. }
  14248. /*
  14249. * from https://github.com/tentone/geo-three
  14250. * Tree-shaking did not work, probably due to static class methods
  14251. */
  14252. function datumsToSpherical(latitude, longitude) {
  14253. const EARTH_RADIUS = 6378137;
  14254. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14255. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14256. const x = longitude * EARTH_ORIGIN / 180.0;
  14257. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14258. y = y * EARTH_ORIGIN / 180.0;
  14259. return new Vector2$1(x, y);
  14260. }
  14261. const Gradients = {
  14262. // From chroma spectral http://gka.github.io/chroma.js/
  14263. SPECTRAL: [
  14264. [0, new Color(0.3686, 0.3098, 0.6353)],
  14265. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14266. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14267. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14268. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14269. [0.5, new Color(1.0, 1.0, 0.749)],
  14270. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14271. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14272. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14273. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14274. [1, new Color(0.6196, 0.0039, 0.2588)],
  14275. ],
  14276. PLASMA: [
  14277. [0.0, new Color(0.241, 0.015, 0.61)],
  14278. [0.1, new Color(0.387, 0.001, 0.654)],
  14279. [0.2, new Color(0.524, 0.025, 0.653)],
  14280. [0.3, new Color(0.651, 0.125, 0.596)],
  14281. [0.4, new Color(0.752, 0.227, 0.513)],
  14282. [0.5, new Color(0.837, 0.329, 0.431)],
  14283. [0.6, new Color(0.907, 0.435, 0.353)],
  14284. [0.7, new Color(0.963, 0.554, 0.272)],
  14285. [0.8, new Color(0.992, 0.681, 0.195)],
  14286. [0.9, new Color(0.987, 0.822, 0.144)],
  14287. [1.0, new Color(0.94, 0.975, 0.131)],
  14288. ],
  14289. YELLOW_GREEN: [
  14290. [0, new Color(0.1647, 0.2824, 0.3451)],
  14291. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14292. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14293. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14294. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14295. [0.5, new Color(0.137, 0.665, 0.5614)],
  14296. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14297. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14298. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14299. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14300. [1, new Color(0.9804, 0.9804, 0.4314)],
  14301. ],
  14302. VIRIDIS: [
  14303. [0.0, new Color(0.267, 0.005, 0.329)],
  14304. [0.1, new Color(0.283, 0.141, 0.458)],
  14305. [0.2, new Color(0.254, 0.265, 0.53)],
  14306. [0.3, new Color(0.207, 0.372, 0.553)],
  14307. [0.4, new Color(0.164, 0.471, 0.558)],
  14308. [0.5, new Color(0.128, 0.567, 0.551)],
  14309. [0.6, new Color(0.135, 0.659, 0.518)],
  14310. [0.7, new Color(0.267, 0.749, 0.441)],
  14311. [0.8, new Color(0.478, 0.821, 0.318)],
  14312. [0.9, new Color(0.741, 0.873, 0.15)],
  14313. [1.0, new Color(0.993, 0.906, 0.144)],
  14314. ],
  14315. INFERNO: [
  14316. [0.0, new Color(0.077, 0.042, 0.206)],
  14317. [0.1, new Color(0.225, 0.036, 0.388)],
  14318. [0.2, new Color(0.373, 0.074, 0.432)],
  14319. [0.3, new Color(0.522, 0.128, 0.42)],
  14320. [0.4, new Color(0.665, 0.182, 0.37)],
  14321. [0.5, new Color(0.797, 0.255, 0.287)],
  14322. [0.6, new Color(0.902, 0.364, 0.184)],
  14323. [0.7, new Color(0.969, 0.516, 0.063)],
  14324. [0.8, new Color(0.988, 0.683, 0.072)],
  14325. [0.9, new Color(0.961, 0.859, 0.298)],
  14326. [1.0, new Color(0.988, 0.998, 0.645)],
  14327. ],
  14328. GRAYSCALE: [
  14329. [0, new Color(0, 0, 0)],
  14330. [1, new Color(1, 1, 1)],
  14331. ],
  14332. // 16 samples of the TURBU color scheme
  14333. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14334. // original file licensed under Apache-2.0
  14335. TURBO: [
  14336. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14337. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14338. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14339. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14340. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14341. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14342. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14343. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14344. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14345. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14346. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14347. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14348. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14349. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14350. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14351. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14352. ],
  14353. RAINBOW: [
  14354. [0, new Color(0.278, 0, 0.714)],
  14355. [1 / 6, new Color(0, 0, 1)],
  14356. [2 / 6, new Color(0, 1, 1)],
  14357. [3 / 6, new Color(0, 1, 0)],
  14358. [4 / 6, new Color(1, 1, 0)],
  14359. [5 / 6, new Color(1, 0.64, 0)],
  14360. [1, new Color(1, 0, 0)],
  14361. ],
  14362. CONTOUR: [
  14363. [0.0, new Color(0, 0, 0)],
  14364. [0.03, new Color(0, 0, 0)],
  14365. [0.04, new Color(1, 1, 1)],
  14366. [1.0, new Color(1, 1, 1)],
  14367. ],
  14368. };
  14369. const PointCloudFS = `
  14370. varying vec3 vColor;
  14371. uniform float alpha;
  14372. void main() {
  14373. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14374. discard;
  14375. } else {
  14376. gl_FragColor = vec4( vColor, alpha);
  14377. }
  14378. }
  14379. `;
  14380. const PointCloudVS = `
  14381. varying vec3 vColor;
  14382. uniform sampler2D gradient;
  14383. uniform sampler2D grayscale;
  14384. attribute float intensity;
  14385. attribute float classification;
  14386. uniform vec3 rootCenter;
  14387. uniform vec3 rootNormal;
  14388. uniform vec2 elevationRange;
  14389. uniform int coloring;
  14390. uniform bool hideGround;
  14391. uniform float maxIntensity;
  14392. uniform float intensityContrast;
  14393. uniform float pointSize;
  14394. #ifdef USE_COLOR
  14395. vec3 getRGB() {
  14396. vec3 rgb = color;
  14397. return rgb;
  14398. }
  14399. #endif
  14400. vec3 getElevation(){
  14401. vec4 world = modelMatrix * vec4( position, 1.0 );
  14402. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14403. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14404. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14405. return cElevation;
  14406. }
  14407. vec3 getIntensity(){
  14408. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14409. float intmod = pow(intensity, intensityContrast);
  14410. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14411. return cIntensity;
  14412. }
  14413. vec3 getClassification(){
  14414. float classNormalized = classification / 255.0;
  14415. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14416. return cClassification;
  14417. }
  14418. vec3 getColor(){
  14419. vec3 color;
  14420. if (hideGround && classification == 2.0) {
  14421. return vec3(0.0, 0.0, 0.0);
  14422. }
  14423. if (coloring == 1) {
  14424. color = getIntensity();
  14425. }
  14426. else if (coloring == 2) {
  14427. color = getClassification();
  14428. } else if (coloring == 3) {
  14429. color = getElevation();
  14430. }
  14431. #ifdef USE_COLOR
  14432. else if (coloring == 4) {
  14433. color = getRGB();
  14434. }
  14435. #endif
  14436. else {
  14437. color = vec3(1.0, 1.0, 1.0);
  14438. }
  14439. return color;
  14440. }
  14441. void main() {
  14442. vColor = getColor();
  14443. gl_PointSize = pointSize;
  14444. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14445. }
  14446. `;
  14447. /** Types of coloring used when viewing point cloud tiles */
  14448. var PointCloudColoring;
  14449. (function (PointCloudColoring) {
  14450. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14451. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14452. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14453. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14454. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14455. })(PointCloudColoring || (PointCloudColoring = {}));
  14456. /** Types of shading used when viewing b3dm (mesh) tiles */
  14457. var Shading;
  14458. (function (Shading) {
  14459. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14460. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14461. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14462. })(Shading || (Shading = {}));
  14463. var GeoTransform;
  14464. (function (GeoTransform) {
  14465. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14466. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14467. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14468. })(GeoTransform || (GeoTransform = {}));
  14469. const gradient = Gradients.RAINBOW;
  14470. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14471. const grayscale = Gradients.GRAYSCALE;
  14472. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14473. const defaultOptions = {
  14474. throttleRequests: true,
  14475. maxRequests: 64,
  14476. updateInterval: 0.1,
  14477. maxConcurrency: 1,
  14478. maximumScreenSpaceError: 16,
  14479. maximumMemoryUsage: 32,
  14480. viewDistanceScale: 1.0,
  14481. skipLevelOfDetail: false,
  14482. updateTransforms: true,
  14483. shading: Shading.FlatTexture,
  14484. transparent: false,
  14485. pointCloudColoring: PointCloudColoring.White,
  14486. pointSize: 1.0,
  14487. worker: true,
  14488. wireframe: false,
  14489. debug: false,
  14490. basisTranscoderPath: null,
  14491. dracoDecoderPath: null,
  14492. material: null,
  14493. computeNormals: false,
  14494. shaderCallback: null,
  14495. geoTransform: GeoTransform.Reset,
  14496. preloadTilesCount: null
  14497. };
  14498. /** 3D Tiles Loader */
  14499. class Loader3DTiles {
  14500. /**
  14501. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14502. * @public
  14503. *
  14504. * @param props - Properties for this load call {@link LoaderProps}.
  14505. * @returns An object containing the 3D Model to be added to the scene
  14506. * and a runtime engine to be updated every frame.
  14507. */
  14508. static load(props) {
  14509. return __awaiter(this, void 0, void 0, function* () {
  14510. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14511. const { url } = props;
  14512. const UPDATE_INTERVAL = options.updateInterval;
  14513. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14514. const loadersGLOptions = {};
  14515. if (options.cesiumIONToken) {
  14516. loadersGLOptions['cesium-ion'] = {
  14517. accessToken: options.cesiumIONToken,
  14518. };
  14519. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14520. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14521. }
  14522. if (props.loadingManager) {
  14523. props.loadingManager.itemStart(url);
  14524. }
  14525. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14526. const renderMap = {};
  14527. const boxMap = {};
  14528. const unloadQueue = [];
  14529. const root = new Group();
  14530. const tileBoxes = new Group();
  14531. tileBoxes.matrixAutoUpdate = false//add
  14532. if (!options.debug) {
  14533. tileBoxes.visible = false;
  14534. }else{
  14535. options.parent.add(tileBoxes) //add
  14536. }
  14537. const pointcloudUniforms = {
  14538. pointSize: { type: 'f', value: options.pointSize },
  14539. gradient: { type: 't', value: gradientTexture },
  14540. grayscale: { type: 't', value: grayscaleTexture },
  14541. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14542. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14543. coloring: { type: 'i', value: options.pointCloudColoring },
  14544. hideGround: { type: 'b', value: true },
  14545. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14546. maxIntensity: { type: 'f', value: 1.0 },
  14547. intensityContrast: { type: 'f', value: 1.0 },
  14548. alpha: { type: 'f', value: 1.0 },
  14549. };
  14550. const pointcloudMaterial = new ShaderMaterial({
  14551. uniforms: pointcloudUniforms,
  14552. vertexShader: PointCloudVS,
  14553. fragmentShader: PointCloudFS,
  14554. transparent: options.transparent,
  14555. vertexColors: true
  14556. });
  14557. let cameraReference = null;
  14558. let rendererReference = null;
  14559. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14560. let ktx2Loader = undefined;
  14561. let dracoLoader = undefined;
  14562. if (options.basisTranscoderPath) {
  14563. ktx2Loader = new KTX2Loader();
  14564. ktx2Loader.detectSupport(props.renderer);
  14565. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14566. ktx2Loader.setWorkerLimit(1);
  14567. gltfLoader.setKTX2Loader(ktx2Loader);
  14568. }
  14569. if (options.dracoDecoderPath) {
  14570. dracoLoader = new DRACOLoader();
  14571. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14572. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14573. gltfLoader.setDRACOLoader(dracoLoader);
  14574. }
  14575. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14576. const tileOptions = {
  14577. maximumMemoryUsage: options.maximumMemoryUsage,
  14578. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14579. initialMaxSSE: options.maximumScreenSpaceError,
  14580. viewDistanceScale: options.viewDistanceScale,
  14581. skipLevelOfDetail: options.skipLevelOfDetail,
  14582. updateTransforms: options.updateTransforms,
  14583. throttleRequests: options.throttleRequests,
  14584. maxRequests: options.maxRequests,
  14585. updateTime: options.updateTime || 0, //add
  14586. //maxDepth: options.maxDepth || 50, // !zeg改
  14587. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14588. let tileContent = null;
  14589. switch (tile.type) {
  14590. case TILE_TYPE.POINTCLOUD: {
  14591. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14592. break;
  14593. }
  14594. case TILE_TYPE.SCENEGRAPH:
  14595. case TILE_TYPE.MESH: {
  14596. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14597. break;
  14598. }
  14599. }
  14600. if (tileContent) {
  14601. tileContent.visible = false;
  14602. renderMap[tile.id] = tileContent;
  14603. tileContent.name = tile.id //add
  14604. tileContent.tile = tile //add
  14605. changeModelPointCount(tile, 'add')
  14606. root.add(renderMap[tile.id]);
  14607. if (options.debug) {
  14608. const box = loadersBoundingBoxToMesh(tile);
  14609. tileBoxes.add(box);
  14610. boxMap[tile.id] = box;
  14611. }
  14612. //xzw :
  14613. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14614. }
  14615. }),
  14616. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14617. if (tileset) {
  14618. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14619. detectOrientation(tile);
  14620. }
  14621. tileset._frameNumber++;
  14622. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14623. }
  14624. }),
  14625. onTileUnload: (tile) => {
  14626. unloadQueue.push(tile);
  14627. },
  14628. onTileError: (tile, message) => {
  14629. console.error('Tile error', tile.id, message);
  14630. },
  14631. };
  14632. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14633. loadImages: false,
  14634. }, '3d-tiles': {
  14635. loadGLTF: false
  14636. } }) }));
  14637. tileset.boxMap = boxMap //add
  14638. // transformations
  14639. const threeMat = new Matrix4$1();
  14640. const tileTransform = new Matrix4$1();
  14641. const rootCenter = new Vector3$1();
  14642. let orientationDetected = false;
  14643. if (tileset.root.boundingVolume) {
  14644. if (tileset.root.header.boundingVolume.region) {
  14645. // TODO: Handle region type bounding volumes
  14646. // https://github.com/visgl/loaders.gl/issues/1994
  14647. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14648. options.geoTransform = GeoTransform.WGS84Cartesian;
  14649. }
  14650. tileTransform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14651. }
  14652. else {
  14653. console.warn("Bounding volume not found, no transformations applied");
  14654. }
  14655. if (options.debug) {
  14656. const box = loadersBoundingBoxToMesh(tileset.root);
  14657. tileBoxes.add(box);
  14658. boxMap[tileset.root.id] = box;
  14659. }
  14660. let disposeFlag = false;
  14661. let loadingEnded = false;
  14662. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14663. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14664. // Extra stats
  14665. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14666. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14667. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14668. let timer = 0;
  14669. let lastCameraTransform = null;
  14670. let lastCameraAspect = null;
  14671. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14672. let sseDenominator = null;
  14673. root.updateMatrixWorld(true);
  14674. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14675. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14676. tileset.lastRootTransform = lastRootTransform //add
  14677. detectOrientation(tileset.root);
  14678. updateResetTransform();
  14679. if (options.debug) {
  14680. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14681. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14682. }
  14683. if (options.geoTransform == GeoTransform.Mercator) {
  14684. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14685. rootCenter.set(coords.x, 0, -coords.y);
  14686. root.position.copy(rootCenter);
  14687. root.rotation.set(-Math.PI / 2, 0, 0);
  14688. root.updateMatrixWorld(true);
  14689. }
  14690. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14691. root.applyMatrix4(tileTransform);
  14692. root.updateMatrixWorld(true);
  14693. rootCenter.copy(root.position);
  14694. }
  14695. function detectOrientation(tile) {
  14696. if (!tile.boundingVolume.halfAxes) {
  14697. return;
  14698. }
  14699. const halfAxes = tile.boundingVolume.halfAxes;
  14700. const orientationMatrix = new Matrix4$1()
  14701. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14702. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14703. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14704. if (!rotation.equals(new Euler())) {
  14705. orientationDetected = true;
  14706. const pos = new Vector3$1(tileTransform.elements[12], tileTransform.elements[13], tileTransform.elements[14]);
  14707. tileTransform.extractRotation(orientationMatrix);
  14708. tileTransform.setPosition(pos);
  14709. updateResetTransform();
  14710. }
  14711. }
  14712. function updateResetTransform() {
  14713. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14714. // Reset the current model matrix and apply our own transformation
  14715. //threeMat.copy(tileTransform).invert();
  14716. //threeMat.premultiply(lastRootTransform); //xzw删 被下面copy这句覆盖了
  14717. let tileTransInvert = new Matrix4$1().copy(tileTransform).invert()
  14718. threeMat.copy(lastRootTransform).multiply(tileTransInvert);
  14719. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14720. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  14721. tileset.tileTransInvert = tileTransInvert.toArray() // add for volumebox
  14722. }
  14723. }
  14724. // 更新瓦片显隐和瓦片迭代更新
  14725. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14726. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14727. return
  14728. }
  14729. // Assumes camera fov, near and far are not changing
  14730. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14731. const loadersFrustum = new PerspectiveFrustum({
  14732. fov: (camera.fov / 180) * Math.PI,
  14733. aspectRatio: camera.aspect,
  14734. near: camera.near,
  14735. far: camera.far,
  14736. });
  14737. sseDenominator = loadersFrustum.sseDenominator;
  14738. lastCameraAspect = camera.aspect;
  14739. if(camera.aspect == 0)return//add
  14740. if (options.debug) {
  14741. console.log('Updated sse denonimator:', sseDenominator);
  14742. }
  14743. }
  14744. const frustum = getCameraFrustum(camera);
  14745. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14746. const cullingVolume = new CullingVolume(planes);
  14747. const rendererSize = new Vector2$1();
  14748. renderer.getSize(rendererSize);
  14749. const frameState = {
  14750. camera: {
  14751. position: lastCameraPosition.toArray(),
  14752. },
  14753. height: rendererSize.y,
  14754. frameNumber: tileset._frameNumber,
  14755. sseDenominator: sseDenominator,
  14756. cullingVolume: cullingVolume,
  14757. viewport: {
  14758. id: 0,
  14759. },
  14760. };
  14761. tileset._cache.reset();
  14762. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14763. for (const tile of tileset.tiles) {
  14764. if (tile.selected) {
  14765. if (!renderMap[tile.id]) {
  14766. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14767. }
  14768. else {
  14769. // Make sure it's visible
  14770. if(!renderMap[tile.id].visible){
  14771. if(viewer.visiVertexCount<maxVertexVisi){
  14772. renderMap[tile.id].visible = true;
  14773. viewer.visiVertexCount += tile.posCount //renderMap[tile.id].vertexCount //xzw add
  14774. options.debug && (boxMap[tile.id].material.opacity = 1 , boxMap[tile.id].children[0].sprite.material.opacity = 1 )
  14775. }else{
  14776. //console.log('超出', visiVertexCount)
  14777. }
  14778. }
  14779. /* if(!renderMap[tile.id].realVisible()){
  14780. console.error('!realVisible')
  14781. } */
  14782. }
  14783. }
  14784. else {
  14785. if (renderMap[tile.id]) {
  14786. if(renderMap[tile.id].visible){
  14787. renderMap[tile.id].visible = false;
  14788. options.debug && (boxMap[tile.id].material.opacity = 0.1, boxMap[tile.id].children[0].sprite.material.opacity = 0.1)
  14789. viewer.visiVertexCount -= tile.posCount //renderMap[tile.id].vertexCount //xzw add
  14790. }
  14791. }
  14792. }
  14793. }
  14794. while (unloadQueue.length > 0) {
  14795. const tile = unloadQueue.pop();
  14796. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14797. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14798. root.remove(renderMap[tile.id]);
  14799. disposeNode(renderMap[tile.id]);
  14800. delete renderMap[tile.id];
  14801. }
  14802. if (boxMap[tile.id]) {
  14803. disposeNode(boxMap[tile.id]);
  14804. tileBoxes.remove(boxMap[tile.id]);
  14805. delete boxMap[tile.id];
  14806. }
  14807. }
  14808. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14809. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14810. if (props.onProgress) {
  14811. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14812. }
  14813. if (props.loadingManager && !loadingEnded) {
  14814. if (tilesLoading == 0 &&
  14815. (options.preloadTilesCount == null ||
  14816. tilesLoaded >= options.preloadTilesCount)) {
  14817. loadingEnded = true;
  14818. props.loadingManager.itemEnd(props.url);
  14819. }
  14820. }
  14821. return frameState;
  14822. }
  14823. return {
  14824. model: root,
  14825. runtime: {
  14826. getTileset: () => {
  14827. return tileset;
  14828. },
  14829. getStats: () => {
  14830. return tileset.stats;
  14831. },
  14832. showTiles: (visible) => {
  14833. tileBoxes.visible = visible;
  14834. },
  14835. setWireframe: (wireframe) => {
  14836. options.wireframe = wireframe;
  14837. root.traverse((object) => {
  14838. if (object instanceof Mesh) {
  14839. object.material.wireframe = wireframe;
  14840. }
  14841. });
  14842. },
  14843. setDebug: (debug) => {
  14844. options.debug = debug;
  14845. tileBoxes.visible = debug;
  14846. },
  14847. setShading: (shading) => {
  14848. options.shading = shading;
  14849. },
  14850. getTileBoxes: () => {
  14851. return tileBoxes;
  14852. },
  14853. setViewDistanceScale: (scale) => {
  14854. tileset.options.viewDistanceScale = scale;
  14855. tileset._frameNumber++;
  14856. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14857. },
  14858. setHideGround: (enabled) => {
  14859. pointcloudUniforms.hideGround.value = enabled;
  14860. },
  14861. setPointCloudColoring: (selection) => {
  14862. pointcloudUniforms.coloring.value = selection;
  14863. },
  14864. setElevationRange: (range) => {
  14865. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14866. },
  14867. setMaxIntensity: (intensity) => {
  14868. pointcloudUniforms.maxIntensity.value = intensity;
  14869. },
  14870. setIntensityContrast: (contrast) => {
  14871. pointcloudUniforms.intensityContrast.value = contrast;
  14872. },
  14873. setPointAlpha: (alpha) => {
  14874. pointcloudUniforms.alpha.value = alpha;
  14875. },
  14876. getLatLongHeightFromPosition: (position) => {
  14877. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14878. return {
  14879. lat: cartographicPosition[1],
  14880. long: cartographicPosition[0],
  14881. height: cartographicPosition[2],
  14882. };
  14883. },
  14884. getPositionFromLatLongHeight: (coord) => {
  14885. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14886. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14887. },
  14888. getCameraFrustum: (camera) => {
  14889. const frustum = getCameraFrustum(camera);
  14890. const meshes = frustum.planes
  14891. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14892. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14893. const model = new Group();
  14894. for (const mesh of meshes)
  14895. model.add(mesh);
  14896. return model;
  14897. },
  14898. update: function (dt, renderer, camera, ifForce) {
  14899. cameraReference = camera;
  14900. rendererReference = renderer;
  14901. timer += dt;
  14902. //updateQuality()
  14903. if(!ifForce) ifForce = tileset.nextForceUpdate
  14904. tileset.nextForceUpdate = false
  14905. if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  14906. viewer.dispatchEvent('content_changed')
  14907. }
  14908. tileset.needRenderNext = ifForce
  14909. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  14910. if (!lastRootTransform.equals(root.matrixWorld)) {
  14911. timer = 0;
  14912. lastRootTransform.copy(root.matrixWorld);
  14913. updateResetTransform();
  14914. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14915. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14916. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14917. rootTransformInverse.copy(lastRootTransform).invert();
  14918. if (options.debug) {
  14919. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14920. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14921. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14922. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14923. tileBoxes.matrix.copy(root.matrixWorld);
  14924. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14925. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14926. //boxMap[tileset.root.id].updateWorldMatrix()
  14927. }
  14928. }
  14929. if (this.lastCameraTransform == null) {
  14930. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14931. }
  14932. else {
  14933. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14934. !(camera.aspect == lastCameraAspect);
  14935. if (cameraChanged || ifForce) {
  14936. timer = 0;
  14937. tileset._frameNumber++;
  14938. camera.getWorldPosition(lastCameraPosition);
  14939. this.lastCameraTransform.copy(camera.matrixWorld);
  14940. tilesetUpdate(tileset, renderMap, renderer, camera);
  14941. }
  14942. }
  14943. }
  14944. },
  14945. dispose: function () {
  14946. disposeFlag = true;
  14947. tileset._destroy();
  14948. while (root.children.length > 0) {
  14949. const obj = root.children[0];
  14950. disposeNode(obj);
  14951. root.remove(obj);
  14952. }
  14953. while (tileBoxes.children.length > 0) {
  14954. const obj = tileBoxes.children[0];
  14955. tileBoxes.remove(obj);
  14956. obj.geometry.dispose();
  14957. obj.material.dispose();
  14958. }
  14959. if (ktx2Loader) {
  14960. ktx2Loader.dispose();
  14961. }
  14962. if (dracoLoader) {
  14963. dracoLoader.dispose();
  14964. }
  14965. },
  14966. limit2lowestDepth: isLowest => {//zeg add 设置是否限制为最低精度tile深度
  14967. maxDepth = isLowest ? 1 : 100 //影响到shouldRefine, 检查方法:可以看到当maxDepth降低了之后viewer.objs.children[0].runtime.getTileset().tiles.filter(e=> e.tileContent.visible)变少
  14968. if (cameraReference) {
  14969. tileset._frameNumber++
  14970. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference)
  14971. }
  14972. },
  14973. },
  14974. };
  14975. });
  14976. }
  14977. }
  14978. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14979. return __awaiter(this, void 0, void 0, function* () {
  14980. return new Promise((resolve, reject) => {
  14981. var _a;
  14982. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14983. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14984. // The computed trasnform already contains the root's transform, so we have to invert it
  14985. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14986. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  14987. // 这句同tile.computedTransform左乘tileTransform。 因为tileTransform拿不到所以使用modelMatrix。modelMatrix为tileTransform左乘rootTransform, 所以再左乘rootTransformInverse
  14988. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  14989. gltfLoader.parse(
  14990. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14991. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14992. (gltf) => {
  14993. const tileContent = gltf.scenes[0];
  14994. //tileContent.vertexCount = 0 //xzw add
  14995. tile.tileContent = tileContent //xzw add
  14996. let needUpdate
  14997. if(tile.rtcCenterState != !!tile.content.rtcCenter){ // 等mesh加载好才知道rtcCenter,每个mesh坐标都不一样
  14998. needUpdate = true
  14999. //console.error('rtcCenter有变化?!')
  15000. }
  15001. tile.rtcCenterState = rtcCenterGlobal = !!tile.content.rtcCenter
  15002. let contentTransform = tile.getContentTransform(needUpdate)
  15003. if(tile.content.rtcCenter){//大部分模型无 rtcCenter
  15004. //console.error('rtcCenter有?!') //似乎bounding中包含这个信息了 所以getContentTransform不含这个
  15005. let tranM = new Matrix4$1()
  15006. tranM.makeTranslation(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  15007. contentTransform.premultiply(tranM)
  15008. }
  15009. if(needUpdate ){
  15010. tile._updateBoundingVolume(tile.header) //add 重新更新
  15011. }
  15012. if (shouldRotate) { //大部分模型 无需 Rotate
  15013. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  15014. }
  15015. tileContent.applyMatrix4(contentTransform);
  15016. //'https://testgis.4dage.com/LVBADUI_qp/tileset.json', //村庄 这个案例是 要rotateX 且有rtcCenter的。boundingVolume已经是转换这两者后的值所以getContentTransform不加这个
  15017. //tile总共要左乘的矩阵 rotateX -> tileTransInvert * computedTransform -> 对geometry的tranM修改 -> 整个模型的matrixWorld
  15018. tileContent.traverse((object) => {
  15019. if (object.type == "Mesh") {
  15020. const mesh = object;
  15021. //mesh.tileId = tile.id//add
  15022. const originalMaterial = mesh.material;
  15023. const originalMap = originalMaterial.map;
  15024. if (options.material) {
  15025. mesh.material = options.material.clone();
  15026. originalMaterial.dispose();
  15027. }
  15028. else if (options.shading == Shading.FlatTexture) {
  15029. mesh.material = unlitMaterial.clone();
  15030. originalMaterial.dispose();
  15031. }
  15032. if (options.shading != Shading.ShadedNoTexture) {
  15033. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  15034. mesh.material.uniforms.map = { value: originalMap };
  15035. }
  15036. else {
  15037. mesh.material.map = originalMap;
  15038. }
  15039. }
  15040. else {
  15041. if (originalMap) {
  15042. originalMap.dispose();
  15043. }
  15044. mesh.material.map = null;
  15045. }
  15046. if (options.shaderCallback) {
  15047. mesh.onBeforeRender = options.shaderCallback;
  15048. }
  15049. mesh.material.wireframe = options.wireframe;
  15050. if (options.computeNormals) {
  15051. mesh.geometry.computeVertexNormals();
  15052. }
  15053. //xzw add:
  15054. //tileContent.vertexCount += mesh.geometry.attributes.position.count
  15055. //------------------add on 2023.1.16----zeg
  15056. //mesh.geometry.applyMatrix4(contentTransform)
  15057. /* if (tile.content.rtcCenter) {
  15058. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  15059. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  15060. } else {
  15061. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  15062. } */
  15063. //---------------------
  15064. }
  15065. });
  15066. resolve(tileContent);
  15067. },
  15068. (e) => {
  15069. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  15070. }
  15071. );
  15072. });
  15073. });
  15074. }
  15075. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  15076. const d = {
  15077. rtc_center: tile.content.rtcCenter,
  15078. points: tile.content.attributes.positions,
  15079. intensities: tile.content.attributes.intensity,
  15080. classifications: tile.content.attributes.classification,
  15081. rgb: null,
  15082. rgba: null,
  15083. };
  15084. const { colors } = tile.content.attributes;
  15085. if (colors && colors.size === 3) {
  15086. d.rgb = colors.value;
  15087. }
  15088. if (colors && colors.size === 4) {
  15089. d.rgba = colors.value;
  15090. }
  15091. const geometry = new BufferGeometry();
  15092. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  15093. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15094. if (d.rgba) {
  15095. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  15096. }
  15097. else if (d.rgb) {
  15098. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  15099. }
  15100. if (d.intensities) {
  15101. geometry.setAttribute('intensity',
  15102. // Handles both 16bit or 8bit intensity values
  15103. new BufferAttribute(d.intensities, 1, true));
  15104. }
  15105. if (d.classifications) {
  15106. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  15107. }
  15108. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  15109. if (d.rtc_center) {
  15110. const c = d.rtc_center;
  15111. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  15112. }
  15113. tileContent.applyMatrix4(contentTransform);
  15114. return tileContent;
  15115. }
  15116. function disposeMaterial(material) {
  15117. var _a, _b, _c, _d;
  15118. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  15119. (_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();
  15120. }
  15121. else if (material.map) {
  15122. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  15123. }
  15124. material.dispose();
  15125. }
  15126. function disposeNode(node) {
  15127. node.traverse((object) => {
  15128. if (object.isMesh) {
  15129. object.geometry.dispose();
  15130. if (object.material.isMaterial) {
  15131. disposeMaterial(object.material);
  15132. }
  15133. else {
  15134. // an array of materials
  15135. for (const material of object.material) {
  15136. disposeMaterial(material);
  15137. }
  15138. }
  15139. }
  15140. });
  15141. for (let i = node.children.length - 1; i >= 0; i--) {
  15142. const obj = node.children[i];
  15143. node.remove(obj);
  15144. }
  15145. }
  15146. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  15147. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  15148. /*
  15149. 关键搜寻:
  15150. Loader3DTiles : const tileset = new Tileset3D
  15151. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  15152. createGLTFNodes(gltfLoader 创建tile
  15153. executeTraversal(root, frameState) 遍历root
  15154. lastRootTransform rootTransformInverse
  15155. tileset._loadTiles 依次加载tiles
  15156. _getPriority 加载优先级 加了一句
  15157. 笔记:
  15158. 主要类:
  15159. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  15160. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  15161. tileset里算的tileTransform之后是不会改变的, tile.transform也是,是json里的。
  15162. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  15163. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  15164. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  15165. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  15166. get isVisibleAndInRequestVolume() {
  15167. return this._inRequestVolume; //去掉了_visible ||
  15168. }
  15169. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  15170. 原本会消失的地方虽然不会消失了但一直是模糊的
  15171. 被隐藏的tiles对应的mesh也是仅隐藏,并未删除
  15172. =========
  15173. 访问所有tile:
  15174. viewer.objs.children[0].runtime.getTileset().tiles
  15175. 它的mesh: tile.tileContent
  15176. 或者直接得到所有mesh: viewer.objs.children[0].children
  15177. tile.depth最低为1 , root是0
  15178. */