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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041
  1. import { EventDispatcher, CanvasTexture, LinearFilter, RepeatWrapping, Vector2 as Vector2$1, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1/*, MeshBasicMaterial */, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from '../build/three.module.js';
  2. import { GLTFLoader as GLTFLoader$1 } from '../loaders/GLTFLoader.js';
  3. import { DRACOLoader } from '../loaders/DRACOLoader.js';
  4. import { KTX2Loader } from '../loaders/KTX2Loader.js';
  5. import MeshBasicMaterial from '../../../src/custom/materials/BasicMaterial.js' // xzw改 原先MeshBasicMaterial贴图发黑,可能和贴图有关
  6. let globalThis = window //add 有的app没有globalThis. 2023.1
  7. /*! *****************************************************************************
  8. Copyright (c) Microsoft Corporation.
  9. Permission to use, copy, modify, and/or distribute this software for any
  10. purpose with or without fee is hereby granted.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  12. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  13. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  14. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  15. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  16. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  17. PERFORMANCE OF THIS SOFTWARE.
  18. ***************************************************************************** */
  19. let visiVertexCount = 0
  20. let visiGeoCount = 0
  21. const maxVertexVisi = 5e6
  22. const maxTexVisi = 500
  23. function getGpuMemoryUsage(win = window){//总的
  24. let c = 0
  25. viewer.objs.children.filter(e=>{
  26. if(e.fileType == '3dTiles'){
  27. let tileset3D = e.runtime.getTileset()
  28. c += tileset3D.gpuMemoryUsageInBytes
  29. }
  30. })
  31. if(win.parent != win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  32. c += getGpuMemoryUsage(win.parent)
  33. }
  34. viewer.tiles3dMemoryUsage = c
  35. viewer.tiles3dVisiVCount = visiVertexCount
  36. return c
  37. }
  38. function __awaiter(thisArg, _arguments, P, generator) {
  39. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  40. return new (P || (P = Promise))(function (resolve, reject) {
  41. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  42. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  43. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  44. step((generator = generator.apply(thisArg, _arguments || [])).next());
  45. });
  46. }
  47. function assert$7(condition, message) {
  48. if (!condition) {
  49. throw new Error(message || 'loader assertion failed.');
  50. }
  51. }
  52. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  53. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  54. matches$1 && parseFloat(matches$1[1]) || 0;
  55. const VERSION$8 = "3.1.4" ;
  56. function assert$6(condition, message) {
  57. if (!condition) {
  58. throw new Error(message || 'loaders.gl assertion failed.');
  59. }
  60. }
  61. const globals$1 = {
  62. self: typeof self !== 'undefined' && self,
  63. window: typeof window !== 'undefined' && window,
  64. global: typeof global !== 'undefined' && global,
  65. document: typeof document !== 'undefined' && document
  66. };
  67. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  68. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  69. const isWorker = typeof importScripts === 'function';
  70. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  71. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  72. matches && parseFloat(matches[1]) || 0;
  73. function _defineProperty(obj, key, value) {
  74. if (key in obj) {
  75. Object.defineProperty(obj, key, {
  76. value: value,
  77. enumerable: true,
  78. configurable: true,
  79. writable: true
  80. });
  81. } else {
  82. obj[key] = value;
  83. }
  84. return obj;
  85. }
  86. class WorkerJob {
  87. constructor(jobName, workerThread) {
  88. _defineProperty(this, "name", void 0);
  89. _defineProperty(this, "workerThread", void 0);
  90. _defineProperty(this, "isRunning", void 0);
  91. _defineProperty(this, "result", void 0);
  92. _defineProperty(this, "_resolve", void 0);
  93. _defineProperty(this, "_reject", void 0);
  94. this.name = jobName;
  95. this.workerThread = workerThread;
  96. this.isRunning = true;
  97. this._resolve = () => {};
  98. this._reject = () => {};
  99. this.result = new Promise((resolve, reject) => {
  100. this._resolve = resolve;
  101. this._reject = reject;
  102. });
  103. }
  104. postMessage(type, payload) {
  105. this.workerThread.postMessage({
  106. source: 'loaders.gl',
  107. type,
  108. payload
  109. });
  110. }
  111. done(value) {
  112. assert$6(this.isRunning);
  113. this.isRunning = false;
  114. this._resolve(value);
  115. }
  116. error(error) {
  117. assert$6(this.isRunning);
  118. this.isRunning = false;
  119. this._reject(error);
  120. }
  121. }
  122. const workerURLCache = new Map();
  123. function getLoadableWorkerURL(props) {
  124. assert$6(props.source && !props.url || !props.source && props.url);
  125. let workerURL = workerURLCache.get(props.source || props.url);
  126. if (!workerURL) {
  127. if (props.url) {
  128. workerURL = getLoadableWorkerURLFromURL(props.url);
  129. workerURLCache.set(props.url, workerURL);
  130. }
  131. if (props.source) {
  132. workerURL = getLoadableWorkerURLFromSource(props.source);
  133. workerURLCache.set(props.source, workerURL);
  134. }
  135. }
  136. assert$6(workerURL);
  137. return workerURL;
  138. }
  139. function getLoadableWorkerURLFromURL(url) {
  140. if (!url.startsWith('http')) {
  141. return url;
  142. }
  143. const workerSource = buildScriptSource(url);
  144. return getLoadableWorkerURLFromSource(workerSource);
  145. }
  146. function getLoadableWorkerURLFromSource(workerSource) {
  147. const blob = new Blob([workerSource], {
  148. type: 'application/javascript'
  149. });
  150. return URL.createObjectURL(blob);
  151. }
  152. function buildScriptSource(workerUrl) {
  153. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  154. }
  155. function getTransferList(object, recursive = true, transfers) {
  156. const transfersSet = transfers || new Set();
  157. if (!object) ; else if (isTransferable(object)) {
  158. transfersSet.add(object);
  159. } else if (isTransferable(object.buffer)) {
  160. transfersSet.add(object.buffer);
  161. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  162. for (const key in object) {
  163. getTransferList(object[key], recursive, transfersSet);
  164. }
  165. }
  166. return transfers === undefined ? Array.from(transfersSet) : [];
  167. }
  168. function isTransferable(object) {
  169. if (!object) {
  170. return false;
  171. }
  172. if (object instanceof ArrayBuffer) {
  173. return true;
  174. }
  175. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  176. return true;
  177. }
  178. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  179. return true;
  180. }
  181. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  182. return true;
  183. }
  184. return false;
  185. }
  186. const NOOP = () => {};
  187. class WorkerThread {
  188. static isSupported() {
  189. return typeof Worker !== 'undefined';
  190. }
  191. constructor(props) {
  192. _defineProperty(this, "name", void 0);
  193. _defineProperty(this, "source", void 0);
  194. _defineProperty(this, "url", void 0);
  195. _defineProperty(this, "terminated", false);
  196. _defineProperty(this, "worker", void 0);
  197. _defineProperty(this, "onMessage", void 0);
  198. _defineProperty(this, "onError", void 0);
  199. _defineProperty(this, "_loadableURL", '');
  200. const {
  201. name,
  202. source,
  203. url
  204. } = props;
  205. assert$6(source || url);
  206. this.name = name;
  207. this.source = source;
  208. this.url = url;
  209. this.onMessage = NOOP;
  210. this.onError = error => console.log(error);
  211. this.worker = this._createBrowserWorker();
  212. }
  213. destroy() {
  214. this.onMessage = NOOP;
  215. this.onError = NOOP;
  216. this.worker.terminate();
  217. this.terminated = true;
  218. }
  219. get isRunning() {
  220. return Boolean(this.onMessage);
  221. }
  222. postMessage(data, transferList) {
  223. transferList = transferList || getTransferList(data);
  224. this.worker.postMessage(data, transferList);
  225. }
  226. _getErrorFromErrorEvent(event) {
  227. let message = 'Failed to load ';
  228. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  229. if (event.message) {
  230. message += "".concat(event.message, " in ");
  231. }
  232. if (event.lineno) {
  233. message += ":".concat(event.lineno, ":").concat(event.colno);
  234. }
  235. return new Error(message);
  236. }
  237. _createBrowserWorker() {
  238. this._loadableURL = getLoadableWorkerURL({
  239. source: this.source,
  240. url: this.url
  241. });
  242. const worker = new Worker(this._loadableURL, {
  243. name: this.name
  244. });
  245. worker.onmessage = event => {
  246. if (!event.data) {
  247. this.onError(new Error('No data received'));
  248. } else {
  249. this.onMessage(event.data);
  250. }
  251. };
  252. worker.onerror = error => {
  253. this.onError(this._getErrorFromErrorEvent(error));
  254. this.terminated = true;
  255. };
  256. worker.onmessageerror = event => console.error(event);
  257. return worker;
  258. }
  259. }
  260. class WorkerPool {
  261. constructor(props) {
  262. _defineProperty(this, "name", 'unnamed');
  263. _defineProperty(this, "source", void 0);
  264. _defineProperty(this, "url", void 0);
  265. _defineProperty(this, "maxConcurrency", 1);
  266. _defineProperty(this, "maxMobileConcurrency", 1);
  267. _defineProperty(this, "onDebug", () => {});
  268. _defineProperty(this, "reuseWorkers", true);
  269. _defineProperty(this, "props", {});
  270. _defineProperty(this, "jobQueue", []);
  271. _defineProperty(this, "idleQueue", []);
  272. _defineProperty(this, "count", 0);
  273. _defineProperty(this, "isDestroyed", false);
  274. this.source = props.source;
  275. this.url = props.url;
  276. this.setProps(props);
  277. }
  278. destroy() {
  279. this.idleQueue.forEach(worker => worker.destroy());
  280. this.isDestroyed = true;
  281. }
  282. setProps(props) {
  283. this.props = { ...this.props,
  284. ...props
  285. };
  286. if (props.name !== undefined) {
  287. this.name = props.name;
  288. }
  289. if (props.maxConcurrency !== undefined) {
  290. this.maxConcurrency = props.maxConcurrency;
  291. }
  292. if (props.maxMobileConcurrency !== undefined) {
  293. this.maxMobileConcurrency = props.maxMobileConcurrency;
  294. }
  295. if (props.reuseWorkers !== undefined) {
  296. this.reuseWorkers = props.reuseWorkers;
  297. }
  298. if (props.onDebug !== undefined) {
  299. this.onDebug = props.onDebug;
  300. }
  301. }
  302. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  303. const startPromise = new Promise(onStart => {
  304. this.jobQueue.push({
  305. name,
  306. onMessage,
  307. onError,
  308. onStart
  309. });
  310. return this;
  311. });
  312. this._startQueuedJob();
  313. return await startPromise;
  314. }
  315. async _startQueuedJob() {
  316. if (!this.jobQueue.length) {
  317. return;
  318. }
  319. const workerThread = this._getAvailableWorker();
  320. if (!workerThread) {
  321. return;
  322. }
  323. const queuedJob = this.jobQueue.shift();
  324. if (queuedJob) {
  325. this.onDebug({
  326. message: 'Starting job',
  327. name: queuedJob.name,
  328. workerThread,
  329. backlog: this.jobQueue.length
  330. });
  331. const job = new WorkerJob(queuedJob.name, workerThread);
  332. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  333. workerThread.onError = error => queuedJob.onError(job, error);
  334. queuedJob.onStart(job);
  335. try {
  336. await job.result;
  337. } finally {
  338. this.returnWorkerToQueue(workerThread);
  339. }
  340. }
  341. }
  342. returnWorkerToQueue(worker) {
  343. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  344. if (shouldDestroyWorker) {
  345. worker.destroy();
  346. this.count--;
  347. } else {
  348. this.idleQueue.push(worker);
  349. }
  350. if (!this.isDestroyed) {
  351. this._startQueuedJob();
  352. }
  353. }
  354. _getAvailableWorker() {
  355. if (this.idleQueue.length > 0) {
  356. return this.idleQueue.shift() || null;
  357. }
  358. if (this.count < this._getMaxConcurrency()) {
  359. this.count++;
  360. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  361. return new WorkerThread({
  362. name,
  363. source: this.source,
  364. url: this.url
  365. });
  366. }
  367. return null;
  368. }
  369. _getMaxConcurrency() {
  370. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  371. }
  372. }
  373. const DEFAULT_PROPS$3 = {
  374. maxConcurrency: 3,
  375. maxMobileConcurrency: 1,
  376. onDebug: () => {},
  377. reuseWorkers: true
  378. };
  379. class WorkerFarm {
  380. static isSupported() {
  381. return WorkerThread.isSupported();
  382. }
  383. static getWorkerFarm(props = {}) {
  384. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  385. WorkerFarm._workerFarm.setProps(props);
  386. return WorkerFarm._workerFarm;
  387. }
  388. constructor(props) {
  389. _defineProperty(this, "props", void 0);
  390. _defineProperty(this, "workerPools", new Map());
  391. this.props = { ...DEFAULT_PROPS$3
  392. };
  393. this.setProps(props);
  394. this.workerPools = new Map();
  395. }
  396. destroy() {
  397. for (const workerPool of this.workerPools.values()) {
  398. workerPool.destroy();
  399. }
  400. }
  401. setProps(props) {
  402. this.props = { ...this.props,
  403. ...props
  404. };
  405. for (const workerPool of this.workerPools.values()) {
  406. workerPool.setProps(this._getWorkerPoolProps());
  407. }
  408. }
  409. getWorkerPool(options) {
  410. const {
  411. name,
  412. source,
  413. url
  414. } = options;
  415. let workerPool = this.workerPools.get(name);
  416. if (!workerPool) {
  417. workerPool = new WorkerPool({
  418. name,
  419. source,
  420. url
  421. });
  422. workerPool.setProps(this._getWorkerPoolProps());
  423. this.workerPools.set(name, workerPool);
  424. }
  425. return workerPool;
  426. }
  427. _getWorkerPoolProps() {
  428. return {
  429. maxConcurrency: this.props.maxConcurrency,
  430. maxMobileConcurrency: this.props.maxMobileConcurrency,
  431. reuseWorkers: this.props.reuseWorkers,
  432. onDebug: this.props.onDebug
  433. };
  434. }
  435. }
  436. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  437. const NPM_TAG = 'latest';
  438. function getWorkerURL(worker, options = {}) {
  439. const workerOptions = options[worker.id] || {};
  440. const workerFile = "".concat(worker.id, "-worker.js");
  441. let url = workerOptions.workerUrl;
  442. if (!url && worker.id === 'compression') {
  443. url = options.workerUrl;
  444. }
  445. if (options._workerType === 'test') {
  446. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  447. }
  448. if (!url) {
  449. let version = worker.version;
  450. if (version === 'latest') {
  451. version = NPM_TAG;
  452. }
  453. const versionTag = version ? "@".concat(version) : '';
  454. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  455. }
  456. assert$6(url);
  457. return url;
  458. }
  459. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  460. assert$6(worker, 'no worker provided');
  461. const workerVersion = worker.version;
  462. if (!coreVersion || !workerVersion) {
  463. return false;
  464. }
  465. return true;
  466. }
  467. var ChildProcessProxy = {};
  468. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  469. 'default': ChildProcessProxy
  470. }));
  471. const VERSION$7 = "3.1.4" ;
  472. const loadLibraryPromises = {};
  473. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  474. if (moduleName) {
  475. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  476. }
  477. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  478. return await loadLibraryPromises[libraryUrl];
  479. }
  480. function getLibraryUrl(library, moduleName, options) {
  481. if (library.startsWith('http')) {
  482. return library;
  483. }
  484. const modules = options.modules || {};
  485. if (modules[library]) {
  486. return modules[library];
  487. }
  488. if (!isBrowser$1) {
  489. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  490. }
  491. if (options.CDN) {
  492. assert$6(options.CDN.startsWith('http'));
  493. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  494. }
  495. if (isWorker) {
  496. return "../src/libs/".concat(library);
  497. }
  498. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  499. }
  500. async function loadLibraryFromFile(libraryUrl) {
  501. if (libraryUrl.endsWith('wasm')) {
  502. const response = await fetch(libraryUrl);
  503. return await response.arrayBuffer();
  504. }
  505. if (!isBrowser$1) {
  506. try {
  507. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  508. } catch {
  509. return null;
  510. }
  511. }
  512. if (isWorker) {
  513. return importScripts(libraryUrl);
  514. }
  515. const response = await fetch(libraryUrl);
  516. const scriptSource = await response.text();
  517. return loadLibraryFromString(scriptSource, libraryUrl);
  518. }
  519. function loadLibraryFromString(scriptSource, id) {
  520. if (!isBrowser$1) {
  521. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  522. }
  523. if (isWorker) {
  524. eval.call(global_, scriptSource);
  525. return null;
  526. }
  527. const script = document.createElement('script');
  528. script.id = id;
  529. try {
  530. script.appendChild(document.createTextNode(scriptSource));
  531. } catch (e) {
  532. script.text = scriptSource;
  533. }
  534. document.body.appendChild(script);
  535. return null;
  536. }
  537. function canParseWithWorker(loader, options) {
  538. if (!WorkerFarm.isSupported()) {
  539. return false;
  540. }
  541. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  542. }
  543. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  544. const name = loader.id;
  545. const url = getWorkerURL(loader, options);
  546. const workerFarm = WorkerFarm.getWorkerFarm(options);
  547. const workerPool = workerFarm.getWorkerPool({
  548. name,
  549. url
  550. });
  551. options = JSON.parse(JSON.stringify(options));
  552. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  553. job.postMessage('process', {
  554. input: data,
  555. options
  556. });
  557. const result = await job.result;
  558. return await result.result;
  559. }
  560. async function onMessage(parseOnMainThread, job, type, payload) {
  561. switch (type) {
  562. case 'done':
  563. job.done(payload);
  564. break;
  565. case 'error':
  566. job.error(new Error(payload.error));
  567. break;
  568. case 'process':
  569. const {
  570. id,
  571. input,
  572. options
  573. } = payload;
  574. try {
  575. const result = await parseOnMainThread(input, options);
  576. job.postMessage('done', {
  577. id,
  578. result
  579. });
  580. } catch (error) {
  581. const message = error instanceof Error ? error.message : 'unknown error';
  582. job.postMessage('error', {
  583. id,
  584. error: message
  585. });
  586. }
  587. break;
  588. default:
  589. console.warn("parse-with-worker unknown message ".concat(type));
  590. }
  591. }
  592. function getFirstCharacters$1(data, length = 5) {
  593. if (typeof data === 'string') {
  594. return data.slice(0, length);
  595. } else if (ArrayBuffer.isView(data)) {
  596. return getMagicString$3(data.buffer, data.byteOffset, length);
  597. } else if (data instanceof ArrayBuffer) {
  598. const byteOffset = 0;
  599. return getMagicString$3(data, byteOffset, length);
  600. }
  601. return '';
  602. }
  603. function getMagicString$3(arrayBuffer, byteOffset, length) {
  604. if (arrayBuffer.byteLength <= byteOffset + length) {
  605. return '';
  606. }
  607. const dataView = new DataView(arrayBuffer);
  608. let magic = '';
  609. for (let i = 0; i < length; i++) {
  610. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  611. }
  612. return magic;
  613. }
  614. function parseJSON(string) {
  615. try {
  616. return JSON.parse(string);
  617. } catch (_) {
  618. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  619. }
  620. }
  621. function isBuffer$1(value) {
  622. return value && typeof value === 'object' && value.isBuffer;
  623. }
  624. function bufferToArrayBuffer(buffer) {
  625. if (isBuffer$1(buffer)) {
  626. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  627. return typedArray.slice().buffer;
  628. }
  629. return buffer;
  630. }
  631. function toArrayBuffer(data) {
  632. if (isBuffer$1(data)) {
  633. return bufferToArrayBuffer(data);
  634. }
  635. if (data instanceof ArrayBuffer) {
  636. return data;
  637. }
  638. if (ArrayBuffer.isView(data)) {
  639. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  640. return data.buffer;
  641. }
  642. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  643. }
  644. if (typeof data === 'string') {
  645. const text = data;
  646. const uint8Array = new TextEncoder().encode(text);
  647. return uint8Array.buffer;
  648. }
  649. if (data && typeof data === 'object' && data._toArrayBuffer) {
  650. return data._toArrayBuffer();
  651. }
  652. throw new Error('toArrayBuffer');
  653. }
  654. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  655. byteLength = byteLength || arrayBuffer1.byteLength;
  656. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  657. return false;
  658. }
  659. const array1 = new Uint8Array(arrayBuffer1);
  660. const array2 = new Uint8Array(arrayBuffer2);
  661. for (let i = 0; i < array1.length; ++i) {
  662. if (array1[i] !== array2[i]) {
  663. return false;
  664. }
  665. }
  666. return true;
  667. }
  668. function concatenateArrayBuffers(...sources) {
  669. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  670. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  671. const result = new Uint8Array(byteLength);
  672. let offset = 0;
  673. for (const sourceArray of sourceArrays) {
  674. result.set(sourceArray, offset);
  675. offset += sourceArray.byteLength;
  676. }
  677. return result.buffer;
  678. }
  679. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  680. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  681. const arrayCopy = new Uint8Array(subArray);
  682. return arrayCopy.buffer;
  683. }
  684. function padToNBytes(byteLength, padding) {
  685. assert$7(byteLength >= 0);
  686. assert$7(padding > 0);
  687. return byteLength + (padding - 1) & ~(padding - 1);
  688. }
  689. function copyToArray(source, target, targetOffset) {
  690. let sourceArray;
  691. if (source instanceof ArrayBuffer) {
  692. sourceArray = new Uint8Array(source);
  693. } else {
  694. const srcByteOffset = source.byteOffset;
  695. const srcByteLength = source.byteLength;
  696. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  697. }
  698. target.set(sourceArray, targetOffset);
  699. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  700. }
  701. async function concatenateArrayBuffersAsync(asyncIterator) {
  702. const arrayBuffers = [];
  703. for await (const chunk of asyncIterator) {
  704. arrayBuffers.push(chunk);
  705. }
  706. return concatenateArrayBuffers(...arrayBuffers);
  707. }
  708. function getHiResTimestamp$1() {
  709. let timestamp;
  710. if (typeof window !== 'undefined' && window.performance) {
  711. timestamp = window.performance.now();
  712. } else if (typeof process !== 'undefined' && process.hrtime) {
  713. const timeParts = process.hrtime();
  714. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  715. } else {
  716. timestamp = Date.now();
  717. }
  718. return timestamp;
  719. }
  720. class Stat {
  721. constructor(name, type) {
  722. _defineProperty(this, "name", void 0);
  723. _defineProperty(this, "type", void 0);
  724. _defineProperty(this, "sampleSize", 1);
  725. _defineProperty(this, "time", void 0);
  726. _defineProperty(this, "count", void 0);
  727. _defineProperty(this, "samples", void 0);
  728. _defineProperty(this, "lastTiming", void 0);
  729. _defineProperty(this, "lastSampleTime", void 0);
  730. _defineProperty(this, "lastSampleCount", void 0);
  731. _defineProperty(this, "_count", 0);
  732. _defineProperty(this, "_time", 0);
  733. _defineProperty(this, "_samples", 0);
  734. _defineProperty(this, "_startTime", 0);
  735. _defineProperty(this, "_timerPending", false);
  736. this.name = name;
  737. this.type = type;
  738. this.reset();
  739. }
  740. setSampleSize(samples) {
  741. this.sampleSize = samples;
  742. return this;
  743. }
  744. incrementCount() {
  745. this.addCount(1);
  746. return this;
  747. }
  748. decrementCount() {
  749. this.subtractCount(1);
  750. return this;
  751. }
  752. addCount(value) {
  753. this._count += value;
  754. this._samples++;
  755. this._checkSampling();
  756. return this;
  757. }
  758. subtractCount(value) {
  759. this._count -= value;
  760. this._samples++;
  761. this._checkSampling();
  762. return this;
  763. }
  764. addTime(time) {
  765. this._time += time;
  766. this.lastTiming = time;
  767. this._samples++;
  768. this._checkSampling();
  769. return this;
  770. }
  771. timeStart() {
  772. this._startTime = getHiResTimestamp$1();
  773. this._timerPending = true;
  774. return this;
  775. }
  776. timeEnd() {
  777. if (!this._timerPending) {
  778. return this;
  779. }
  780. this.addTime(getHiResTimestamp$1() - this._startTime);
  781. this._timerPending = false;
  782. this._checkSampling();
  783. return this;
  784. }
  785. getSampleAverageCount() {
  786. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  787. }
  788. getSampleAverageTime() {
  789. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  790. }
  791. getSampleHz() {
  792. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  793. }
  794. getAverageCount() {
  795. return this.samples > 0 ? this.count / this.samples : 0;
  796. }
  797. getAverageTime() {
  798. return this.samples > 0 ? this.time / this.samples : 0;
  799. }
  800. getHz() {
  801. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  802. }
  803. reset() {
  804. this.time = 0;
  805. this.count = 0;
  806. this.samples = 0;
  807. this.lastTiming = 0;
  808. this.lastSampleTime = 0;
  809. this.lastSampleCount = 0;
  810. this._count = 0;
  811. this._time = 0;
  812. this._samples = 0;
  813. this._startTime = 0;
  814. this._timerPending = false;
  815. return this;
  816. }
  817. _checkSampling() {
  818. if (this._samples === this.sampleSize) {
  819. this.lastSampleTime = this._time;
  820. this.lastSampleCount = this._count;
  821. this.count += this._count;
  822. this.time += this._time;
  823. this.samples += this._samples;
  824. this._time = 0;
  825. this._count = 0;
  826. this._samples = 0;
  827. }
  828. }
  829. }
  830. class Stats {
  831. constructor(options) {
  832. _defineProperty(this, "id", void 0);
  833. _defineProperty(this, "stats", {});
  834. this.id = options.id;
  835. this.stats = {};
  836. this._initializeStats(options.stats);
  837. Object.seal(this);
  838. }
  839. get(name) {
  840. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  841. return this._getOrCreate({
  842. name,
  843. type
  844. });
  845. }
  846. get size() {
  847. return Object.keys(this.stats).length;
  848. }
  849. reset() {
  850. for (const key in this.stats) {
  851. this.stats[key].reset();
  852. }
  853. return this;
  854. }
  855. forEach(fn) {
  856. for (const key in this.stats) {
  857. fn(this.stats[key]);
  858. }
  859. }
  860. getTable() {
  861. const table = {};
  862. this.forEach(stat => {
  863. table[stat.name] = {
  864. time: stat.time || 0,
  865. count: stat.count || 0,
  866. average: stat.getAverageTime() || 0,
  867. hz: stat.getHz() || 0
  868. };
  869. });
  870. return table;
  871. }
  872. _initializeStats() {
  873. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  874. stats.forEach(stat => this._getOrCreate(stat));
  875. }
  876. _getOrCreate(stat) {
  877. if (!stat || !stat.name) {
  878. return null;
  879. }
  880. const {
  881. name,
  882. type
  883. } = stat;
  884. if (!this.stats[name]) {
  885. if (stat instanceof Stat) {
  886. this.stats[name] = stat;
  887. } else {
  888. this.stats[name] = new Stat(name, type);
  889. }
  890. }
  891. return this.stats[name];
  892. }
  893. }
  894. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  895. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  896. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  897. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  898. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  899. const DEFAULT_PROPS$2 = {
  900. id: 'request-scheduler',
  901. throttleRequests: true,
  902. maxRequests: 6
  903. };
  904. class RequestScheduler {
  905. constructor(props = {}) {
  906. _defineProperty(this, "props", void 0);
  907. _defineProperty(this, "stats", void 0);
  908. _defineProperty(this, "activeRequestCount", 0);
  909. _defineProperty(this, "requestQueue", []);
  910. _defineProperty(this, "requestMap", new Map());
  911. _defineProperty(this, "deferredUpdate", null);
  912. this.props = { ...DEFAULT_PROPS$2,
  913. ...props
  914. };
  915. this.stats = new Stats({
  916. id: this.props.id
  917. });
  918. this.stats.get(STAT_QUEUED_REQUESTS);
  919. this.stats.get(STAT_ACTIVE_REQUESTS);
  920. this.stats.get(STAT_CANCELLED_REQUESTS);
  921. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  922. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  923. }
  924. scheduleRequest(handle, getPriority = () => 0) {
  925. if (!this.props.throttleRequests) {
  926. return Promise.resolve({
  927. done: () => {}
  928. });
  929. }
  930. if (this.requestMap.has(handle)) {
  931. return this.requestMap.get(handle);
  932. }
  933. const request = {
  934. handle,
  935. priority: 0,
  936. getPriority
  937. };
  938. const promise = new Promise(resolve => {
  939. request.resolve = resolve;
  940. return request;
  941. });
  942. this.requestQueue.push(request);
  943. this.requestMap.set(handle, promise);
  944. this._issueNewRequests();
  945. return promise;
  946. }
  947. _issueRequest(request) {
  948. const {
  949. handle,
  950. resolve
  951. } = request;
  952. let isDone = false;
  953. const done = () => {
  954. if (!isDone) {
  955. isDone = true;
  956. this.requestMap.delete(handle);
  957. this.activeRequestCount--;
  958. this._issueNewRequests();
  959. }
  960. };
  961. this.activeRequestCount++;
  962. return resolve ? resolve({
  963. done
  964. }) : Promise.resolve({
  965. done
  966. });
  967. }
  968. _issueNewRequests() {
  969. if (!this.deferredUpdate) {
  970. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  971. }
  972. }
  973. _issueNewRequestsAsync() {
  974. this.deferredUpdate = null;
  975. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  976. if (freeSlots === 0) {
  977. return;
  978. }
  979. this._updateAllRequests();
  980. for (let i = 0; i < freeSlots; ++i) {
  981. const request = this.requestQueue.shift();
  982. if (request) {
  983. this._issueRequest(request);
  984. }
  985. }
  986. }
  987. _updateAllRequests() {
  988. const requestQueue = this.requestQueue;
  989. for (let i = 0; i < requestQueue.length; ++i) {
  990. const request = requestQueue[i];
  991. if (!this._updateRequest(request)) {
  992. requestQueue.splice(i, 1);
  993. this.requestMap.delete(request.handle);
  994. i--;
  995. }
  996. }
  997. requestQueue.sort((a, b) => a.priority - b.priority);
  998. }
  999. _updateRequest(request) {
  1000. request.priority = request.getPriority(request.handle);
  1001. if (request.priority < 0) {
  1002. request.resolve(null);
  1003. return false;
  1004. }
  1005. return true;
  1006. }
  1007. }
  1008. let pathPrefix = '';
  1009. const fileAliases = {};
  1010. function resolvePath(filename) {
  1011. for (const alias in fileAliases) {
  1012. if (filename.startsWith(alias)) {
  1013. const replacement = fileAliases[alias];
  1014. filename = filename.replace(alias, replacement);
  1015. }
  1016. }
  1017. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1018. filename = "".concat(pathPrefix).concat(filename);
  1019. }
  1020. return filename;
  1021. }
  1022. function filename(url) {
  1023. const slashIndex = url && url.lastIndexOf('/');
  1024. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1025. }
  1026. function dirname(url) {
  1027. const slashIndex = url && url.lastIndexOf('/');
  1028. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1029. }
  1030. const isBoolean = x => typeof x === 'boolean';
  1031. const isFunction = x => typeof x === 'function';
  1032. const isObject = x => x !== null && typeof x === 'object';
  1033. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1034. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1035. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1036. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1037. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1038. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1039. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1040. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1041. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1042. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1043. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1044. function parseMIMEType(mimeString) {
  1045. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1046. if (matches) {
  1047. return matches[1];
  1048. }
  1049. return mimeString;
  1050. }
  1051. function parseMIMETypeFromURL(url) {
  1052. const matches = DATA_URL_PATTERN.exec(url);
  1053. if (matches) {
  1054. return matches[1];
  1055. }
  1056. return '';
  1057. }
  1058. const QUERY_STRING_PATTERN = /\?.*/;
  1059. function getResourceUrlAndType(resource) {
  1060. if (isResponse(resource)) {
  1061. const url = stripQueryString(resource.url || '');
  1062. const contentTypeHeader = resource.headers.get('content-type') || '';
  1063. return {
  1064. url,
  1065. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1066. };
  1067. }
  1068. if (isBlob(resource)) {
  1069. return {
  1070. url: stripQueryString(resource.name || ''),
  1071. type: resource.type || ''
  1072. };
  1073. }
  1074. if (typeof resource === 'string') {
  1075. return {
  1076. url: stripQueryString(resource),
  1077. type: parseMIMETypeFromURL(resource)
  1078. };
  1079. }
  1080. return {
  1081. url: '',
  1082. type: ''
  1083. };
  1084. }
  1085. function getResourceContentLength(resource) {
  1086. if (isResponse(resource)) {
  1087. return resource.headers['content-length'] || -1;
  1088. }
  1089. if (isBlob(resource)) {
  1090. return resource.size;
  1091. }
  1092. if (typeof resource === 'string') {
  1093. return resource.length;
  1094. }
  1095. if (resource instanceof ArrayBuffer) {
  1096. return resource.byteLength;
  1097. }
  1098. if (ArrayBuffer.isView(resource)) {
  1099. return resource.byteLength;
  1100. }
  1101. return -1;
  1102. }
  1103. function stripQueryString(url) {
  1104. return url.replace(QUERY_STRING_PATTERN, '');
  1105. }
  1106. async function makeResponse(resource) {
  1107. if (isResponse(resource)) {
  1108. return resource;
  1109. }
  1110. const headers = {};
  1111. const contentLength = getResourceContentLength(resource);
  1112. if (contentLength >= 0) {
  1113. headers['content-length'] = String(contentLength);
  1114. }
  1115. const {
  1116. url,
  1117. type
  1118. } = getResourceUrlAndType(resource);
  1119. if (type) {
  1120. headers['content-type'] = type;
  1121. }
  1122. const initialDataUrl = await getInitialDataUrl(resource);
  1123. if (initialDataUrl) {
  1124. headers['x-first-bytes'] = initialDataUrl;
  1125. }
  1126. if (typeof resource === 'string') {
  1127. resource = new TextEncoder().encode(resource);
  1128. }
  1129. const response = new Response(resource, {
  1130. headers
  1131. });
  1132. Object.defineProperty(response, 'url', {
  1133. value: url
  1134. });
  1135. return response;
  1136. }
  1137. async function checkResponse(response) {
  1138. if (!response.ok) {
  1139. const message = await getResponseError(response);
  1140. throw new Error(message);
  1141. }
  1142. }
  1143. async function getResponseError(response) {
  1144. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1145. try {
  1146. const contentType = response.headers.get('Content-Type');
  1147. let text = response.statusText;
  1148. if (contentType.includes('application/json')) {
  1149. text += " ".concat(await response.text());
  1150. }
  1151. message += text;
  1152. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1153. } catch (error) {}
  1154. return message;
  1155. }
  1156. async function getInitialDataUrl(resource) {
  1157. const INITIAL_DATA_LENGTH = 5;
  1158. if (typeof resource === 'string') {
  1159. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1160. }
  1161. if (resource instanceof Blob) {
  1162. const blobSlice = resource.slice(0, 5);
  1163. return await new Promise(resolve => {
  1164. const reader = new FileReader();
  1165. reader.onload = event => {
  1166. var _event$target;
  1167. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1168. };
  1169. reader.readAsDataURL(blobSlice);
  1170. });
  1171. }
  1172. if (resource instanceof ArrayBuffer) {
  1173. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1174. const base64 = arrayBufferToBase64(slice);
  1175. return "data:base64,".concat(base64);
  1176. }
  1177. return null;
  1178. }
  1179. function arrayBufferToBase64(buffer) {
  1180. let binary = '';
  1181. const bytes = new Uint8Array(buffer);
  1182. for (let i = 0; i < bytes.byteLength; i++) {
  1183. binary += String.fromCharCode(bytes[i]);
  1184. }
  1185. return btoa(binary);
  1186. }
  1187. async function fetchFile(url, options) {
  1188. if (typeof url === 'string') {
  1189. url = resolvePath(url);
  1190. let fetchOptions = options;
  1191. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1192. fetchOptions = options.fetch;
  1193. }
  1194. return await fetch(url, fetchOptions);
  1195. }
  1196. return await makeResponse(url);
  1197. }
  1198. function isElectron(mockUserAgent) {
  1199. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1200. return true;
  1201. }
  1202. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1203. return true;
  1204. }
  1205. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1206. const userAgent = mockUserAgent || realUserAgent;
  1207. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1208. return true;
  1209. }
  1210. return false;
  1211. }
  1212. function isBrowser() {
  1213. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1214. return !isNode || isElectron();
  1215. }
  1216. const globals = {
  1217. self: typeof self !== 'undefined' && self,
  1218. window: typeof window !== 'undefined' && window,
  1219. global: typeof global !== 'undefined' && global,
  1220. document: typeof document !== 'undefined' && document,
  1221. process: typeof process === 'object' && process
  1222. };
  1223. const window_ = globals.window || globals.self || globals.global;
  1224. const process_ = globals.process || {};
  1225. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1226. isBrowser();
  1227. function getStorage(type) {
  1228. try {
  1229. const storage = window[type];
  1230. const x = '__storage_test__';
  1231. storage.setItem(x, x);
  1232. storage.removeItem(x);
  1233. return storage;
  1234. } catch (e) {
  1235. return null;
  1236. }
  1237. }
  1238. class LocalStorage {
  1239. constructor(id) {
  1240. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1241. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1242. _defineProperty(this, "storage", void 0);
  1243. _defineProperty(this, "id", void 0);
  1244. _defineProperty(this, "config", {});
  1245. this.storage = getStorage(type);
  1246. this.id = id;
  1247. this.config = {};
  1248. Object.assign(this.config, defaultSettings);
  1249. this._loadConfiguration();
  1250. }
  1251. getConfiguration() {
  1252. return this.config;
  1253. }
  1254. setConfiguration(configuration) {
  1255. this.config = {};
  1256. return this.updateConfiguration(configuration);
  1257. }
  1258. updateConfiguration(configuration) {
  1259. Object.assign(this.config, configuration);
  1260. if (this.storage) {
  1261. const serialized = JSON.stringify(this.config);
  1262. this.storage.setItem(this.id, serialized);
  1263. }
  1264. return this;
  1265. }
  1266. _loadConfiguration() {
  1267. let configuration = {};
  1268. if (this.storage) {
  1269. const serializedConfiguration = this.storage.getItem(this.id);
  1270. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1271. }
  1272. Object.assign(this.config, configuration);
  1273. return this;
  1274. }
  1275. }
  1276. function formatTime(ms) {
  1277. let formatted;
  1278. if (ms < 10) {
  1279. formatted = "".concat(ms.toFixed(2), "ms");
  1280. } else if (ms < 100) {
  1281. formatted = "".concat(ms.toFixed(1), "ms");
  1282. } else if (ms < 1000) {
  1283. formatted = "".concat(ms.toFixed(0), "ms");
  1284. } else {
  1285. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1286. }
  1287. return formatted;
  1288. }
  1289. function leftPad(string) {
  1290. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1291. const padLength = Math.max(length - string.length, 0);
  1292. return "".concat(' '.repeat(padLength)).concat(string);
  1293. }
  1294. function formatImage(image, message, scale) {
  1295. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1296. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1297. if (image.width > maxWidth) {
  1298. scale = Math.min(scale, maxWidth / image.width);
  1299. }
  1300. const width = image.width * scale;
  1301. const height = image.height * scale;
  1302. 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('');
  1303. return ["".concat(message, " %c+"), style];
  1304. }
  1305. let COLOR;
  1306. (function (COLOR) {
  1307. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1308. COLOR[COLOR["RED"] = 31] = "RED";
  1309. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1310. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1311. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1312. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1313. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1314. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1315. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1316. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1317. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1318. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1319. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1320. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1321. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1322. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1323. })(COLOR || (COLOR = {}));
  1324. function getColor(color) {
  1325. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1326. }
  1327. function addColor(string, color, background) {
  1328. if (!isBrowser && typeof string === 'string') {
  1329. if (color) {
  1330. color = getColor(color);
  1331. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1332. }
  1333. if (background) {
  1334. color = getColor(background);
  1335. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1336. }
  1337. }
  1338. return string;
  1339. }
  1340. function autobind(obj) {
  1341. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1342. const proto = Object.getPrototypeOf(obj);
  1343. const propNames = Object.getOwnPropertyNames(proto);
  1344. for (const key of propNames) {
  1345. if (typeof obj[key] === 'function') {
  1346. if (!predefined.find(name => key === name)) {
  1347. obj[key] = obj[key].bind(obj);
  1348. }
  1349. }
  1350. }
  1351. }
  1352. function assert$5(condition, message) {
  1353. if (!condition) {
  1354. throw new Error(message || 'Assertion failed');
  1355. }
  1356. }
  1357. function getHiResTimestamp() {
  1358. let timestamp;
  1359. if (isBrowser && 'performance' in window_) {
  1360. var _window$performance, _window$performance$n;
  1361. 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);
  1362. } else if ('hrtime' in process_) {
  1363. var _process$hrtime;
  1364. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1365. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1366. } else {
  1367. timestamp = Date.now();
  1368. }
  1369. return timestamp;
  1370. }
  1371. const originalConsole = {
  1372. debug: isBrowser ? console.debug || console.log : console.log,
  1373. log: console.log,
  1374. info: console.info,
  1375. warn: console.warn,
  1376. error: console.error
  1377. };
  1378. const DEFAULT_SETTINGS = {
  1379. enabled: true,
  1380. level: 0
  1381. };
  1382. function noop$1() {}
  1383. const cache = {};
  1384. const ONCE = {
  1385. once: true
  1386. };
  1387. class Log {
  1388. constructor() {
  1389. let {
  1390. id
  1391. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1392. id: ''
  1393. };
  1394. _defineProperty(this, "id", void 0);
  1395. _defineProperty(this, "VERSION", VERSION$6);
  1396. _defineProperty(this, "_startTs", getHiResTimestamp());
  1397. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1398. _defineProperty(this, "_storage", void 0);
  1399. _defineProperty(this, "userData", {});
  1400. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1401. this.id = id;
  1402. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1403. this.userData = {};
  1404. this.timeStamp("".concat(this.id, " started"));
  1405. autobind(this);
  1406. Object.seal(this);
  1407. }
  1408. set level(newLevel) {
  1409. this.setLevel(newLevel);
  1410. }
  1411. get level() {
  1412. return this.getLevel();
  1413. }
  1414. isEnabled() {
  1415. return this._storage.config.enabled;
  1416. }
  1417. getLevel() {
  1418. return this._storage.config.level;
  1419. }
  1420. getTotal() {
  1421. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1422. }
  1423. getDelta() {
  1424. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1425. }
  1426. set priority(newPriority) {
  1427. this.level = newPriority;
  1428. }
  1429. get priority() {
  1430. return this.level;
  1431. }
  1432. getPriority() {
  1433. return this.level;
  1434. }
  1435. enable() {
  1436. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1437. this._storage.updateConfiguration({
  1438. enabled
  1439. });
  1440. return this;
  1441. }
  1442. setLevel(level) {
  1443. this._storage.updateConfiguration({
  1444. level
  1445. });
  1446. return this;
  1447. }
  1448. get(setting) {
  1449. return this._storage.config[setting];
  1450. }
  1451. set(setting, value) {
  1452. this._storage.updateConfiguration({
  1453. [setting]: value
  1454. });
  1455. }
  1456. settings() {
  1457. if (console.table) {
  1458. console.table(this._storage.config);
  1459. } else {
  1460. console.log(this._storage.config);
  1461. }
  1462. }
  1463. assert(condition, message) {
  1464. assert$5(condition, message);
  1465. }
  1466. warn(message) {
  1467. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1468. }
  1469. error(message) {
  1470. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1471. }
  1472. deprecated(oldUsage, newUsage) {
  1473. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1474. }
  1475. removed(oldUsage, newUsage) {
  1476. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1477. }
  1478. probe(logLevel, message) {
  1479. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1480. time: true,
  1481. once: true
  1482. });
  1483. }
  1484. log(logLevel, message) {
  1485. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1486. }
  1487. info(logLevel, message) {
  1488. return this._getLogFunction(logLevel, message, console.info, arguments);
  1489. }
  1490. once(logLevel, message) {
  1491. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1492. args[_key - 2] = arguments[_key];
  1493. }
  1494. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1495. }
  1496. table(logLevel, table, columns) {
  1497. if (table) {
  1498. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1499. tag: getTableHeader(table)
  1500. });
  1501. }
  1502. return noop$1;
  1503. }
  1504. image(_ref) {
  1505. let {
  1506. logLevel,
  1507. priority,
  1508. image,
  1509. message = '',
  1510. scale = 1
  1511. } = _ref;
  1512. if (!this._shouldLog(logLevel || priority)) {
  1513. return noop$1;
  1514. }
  1515. return isBrowser ? logImageInBrowser({
  1516. image,
  1517. message,
  1518. scale
  1519. }) : logImageInNode({
  1520. image,
  1521. message,
  1522. scale
  1523. });
  1524. }
  1525. time(logLevel, message) {
  1526. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1527. }
  1528. timeEnd(logLevel, message) {
  1529. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1530. }
  1531. timeStamp(logLevel, message) {
  1532. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1533. }
  1534. group(logLevel, message) {
  1535. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1536. collapsed: false
  1537. };
  1538. const options = normalizeArguments({
  1539. logLevel,
  1540. message,
  1541. opts
  1542. });
  1543. const {
  1544. collapsed
  1545. } = opts;
  1546. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1547. return this._getLogFunction(options);
  1548. }
  1549. groupCollapsed(logLevel, message) {
  1550. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1551. return this.group(logLevel, message, Object.assign({}, opts, {
  1552. collapsed: true
  1553. }));
  1554. }
  1555. groupEnd(logLevel) {
  1556. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1557. }
  1558. withGroup(logLevel, message, func) {
  1559. this.group(logLevel, message)();
  1560. try {
  1561. func();
  1562. } finally {
  1563. this.groupEnd(logLevel)();
  1564. }
  1565. }
  1566. trace() {
  1567. if (console.trace) {
  1568. console.trace();
  1569. }
  1570. }
  1571. _shouldLog(logLevel) {
  1572. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1573. }
  1574. _getLogFunction(logLevel, message, method, args, opts) {
  1575. if (this._shouldLog(logLevel)) {
  1576. opts = normalizeArguments({
  1577. logLevel,
  1578. message,
  1579. args,
  1580. opts
  1581. });
  1582. method = method || opts.method;
  1583. assert$5(method);
  1584. opts.total = this.getTotal();
  1585. opts.delta = this.getDelta();
  1586. this._deltaTs = getHiResTimestamp();
  1587. const tag = opts.tag || opts.message;
  1588. if (opts.once) {
  1589. if (!cache[tag]) {
  1590. cache[tag] = getHiResTimestamp();
  1591. } else {
  1592. return noop$1;
  1593. }
  1594. }
  1595. message = decorateMessage(this.id, opts.message, opts);
  1596. return method.bind(console, message, ...opts.args);
  1597. }
  1598. return noop$1;
  1599. }
  1600. }
  1601. _defineProperty(Log, "VERSION", VERSION$6);
  1602. function normalizeLogLevel(logLevel) {
  1603. if (!logLevel) {
  1604. return 0;
  1605. }
  1606. let resolvedLevel;
  1607. switch (typeof logLevel) {
  1608. case 'number':
  1609. resolvedLevel = logLevel;
  1610. break;
  1611. case 'object':
  1612. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1613. break;
  1614. default:
  1615. return 0;
  1616. }
  1617. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1618. return resolvedLevel;
  1619. }
  1620. function normalizeArguments(opts) {
  1621. const {
  1622. logLevel,
  1623. message
  1624. } = opts;
  1625. opts.logLevel = normalizeLogLevel(logLevel);
  1626. const args = opts.args ? Array.from(opts.args) : [];
  1627. while (args.length && args.shift() !== message) {}
  1628. switch (typeof logLevel) {
  1629. case 'string':
  1630. case 'function':
  1631. if (message !== undefined) {
  1632. args.unshift(message);
  1633. }
  1634. opts.message = logLevel;
  1635. break;
  1636. case 'object':
  1637. Object.assign(opts, logLevel);
  1638. break;
  1639. }
  1640. if (typeof opts.message === 'function') {
  1641. opts.message = opts.message();
  1642. }
  1643. const messageType = typeof opts.message;
  1644. assert$5(messageType === 'string' || messageType === 'object');
  1645. return Object.assign(opts, {
  1646. args
  1647. }, opts.opts);
  1648. }
  1649. function decorateMessage(id, message, opts) {
  1650. if (typeof message === 'string') {
  1651. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1652. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1653. message = addColor(message, opts.color, opts.background);
  1654. }
  1655. return message;
  1656. }
  1657. function logImageInNode(_ref2) {
  1658. let {
  1659. image,
  1660. message = '',
  1661. scale = 1
  1662. } = _ref2;
  1663. let asciify = null;
  1664. try {
  1665. asciify = module.require('asciify-image');
  1666. } catch (error) {}
  1667. if (asciify) {
  1668. return () => asciify(image, {
  1669. fit: 'box',
  1670. width: "".concat(Math.round(80 * scale), "%")
  1671. }).then(data => console.log(data));
  1672. }
  1673. return noop$1;
  1674. }
  1675. function logImageInBrowser(_ref3) {
  1676. let {
  1677. image,
  1678. message = '',
  1679. scale = 1
  1680. } = _ref3;
  1681. if (typeof image === 'string') {
  1682. const img = new Image();
  1683. img.onload = () => {
  1684. const args = formatImage(img, message, scale);
  1685. console.log(...args);
  1686. };
  1687. img.src = image;
  1688. return noop$1;
  1689. }
  1690. const element = image.nodeName || '';
  1691. if (element.toLowerCase() === 'img') {
  1692. console.log(...formatImage(image, message, scale));
  1693. return noop$1;
  1694. }
  1695. if (element.toLowerCase() === 'canvas') {
  1696. const img = new Image();
  1697. img.onload = () => console.log(...formatImage(img, message, scale));
  1698. img.src = image.toDataURL();
  1699. return noop$1;
  1700. }
  1701. return noop$1;
  1702. }
  1703. function getTableHeader(table) {
  1704. for (const key in table) {
  1705. for (const title in table[key]) {
  1706. return title || 'untitled';
  1707. }
  1708. }
  1709. return 'empty';
  1710. }
  1711. const probeLog = new Log({
  1712. id: 'loaders.gl'
  1713. });
  1714. class NullLog {
  1715. log() {
  1716. return () => {};
  1717. }
  1718. info() {
  1719. return () => {};
  1720. }
  1721. warn() {
  1722. return () => {};
  1723. }
  1724. error() {
  1725. return () => {};
  1726. }
  1727. }
  1728. class ConsoleLog {
  1729. constructor() {
  1730. _defineProperty(this, "console", void 0);
  1731. this.console = console;
  1732. }
  1733. log(...args) {
  1734. return this.console.log.bind(this.console, ...args);
  1735. }
  1736. info(...args) {
  1737. return this.console.info.bind(this.console, ...args);
  1738. }
  1739. warn(...args) {
  1740. return this.console.warn.bind(this.console, ...args);
  1741. }
  1742. error(...args) {
  1743. return this.console.error.bind(this.console, ...args);
  1744. }
  1745. }
  1746. const DEFAULT_LOADER_OPTIONS = {
  1747. fetch: null,
  1748. mimeType: undefined,
  1749. nothrow: false,
  1750. log: new ConsoleLog(),
  1751. CDN: 'https://unpkg.com/@loaders.gl',
  1752. worker: true,
  1753. maxConcurrency: 3,
  1754. maxMobileConcurrency: 1,
  1755. reuseWorkers: true,
  1756. _workerType: '',
  1757. limit: 0,
  1758. _limitMB: 0,
  1759. batchSize: 'auto',
  1760. batchDebounceMs: 0,
  1761. metadata: false,
  1762. transforms: []
  1763. };
  1764. const REMOVED_LOADER_OPTIONS = {
  1765. throws: 'nothrow',
  1766. dataType: '(no longer used)',
  1767. uri: 'baseUri',
  1768. method: 'fetch.method',
  1769. headers: 'fetch.headers',
  1770. body: 'fetch.body',
  1771. mode: 'fetch.mode',
  1772. credentials: 'fetch.credentials',
  1773. cache: 'fetch.cache',
  1774. redirect: 'fetch.redirect',
  1775. referrer: 'fetch.referrer',
  1776. referrerPolicy: 'fetch.referrerPolicy',
  1777. integrity: 'fetch.integrity',
  1778. keepalive: 'fetch.keepalive',
  1779. signal: 'fetch.signal'
  1780. };
  1781. function getGlobalLoaderState() {
  1782. globalThis.loaders = globalThis.loaders || {};
  1783. const {
  1784. loaders
  1785. } = globalThis;
  1786. loaders._state = loaders._state || {};
  1787. return loaders._state;
  1788. }
  1789. const getGlobalLoaderOptions = () => {
  1790. const state = getGlobalLoaderState();
  1791. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1792. };
  1793. return state.globalOptions;
  1794. };
  1795. function normalizeOptions(options, loader, loaders, url) {
  1796. loaders = loaders || [];
  1797. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1798. validateOptions(options, loaders);
  1799. return normalizeOptionsInternal(loader, options, url);
  1800. }
  1801. function getFetchFunction(options, context) {
  1802. const globalOptions = getGlobalLoaderOptions();
  1803. const fetchOptions = options || globalOptions;
  1804. if (typeof fetchOptions.fetch === 'function') {
  1805. return fetchOptions.fetch;
  1806. }
  1807. if (isObject(fetchOptions.fetch)) {
  1808. return url => fetchFile(url, fetchOptions);
  1809. }
  1810. if (context !== null && context !== void 0 && context.fetch) {
  1811. return context === null || context === void 0 ? void 0 : context.fetch;
  1812. }
  1813. return fetchFile;
  1814. }
  1815. function validateOptions(options, loaders) {
  1816. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1817. for (const loader of loaders) {
  1818. const idOptions = options && options[loader.id] || {};
  1819. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1820. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1821. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1822. }
  1823. }
  1824. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1825. const loaderName = id || 'Top level';
  1826. const prefix = id ? "".concat(id, ".") : '';
  1827. for (const key in options) {
  1828. const isSubOptions = !id && isObject(options[key]);
  1829. const isBaseUriOption = key === 'baseUri' && !id;
  1830. const isWorkerUrlOption = key === 'workerUrl' && id;
  1831. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1832. if (key in deprecatedOptions) {
  1833. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1834. } else if (!isSubOptions) {
  1835. const suggestion = findSimilarOption(key, loaders);
  1836. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1837. }
  1838. }
  1839. }
  1840. }
  1841. function findSimilarOption(optionKey, loaders) {
  1842. const lowerCaseOptionKey = optionKey.toLowerCase();
  1843. let bestSuggestion = '';
  1844. for (const loader of loaders) {
  1845. for (const key in loader.options) {
  1846. if (optionKey === key) {
  1847. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1848. }
  1849. const lowerCaseKey = key.toLowerCase();
  1850. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1851. if (isPartialMatch) {
  1852. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1853. }
  1854. }
  1855. }
  1856. return bestSuggestion;
  1857. }
  1858. function normalizeOptionsInternal(loader, options, url) {
  1859. const loaderDefaultOptions = loader.options || {};
  1860. const mergedOptions = { ...loaderDefaultOptions
  1861. };
  1862. addUrlOptions(mergedOptions, url);
  1863. if (mergedOptions.log === null) {
  1864. mergedOptions.log = new NullLog();
  1865. }
  1866. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1867. mergeNestedFields(mergedOptions, options);
  1868. return mergedOptions;
  1869. }
  1870. function mergeNestedFields(mergedOptions, options) {
  1871. for (const key in options) {
  1872. if (key in options) {
  1873. const value = options[key];
  1874. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1875. mergedOptions[key] = { ...mergedOptions[key],
  1876. ...options[key]
  1877. };
  1878. } else {
  1879. mergedOptions[key] = options[key];
  1880. }
  1881. }
  1882. }
  1883. }
  1884. function addUrlOptions(options, url) {
  1885. if (url && !('baseUri' in options)) {
  1886. options.baseUri = url;
  1887. }
  1888. }
  1889. function isLoaderObject(loader) {
  1890. var _loader;
  1891. if (!loader) {
  1892. return false;
  1893. }
  1894. if (Array.isArray(loader)) {
  1895. loader = loader[0];
  1896. }
  1897. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1898. return hasExtensions;
  1899. }
  1900. function normalizeLoader(loader) {
  1901. var _loader2, _loader3;
  1902. assert$7(loader, 'null loader');
  1903. assert$7(isLoaderObject(loader), 'invalid loader');
  1904. let options;
  1905. if (Array.isArray(loader)) {
  1906. options = loader[1];
  1907. loader = loader[0];
  1908. loader = { ...loader,
  1909. options: { ...loader.options,
  1910. ...options
  1911. }
  1912. };
  1913. }
  1914. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1915. loader.text = true;
  1916. }
  1917. if (!loader.text) {
  1918. loader.binary = true;
  1919. }
  1920. return loader;
  1921. }
  1922. const getGlobalLoaderRegistry = () => {
  1923. const state = getGlobalLoaderState();
  1924. state.loaderRegistry = state.loaderRegistry || [];
  1925. return state.loaderRegistry;
  1926. };
  1927. function getRegisteredLoaders() {
  1928. return getGlobalLoaderRegistry();
  1929. }
  1930. const EXT_PATTERN = /\.([^.]+)$/;
  1931. async function selectLoader(data, loaders = [], options, context) {
  1932. if (!validHTTPResponse(data)) {
  1933. return null;
  1934. }
  1935. let loader = selectLoaderSync(data, loaders, { ...options,
  1936. nothrow: true
  1937. }, context);
  1938. if (loader) {
  1939. return loader;
  1940. }
  1941. if (isBlob(data)) {
  1942. data = await data.slice(0, 10).arrayBuffer();
  1943. loader = selectLoaderSync(data, loaders, options, context);
  1944. }
  1945. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1946. throw new Error(getNoValidLoaderMessage(data));
  1947. }
  1948. return loader;
  1949. }
  1950. function selectLoaderSync(data, loaders = [], options, context) {
  1951. if (!validHTTPResponse(data)) {
  1952. return null;
  1953. }
  1954. if (loaders && !Array.isArray(loaders)) {
  1955. return normalizeLoader(loaders);
  1956. }
  1957. let candidateLoaders = [];
  1958. if (loaders) {
  1959. candidateLoaders = candidateLoaders.concat(loaders);
  1960. }
  1961. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1962. candidateLoaders.push(...getRegisteredLoaders());
  1963. }
  1964. normalizeLoaders(candidateLoaders);
  1965. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1966. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1967. throw new Error(getNoValidLoaderMessage(data));
  1968. }
  1969. return loader;
  1970. }
  1971. function selectLoaderInternal(data, loaders, options, context) {
  1972. const {
  1973. url,
  1974. type
  1975. } = getResourceUrlAndType(data);
  1976. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1977. let loader = null;
  1978. if (options !== null && options !== void 0 && options.mimeType) {
  1979. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  1980. }
  1981. loader = loader || findLoaderByUrl(loaders, testUrl);
  1982. loader = loader || findLoaderByMIMEType(loaders, type);
  1983. loader = loader || findLoaderByInitialBytes(loaders, data);
  1984. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  1985. return loader;
  1986. }
  1987. function validHTTPResponse(data) {
  1988. if (data instanceof Response) {
  1989. if (data.status === 204) {
  1990. return false;
  1991. }
  1992. }
  1993. return true;
  1994. }
  1995. function getNoValidLoaderMessage(data) {
  1996. const {
  1997. url,
  1998. type
  1999. } = getResourceUrlAndType(data);
  2000. let message = 'No valid loader found (';
  2001. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2002. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2003. const firstCharacters = data ? getFirstCharacters(data) : '';
  2004. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2005. message += ')';
  2006. return message;
  2007. }
  2008. function normalizeLoaders(loaders) {
  2009. for (const loader of loaders) {
  2010. normalizeLoader(loader);
  2011. }
  2012. }
  2013. function findLoaderByUrl(loaders, url) {
  2014. const match = url && EXT_PATTERN.exec(url);
  2015. const extension = match && match[1];
  2016. return extension ? findLoaderByExtension(loaders, extension) : null;
  2017. }
  2018. function findLoaderByExtension(loaders, extension) {
  2019. extension = extension.toLowerCase();
  2020. for (const loader of loaders) {
  2021. for (const loaderExtension of loader.extensions) {
  2022. if (loaderExtension.toLowerCase() === extension) {
  2023. return loader;
  2024. }
  2025. }
  2026. }
  2027. return null;
  2028. }
  2029. function findLoaderByMIMEType(loaders, mimeType) {
  2030. for (const loader of loaders) {
  2031. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2032. return loader;
  2033. }
  2034. if (mimeType === "application/x.".concat(loader.id)) {
  2035. return loader;
  2036. }
  2037. }
  2038. return null;
  2039. }
  2040. function findLoaderByInitialBytes(loaders, data) {
  2041. if (!data) {
  2042. return null;
  2043. }
  2044. for (const loader of loaders) {
  2045. if (typeof data === 'string') {
  2046. if (testDataAgainstText(data, loader)) {
  2047. return loader;
  2048. }
  2049. } else if (ArrayBuffer.isView(data)) {
  2050. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2051. return loader;
  2052. }
  2053. } else if (data instanceof ArrayBuffer) {
  2054. const byteOffset = 0;
  2055. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2056. return loader;
  2057. }
  2058. }
  2059. }
  2060. return null;
  2061. }
  2062. function testDataAgainstText(data, loader) {
  2063. if (loader.testText) {
  2064. return loader.testText(data);
  2065. }
  2066. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2067. return tests.some(test => data.startsWith(test));
  2068. }
  2069. function testDataAgainstBinary(data, byteOffset, loader) {
  2070. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2071. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2072. }
  2073. function testBinary(data, byteOffset, loader, test) {
  2074. if (test instanceof ArrayBuffer) {
  2075. return compareArrayBuffers(test, data, test.byteLength);
  2076. }
  2077. switch (typeof test) {
  2078. case 'function':
  2079. return test(data, loader);
  2080. case 'string':
  2081. const magic = getMagicString$2(data, byteOffset, test.length);
  2082. return test === magic;
  2083. default:
  2084. return false;
  2085. }
  2086. }
  2087. function getFirstCharacters(data, length = 5) {
  2088. if (typeof data === 'string') {
  2089. return data.slice(0, length);
  2090. } else if (ArrayBuffer.isView(data)) {
  2091. return getMagicString$2(data.buffer, data.byteOffset, length);
  2092. } else if (data instanceof ArrayBuffer) {
  2093. const byteOffset = 0;
  2094. return getMagicString$2(data, byteOffset, length);
  2095. }
  2096. return '';
  2097. }
  2098. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2099. if (arrayBuffer.byteLength < byteOffset + length) {
  2100. return '';
  2101. }
  2102. const dataView = new DataView(arrayBuffer);
  2103. let magic = '';
  2104. for (let i = 0; i < length; i++) {
  2105. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2106. }
  2107. return magic;
  2108. }
  2109. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2110. function* makeStringIterator(string, options) {
  2111. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2112. let offset = 0;
  2113. const textEncoder = new TextEncoder();
  2114. while (offset < string.length) {
  2115. const chunkLength = Math.min(string.length - offset, chunkSize);
  2116. const chunk = string.slice(offset, offset + chunkLength);
  2117. offset += chunkLength;
  2118. yield textEncoder.encode(chunk);
  2119. }
  2120. }
  2121. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2122. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2123. const {
  2124. chunkSize = DEFAULT_CHUNK_SIZE$1
  2125. } = options;
  2126. let byteOffset = 0;
  2127. while (byteOffset < arrayBuffer.byteLength) {
  2128. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2129. const chunk = new ArrayBuffer(chunkByteLength);
  2130. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2131. const chunkArray = new Uint8Array(chunk);
  2132. chunkArray.set(sourceArray);
  2133. byteOffset += chunkByteLength;
  2134. yield chunk;
  2135. }
  2136. }
  2137. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2138. async function* makeBlobIterator(blob, options) {
  2139. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2140. let offset = 0;
  2141. while (offset < blob.size) {
  2142. const end = offset + chunkSize;
  2143. const chunk = await blob.slice(offset, end).arrayBuffer();
  2144. offset = end;
  2145. yield chunk;
  2146. }
  2147. }
  2148. function makeStreamIterator(stream, options) {
  2149. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2150. }
  2151. async function* makeBrowserStreamIterator(stream, options) {
  2152. const reader = stream.getReader();
  2153. let nextBatchPromise;
  2154. try {
  2155. while (true) {
  2156. const currentBatchPromise = nextBatchPromise || reader.read();
  2157. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2158. nextBatchPromise = reader.read();
  2159. }
  2160. const {
  2161. done,
  2162. value
  2163. } = await currentBatchPromise;
  2164. if (done) {
  2165. return;
  2166. }
  2167. yield toArrayBuffer(value);
  2168. }
  2169. } catch (error) {
  2170. reader.releaseLock();
  2171. }
  2172. }
  2173. async function* makeNodeStreamIterator(stream, options) {
  2174. for await (const chunk of stream) {
  2175. yield toArrayBuffer(chunk);
  2176. }
  2177. }
  2178. function makeIterator(data, options) {
  2179. if (typeof data === 'string') {
  2180. return makeStringIterator(data, options);
  2181. }
  2182. if (data instanceof ArrayBuffer) {
  2183. return makeArrayBufferIterator(data, options);
  2184. }
  2185. if (isBlob(data)) {
  2186. return makeBlobIterator(data, options);
  2187. }
  2188. if (isReadableStream(data)) {
  2189. return makeStreamIterator(data, options);
  2190. }
  2191. if (isResponse(data)) {
  2192. const response = data;
  2193. return makeStreamIterator(response.body, options);
  2194. }
  2195. throw new Error('makeIterator');
  2196. }
  2197. const ERR_DATA = 'Cannot convert supplied data type';
  2198. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2199. if (loader.text && typeof data === 'string') {
  2200. return data;
  2201. }
  2202. if (isBuffer(data)) {
  2203. data = data.buffer;
  2204. }
  2205. if (data instanceof ArrayBuffer) {
  2206. const arrayBuffer = data;
  2207. if (loader.text && !loader.binary) {
  2208. const textDecoder = new TextDecoder('utf8');
  2209. return textDecoder.decode(arrayBuffer);
  2210. }
  2211. return arrayBuffer;
  2212. }
  2213. if (ArrayBuffer.isView(data)) {
  2214. if (loader.text && !loader.binary) {
  2215. const textDecoder = new TextDecoder('utf8');
  2216. return textDecoder.decode(data);
  2217. }
  2218. let arrayBuffer = data.buffer;
  2219. const byteLength = data.byteLength || data.length;
  2220. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2221. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2222. }
  2223. return arrayBuffer;
  2224. }
  2225. throw new Error(ERR_DATA);
  2226. }
  2227. async function getArrayBufferOrStringFromData(data, loader, options) {
  2228. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2229. if (typeof data === 'string' || isArrayBuffer) {
  2230. return getArrayBufferOrStringFromDataSync(data, loader);
  2231. }
  2232. if (isBlob(data)) {
  2233. data = await makeResponse(data);
  2234. }
  2235. if (isResponse(data)) {
  2236. const response = data;
  2237. await checkResponse(response);
  2238. return loader.binary ? await response.arrayBuffer() : await response.text();
  2239. }
  2240. if (isReadableStream(data)) {
  2241. data = makeIterator(data, options);
  2242. }
  2243. if (isIterable(data) || isAsyncIterable(data)) {
  2244. return concatenateArrayBuffersAsync(data);
  2245. }
  2246. throw new Error(ERR_DATA);
  2247. }
  2248. function getLoaderContext(context, options, previousContext = null) {
  2249. if (previousContext) {
  2250. return previousContext;
  2251. }
  2252. const resolvedContext = {
  2253. fetch: getFetchFunction(options, context),
  2254. ...context
  2255. };
  2256. if (!Array.isArray(resolvedContext.loaders)) {
  2257. resolvedContext.loaders = null;
  2258. }
  2259. return resolvedContext;
  2260. }
  2261. function getLoadersFromContext(loaders, context) {
  2262. if (!context && loaders && !Array.isArray(loaders)) {
  2263. return loaders;
  2264. }
  2265. let candidateLoaders;
  2266. if (loaders) {
  2267. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2268. }
  2269. if (context && context.loaders) {
  2270. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2271. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2272. }
  2273. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2274. }
  2275. async function parse$3(data, loaders, options, context) {
  2276. assert$6(!context || typeof context === 'object');
  2277. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2278. context = undefined;
  2279. options = loaders;
  2280. loaders = undefined;
  2281. }
  2282. data = await data;
  2283. options = options || {};
  2284. const {
  2285. url
  2286. } = getResourceUrlAndType(data);
  2287. const typedLoaders = loaders;
  2288. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2289. const loader = await selectLoader(data, candidateLoaders, options);
  2290. if (!loader) {
  2291. return null;
  2292. }
  2293. options = normalizeOptions(options, loader, candidateLoaders, url);
  2294. context = getLoaderContext({
  2295. url,
  2296. parse: parse$3,
  2297. loaders: candidateLoaders
  2298. }, options, context);
  2299. return await parseWithLoader(loader, data, options, context);
  2300. }
  2301. async function parseWithLoader(loader, data, options, context) {
  2302. validateWorkerVersion(loader);
  2303. data = await getArrayBufferOrStringFromData(data, loader, options);
  2304. if (loader.parseTextSync && typeof data === 'string') {
  2305. options.dataType = 'text';
  2306. return loader.parseTextSync(data, options, context, loader);
  2307. }
  2308. if (canParseWithWorker(loader, options)) {
  2309. return await parseWithWorker(loader, data, options, context, parse$3);
  2310. }
  2311. if (loader.parseText && typeof data === 'string') {
  2312. return await loader.parseText(data, options, context, loader);
  2313. }
  2314. if (loader.parse) {
  2315. return await loader.parse(data, options, context, loader);
  2316. }
  2317. assert$6(!loader.parseSync);
  2318. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2319. }
  2320. async function load(url, loaders, options, context) {
  2321. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2322. options = loaders;
  2323. loaders = undefined;
  2324. }
  2325. const fetch = getFetchFunction(options);
  2326. let data = url;
  2327. if (typeof url === 'string') {
  2328. data = await fetch(url);
  2329. }
  2330. if (isBlob(url)) {
  2331. data = await fetch(url);
  2332. }
  2333. return await parse$3(data, loaders, options);
  2334. }
  2335. function assert$4(condition, message) {
  2336. if (!condition) {
  2337. throw new Error("math.gl assertion ".concat(message));
  2338. }
  2339. }
  2340. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2341. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2342. const config = {};
  2343. config.EPSILON = 1e-12;
  2344. config.debug = false;
  2345. config.precision = 4;
  2346. config.printTypes = false;
  2347. config.printDegrees = false;
  2348. config.printRowMajor = true;
  2349. function round(value) {
  2350. return Math.round(value / config.EPSILON) * config.EPSILON;
  2351. }
  2352. function formatValue(value, {
  2353. precision = config.precision || 4
  2354. } = {}) {
  2355. value = round(value);
  2356. return "".concat(parseFloat(value.toPrecision(precision)));
  2357. }
  2358. function isArray(value) {
  2359. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2360. }
  2361. function duplicateArray(array) {
  2362. return array.clone ? array.clone() : new Array(array.length);
  2363. }
  2364. function map$1(value, func, result) {
  2365. if (isArray(value)) {
  2366. result = result || duplicateArray(value);
  2367. for (let i = 0; i < result.length && i < value.length; ++i) {
  2368. result[i] = func(value[i], i, result);
  2369. }
  2370. return result;
  2371. }
  2372. return func(value);
  2373. }
  2374. function toRadians(degrees) {
  2375. return radians(degrees);
  2376. }
  2377. function toDegrees(radians) {
  2378. return degrees(radians);
  2379. }
  2380. function radians(degrees, result) {
  2381. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2382. }
  2383. function degrees(radians, result) {
  2384. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2385. }
  2386. function clamp(value, min, max) {
  2387. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2388. }
  2389. function equals(a, b, epsilon) {
  2390. const oldEpsilon = config.EPSILON;
  2391. if (epsilon) {
  2392. config.EPSILON = epsilon;
  2393. }
  2394. try {
  2395. if (a === b) {
  2396. return true;
  2397. }
  2398. if (isArray(a) && isArray(b)) {
  2399. if (a.length !== b.length) {
  2400. return false;
  2401. }
  2402. for (let i = 0; i < a.length; ++i) {
  2403. if (!equals(a[i], b[i])) {
  2404. return false;
  2405. }
  2406. }
  2407. return true;
  2408. }
  2409. if (a && a.equals) {
  2410. return a.equals(b);
  2411. }
  2412. if (b && b.equals) {
  2413. return b.equals(a);
  2414. }
  2415. if (Number.isFinite(a) && Number.isFinite(b)) {
  2416. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2417. }
  2418. return false;
  2419. } finally {
  2420. config.EPSILON = oldEpsilon;
  2421. }
  2422. }
  2423. function _extendableBuiltin(cls) {
  2424. function ExtendableBuiltin() {
  2425. var instance = Reflect.construct(cls, Array.from(arguments));
  2426. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2427. return instance;
  2428. }
  2429. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2430. constructor: {
  2431. value: cls,
  2432. enumerable: false,
  2433. writable: true,
  2434. configurable: true
  2435. }
  2436. });
  2437. if (Object.setPrototypeOf) {
  2438. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2439. } else {
  2440. ExtendableBuiltin.__proto__ = cls;
  2441. }
  2442. return ExtendableBuiltin;
  2443. }
  2444. class MathArray extends _extendableBuiltin(Array) {
  2445. get ELEMENTS() {
  2446. assert$4(false);
  2447. return 0;
  2448. }
  2449. clone() {
  2450. return new this.constructor().copy(this);
  2451. }
  2452. from(arrayOrObject) {
  2453. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2454. }
  2455. fromArray(array, offset = 0) {
  2456. for (let i = 0; i < this.ELEMENTS; ++i) {
  2457. this[i] = array[i + offset];
  2458. }
  2459. return this.check();
  2460. }
  2461. to(arrayOrObject) {
  2462. if (arrayOrObject === this) {
  2463. return this;
  2464. }
  2465. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2466. }
  2467. toTarget(target) {
  2468. return target ? this.to(target) : this;
  2469. }
  2470. toArray(array = [], offset = 0) {
  2471. for (let i = 0; i < this.ELEMENTS; ++i) {
  2472. array[offset + i] = this[i];
  2473. }
  2474. return array;
  2475. }
  2476. toFloat32Array() {
  2477. return new Float32Array(this);
  2478. }
  2479. toString() {
  2480. return this.formatString(config);
  2481. }
  2482. formatString(opts) {
  2483. let string = '';
  2484. for (let i = 0; i < this.ELEMENTS; ++i) {
  2485. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2486. }
  2487. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2488. }
  2489. equals(array) {
  2490. if (!array || this.length !== array.length) {
  2491. return false;
  2492. }
  2493. for (let i = 0; i < this.ELEMENTS; ++i) {
  2494. if (!equals(this[i], array[i])) {
  2495. return false;
  2496. }
  2497. }
  2498. return true;
  2499. }
  2500. exactEquals(array) {
  2501. if (!array || this.length !== array.length) {
  2502. return false;
  2503. }
  2504. for (let i = 0; i < this.ELEMENTS; ++i) {
  2505. if (this[i] !== array[i]) {
  2506. return false;
  2507. }
  2508. }
  2509. return true;
  2510. }
  2511. negate() {
  2512. for (let i = 0; i < this.ELEMENTS; ++i) {
  2513. this[i] = -this[i];
  2514. }
  2515. return this.check();
  2516. }
  2517. lerp(a, b, t) {
  2518. if (t === undefined) {
  2519. t = b;
  2520. b = a;
  2521. a = this;
  2522. }
  2523. for (let i = 0; i < this.ELEMENTS; ++i) {
  2524. const ai = a[i];
  2525. this[i] = ai + t * (b[i] - ai);
  2526. }
  2527. return this.check();
  2528. }
  2529. min(vector) {
  2530. for (let i = 0; i < this.ELEMENTS; ++i) {
  2531. this[i] = Math.min(vector[i], this[i]);
  2532. }
  2533. return this.check();
  2534. }
  2535. max(vector) {
  2536. for (let i = 0; i < this.ELEMENTS; ++i) {
  2537. this[i] = Math.max(vector[i], this[i]);
  2538. }
  2539. return this.check();
  2540. }
  2541. clamp(minVector, maxVector) {
  2542. for (let i = 0; i < this.ELEMENTS; ++i) {
  2543. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2544. }
  2545. return this.check();
  2546. }
  2547. add(...vectors) {
  2548. for (const vector of vectors) {
  2549. for (let i = 0; i < this.ELEMENTS; ++i) {
  2550. this[i] += vector[i];
  2551. }
  2552. }
  2553. return this.check();
  2554. }
  2555. subtract(...vectors) {
  2556. for (const vector of vectors) {
  2557. for (let i = 0; i < this.ELEMENTS; ++i) {
  2558. this[i] -= vector[i];
  2559. }
  2560. }
  2561. return this.check();
  2562. }
  2563. scale(scale) {
  2564. if (Array.isArray(scale)) {
  2565. return this.multiply(scale);
  2566. }
  2567. for (let i = 0; i < this.ELEMENTS; ++i) {
  2568. this[i] *= scale;
  2569. }
  2570. return this.check();
  2571. }
  2572. sub(a) {
  2573. return this.subtract(a);
  2574. }
  2575. setScalar(a) {
  2576. for (let i = 0; i < this.ELEMENTS; ++i) {
  2577. this[i] = a;
  2578. }
  2579. return this.check();
  2580. }
  2581. addScalar(a) {
  2582. for (let i = 0; i < this.ELEMENTS; ++i) {
  2583. this[i] += a;
  2584. }
  2585. return this.check();
  2586. }
  2587. subScalar(a) {
  2588. return this.addScalar(-a);
  2589. }
  2590. multiplyScalar(scalar) {
  2591. for (let i = 0; i < this.ELEMENTS; ++i) {
  2592. this[i] *= scalar;
  2593. }
  2594. return this.check();
  2595. }
  2596. divideScalar(a) {
  2597. return this.scale(1 / a);
  2598. }
  2599. clampScalar(min, max) {
  2600. for (let i = 0; i < this.ELEMENTS; ++i) {
  2601. this[i] = Math.min(Math.max(this[i], min), max);
  2602. }
  2603. return this.check();
  2604. }
  2605. multiplyByScalar(scalar) {
  2606. return this.scale(scalar);
  2607. }
  2608. get elements() {
  2609. return this;
  2610. }
  2611. check() {
  2612. if (config.debug && !this.validate()) {
  2613. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2614. }
  2615. return this;
  2616. }
  2617. validate() {
  2618. let valid = this.length === this.ELEMENTS;
  2619. for (let i = 0; i < this.ELEMENTS; ++i) {
  2620. valid = valid && Number.isFinite(this[i]);
  2621. }
  2622. return valid;
  2623. }
  2624. }
  2625. function validateVector(v, length) {
  2626. if (v.length !== length) {
  2627. return false;
  2628. }
  2629. for (let i = 0; i < v.length; ++i) {
  2630. if (!Number.isFinite(v[i])) {
  2631. return false;
  2632. }
  2633. }
  2634. return true;
  2635. }
  2636. function checkNumber(value) {
  2637. if (!Number.isFinite(value)) {
  2638. throw new Error("Invalid number ".concat(value));
  2639. }
  2640. return value;
  2641. }
  2642. function checkVector(v, length, callerName = '') {
  2643. if (config.debug && !validateVector(v, length)) {
  2644. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2645. }
  2646. return v;
  2647. }
  2648. const map = {};
  2649. function deprecated(method, version) {
  2650. if (!map[method]) {
  2651. map[method] = true;
  2652. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2653. }
  2654. }
  2655. class Vector extends MathArray {
  2656. get ELEMENTS() {
  2657. assert$4(false);
  2658. return 0;
  2659. }
  2660. copy(vector) {
  2661. assert$4(false);
  2662. return this;
  2663. }
  2664. get x() {
  2665. return this[0];
  2666. }
  2667. set x(value) {
  2668. this[0] = checkNumber(value);
  2669. }
  2670. get y() {
  2671. return this[1];
  2672. }
  2673. set y(value) {
  2674. this[1] = checkNumber(value);
  2675. }
  2676. len() {
  2677. return Math.sqrt(this.lengthSquared());
  2678. }
  2679. magnitude() {
  2680. return this.len();
  2681. }
  2682. lengthSquared() {
  2683. let length = 0;
  2684. for (let i = 0; i < this.ELEMENTS; ++i) {
  2685. length += this[i] * this[i];
  2686. }
  2687. return length;
  2688. }
  2689. magnitudeSquared() {
  2690. return this.lengthSquared();
  2691. }
  2692. distance(mathArray) {
  2693. return Math.sqrt(this.distanceSquared(mathArray));
  2694. }
  2695. distanceSquared(mathArray) {
  2696. let length = 0;
  2697. for (let i = 0; i < this.ELEMENTS; ++i) {
  2698. const dist = this[i] - mathArray[i];
  2699. length += dist * dist;
  2700. }
  2701. return checkNumber(length);
  2702. }
  2703. dot(mathArray) {
  2704. let product = 0;
  2705. for (let i = 0; i < this.ELEMENTS; ++i) {
  2706. product += this[i] * mathArray[i];
  2707. }
  2708. return checkNumber(product);
  2709. }
  2710. normalize() {
  2711. const length = this.magnitude();
  2712. if (length !== 0) {
  2713. for (let i = 0; i < this.ELEMENTS; ++i) {
  2714. this[i] /= length;
  2715. }
  2716. }
  2717. return this.check();
  2718. }
  2719. multiply(...vectors) {
  2720. for (const vector of vectors) {
  2721. for (let i = 0; i < this.ELEMENTS; ++i) {
  2722. this[i] *= vector[i];
  2723. }
  2724. }
  2725. return this.check();
  2726. }
  2727. divide(...vectors) {
  2728. for (const vector of vectors) {
  2729. for (let i = 0; i < this.ELEMENTS; ++i) {
  2730. this[i] /= vector[i];
  2731. }
  2732. }
  2733. return this.check();
  2734. }
  2735. lengthSq() {
  2736. return this.lengthSquared();
  2737. }
  2738. distanceTo(vector) {
  2739. return this.distance(vector);
  2740. }
  2741. distanceToSquared(vector) {
  2742. return this.distanceSquared(vector);
  2743. }
  2744. getComponent(i) {
  2745. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2746. return checkNumber(this[i]);
  2747. }
  2748. setComponent(i, value) {
  2749. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2750. this[i] = value;
  2751. return this.check();
  2752. }
  2753. addVectors(a, b) {
  2754. return this.copy(a).add(b);
  2755. }
  2756. subVectors(a, b) {
  2757. return this.copy(a).subtract(b);
  2758. }
  2759. multiplyVectors(a, b) {
  2760. return this.copy(a).multiply(b);
  2761. }
  2762. addScaledVector(a, b) {
  2763. return this.add(new this.constructor(a).multiplyScalar(b));
  2764. }
  2765. }
  2766. /**
  2767. * Common utilities
  2768. * @module glMatrix
  2769. */
  2770. // Configuration Constants
  2771. var EPSILON = 0.000001;
  2772. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2773. if (!Math.hypot) Math.hypot = function () {
  2774. var y = 0,
  2775. i = arguments.length;
  2776. while (i--) {
  2777. y += arguments[i] * arguments[i];
  2778. }
  2779. return Math.sqrt(y);
  2780. };
  2781. /**
  2782. * 2 Dimensional Vector
  2783. * @module vec2
  2784. */
  2785. /**
  2786. * Creates a new, empty vec2
  2787. *
  2788. * @returns {vec2} a new 2D vector
  2789. */
  2790. function create$4() {
  2791. var out = new ARRAY_TYPE(2);
  2792. if (ARRAY_TYPE != Float32Array) {
  2793. out[0] = 0;
  2794. out[1] = 0;
  2795. }
  2796. return out;
  2797. }
  2798. /**
  2799. * Transforms the vec2 with a mat2
  2800. *
  2801. * @param {vec2} out the receiving vector
  2802. * @param {ReadonlyVec2} a the vector to transform
  2803. * @param {ReadonlyMat2} m matrix to transform with
  2804. * @returns {vec2} out
  2805. */
  2806. function transformMat2(out, a, m) {
  2807. var x = a[0],
  2808. y = a[1];
  2809. out[0] = m[0] * x + m[2] * y;
  2810. out[1] = m[1] * x + m[3] * y;
  2811. return out;
  2812. }
  2813. /**
  2814. * Transforms the vec2 with a mat2d
  2815. *
  2816. * @param {vec2} out the receiving vector
  2817. * @param {ReadonlyVec2} a the vector to transform
  2818. * @param {ReadonlyMat2d} m matrix to transform with
  2819. * @returns {vec2} out
  2820. */
  2821. function transformMat2d(out, a, m) {
  2822. var x = a[0],
  2823. y = a[1];
  2824. out[0] = m[0] * x + m[2] * y + m[4];
  2825. out[1] = m[1] * x + m[3] * y + m[5];
  2826. return out;
  2827. }
  2828. /**
  2829. * Transforms the vec2 with a mat3
  2830. * 3rd vector component is implicitly '1'
  2831. *
  2832. * @param {vec2} out the receiving vector
  2833. * @param {ReadonlyVec2} a the vector to transform
  2834. * @param {ReadonlyMat3} m matrix to transform with
  2835. * @returns {vec2} out
  2836. */
  2837. function transformMat3$1(out, a, m) {
  2838. var x = a[0],
  2839. y = a[1];
  2840. out[0] = m[0] * x + m[3] * y + m[6];
  2841. out[1] = m[1] * x + m[4] * y + m[7];
  2842. return out;
  2843. }
  2844. /**
  2845. * Transforms the vec2 with a mat4
  2846. * 3rd vector component is implicitly '0'
  2847. * 4th vector component is implicitly '1'
  2848. *
  2849. * @param {vec2} out the receiving vector
  2850. * @param {ReadonlyVec2} a the vector to transform
  2851. * @param {ReadonlyMat4} m matrix to transform with
  2852. * @returns {vec2} out
  2853. */
  2854. function transformMat4$2(out, a, m) {
  2855. var x = a[0];
  2856. var y = a[1];
  2857. out[0] = m[0] * x + m[4] * y + m[12];
  2858. out[1] = m[1] * x + m[5] * y + m[13];
  2859. return out;
  2860. }
  2861. /**
  2862. * Perform some operation over an array of vec2s.
  2863. *
  2864. * @param {Array} a the array of vectors to iterate over
  2865. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2866. * @param {Number} offset Number of elements to skip at the beginning of the array
  2867. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2868. * @param {Function} fn Function to call for each vector in the array
  2869. * @param {Object} [arg] additional argument to pass to fn
  2870. * @returns {Array} a
  2871. * @function
  2872. */
  2873. (function () {
  2874. var vec = create$4();
  2875. return function (a, stride, offset, count, fn, arg) {
  2876. var i, l;
  2877. if (!stride) {
  2878. stride = 2;
  2879. }
  2880. if (!offset) {
  2881. offset = 0;
  2882. }
  2883. if (count) {
  2884. l = Math.min(count * stride + offset, a.length);
  2885. } else {
  2886. l = a.length;
  2887. }
  2888. for (i = offset; i < l; i += stride) {
  2889. vec[0] = a[i];
  2890. vec[1] = a[i + 1];
  2891. fn(vec, vec, arg);
  2892. a[i] = vec[0];
  2893. a[i + 1] = vec[1];
  2894. }
  2895. return a;
  2896. };
  2897. })();
  2898. function vec2_transformMat4AsVector(out, a, m) {
  2899. const x = a[0];
  2900. const y = a[1];
  2901. const w = m[3] * x + m[7] * y || 1.0;
  2902. out[0] = (m[0] * x + m[4] * y) / w;
  2903. out[1] = (m[1] * x + m[5] * y) / w;
  2904. return out;
  2905. }
  2906. function vec3_transformMat4AsVector(out, a, m) {
  2907. const x = a[0];
  2908. const y = a[1];
  2909. const z = a[2];
  2910. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2911. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2912. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2913. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2914. return out;
  2915. }
  2916. function vec3_transformMat2(out, a, m) {
  2917. const x = a[0];
  2918. const y = a[1];
  2919. out[0] = m[0] * x + m[2] * y;
  2920. out[1] = m[1] * x + m[3] * y;
  2921. out[2] = a[2];
  2922. return out;
  2923. }
  2924. function vec4_transformMat3(out, a, m) {
  2925. const x = a[0];
  2926. const y = a[1];
  2927. const z = a[2];
  2928. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2929. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2930. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2931. out[3] = a[3];
  2932. return out;
  2933. }
  2934. class Vector2 extends Vector {
  2935. constructor(x = 0, y = 0) {
  2936. super(2);
  2937. if (isArray(x) && arguments.length === 1) {
  2938. this.copy(x);
  2939. } else {
  2940. if (config.debug) {
  2941. checkNumber(x);
  2942. checkNumber(y);
  2943. }
  2944. this[0] = x;
  2945. this[1] = y;
  2946. }
  2947. }
  2948. set(x, y) {
  2949. this[0] = x;
  2950. this[1] = y;
  2951. return this.check();
  2952. }
  2953. copy(array) {
  2954. this[0] = array[0];
  2955. this[1] = array[1];
  2956. return this.check();
  2957. }
  2958. fromObject(object) {
  2959. if (config.debug) {
  2960. checkNumber(object.x);
  2961. checkNumber(object.y);
  2962. }
  2963. this[0] = object.x;
  2964. this[1] = object.y;
  2965. return this.check();
  2966. }
  2967. toObject(object) {
  2968. object.x = this[0];
  2969. object.y = this[1];
  2970. return object;
  2971. }
  2972. get ELEMENTS() {
  2973. return 2;
  2974. }
  2975. horizontalAngle() {
  2976. return Math.atan2(this.y, this.x);
  2977. }
  2978. verticalAngle() {
  2979. return Math.atan2(this.x, this.y);
  2980. }
  2981. transform(matrix4) {
  2982. return this.transformAsPoint(matrix4);
  2983. }
  2984. transformAsPoint(matrix4) {
  2985. transformMat4$2(this, this, matrix4);
  2986. return this.check();
  2987. }
  2988. transformAsVector(matrix4) {
  2989. vec2_transformMat4AsVector(this, this, matrix4);
  2990. return this.check();
  2991. }
  2992. transformByMatrix3(matrix3) {
  2993. transformMat3$1(this, this, matrix3);
  2994. return this.check();
  2995. }
  2996. transformByMatrix2x3(matrix2x3) {
  2997. transformMat2d(this, this, matrix2x3);
  2998. return this.check();
  2999. }
  3000. transformByMatrix2(matrix2) {
  3001. transformMat2(this, this, matrix2);
  3002. return this.check();
  3003. }
  3004. }
  3005. /**
  3006. * 3 Dimensional Vector
  3007. * @module vec3
  3008. */
  3009. /**
  3010. * Creates a new, empty vec3
  3011. *
  3012. * @returns {vec3} a new 3D vector
  3013. */
  3014. function create$3() {
  3015. var out = new ARRAY_TYPE(3);
  3016. if (ARRAY_TYPE != Float32Array) {
  3017. out[0] = 0;
  3018. out[1] = 0;
  3019. out[2] = 0;
  3020. }
  3021. return out;
  3022. }
  3023. /**
  3024. * Calculates the length of a vec3
  3025. *
  3026. * @param {ReadonlyVec3} a vector to calculate length of
  3027. * @returns {Number} length of a
  3028. */
  3029. function length$2(a) {
  3030. var x = a[0];
  3031. var y = a[1];
  3032. var z = a[2];
  3033. return Math.hypot(x, y, z);
  3034. }
  3035. /**
  3036. * Creates a new vec3 initialized with the given values
  3037. *
  3038. * @param {Number} x X component
  3039. * @param {Number} y Y component
  3040. * @param {Number} z Z component
  3041. * @returns {vec3} a new 3D vector
  3042. */
  3043. function fromValues(x, y, z) {
  3044. var out = new ARRAY_TYPE(3);
  3045. out[0] = x;
  3046. out[1] = y;
  3047. out[2] = z;
  3048. return out;
  3049. }
  3050. /**
  3051. * Normalize a vec3
  3052. *
  3053. * @param {vec3} out the receiving vector
  3054. * @param {ReadonlyVec3} a vector to normalize
  3055. * @returns {vec3} out
  3056. */
  3057. function normalize$2(out, a) {
  3058. var x = a[0];
  3059. var y = a[1];
  3060. var z = a[2];
  3061. var len = x * x + y * y + z * z;
  3062. if (len > 0) {
  3063. //TODO: evaluate use of glm_invsqrt here?
  3064. len = 1 / Math.sqrt(len);
  3065. }
  3066. out[0] = a[0] * len;
  3067. out[1] = a[1] * len;
  3068. out[2] = a[2] * len;
  3069. return out;
  3070. }
  3071. /**
  3072. * Calculates the dot product of two vec3's
  3073. *
  3074. * @param {ReadonlyVec3} a the first operand
  3075. * @param {ReadonlyVec3} b the second operand
  3076. * @returns {Number} dot product of a and b
  3077. */
  3078. function dot$2(a, b) {
  3079. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3080. }
  3081. /**
  3082. * Computes the cross product of two vec3's
  3083. *
  3084. * @param {vec3} out the receiving vector
  3085. * @param {ReadonlyVec3} a the first operand
  3086. * @param {ReadonlyVec3} b the second operand
  3087. * @returns {vec3} out
  3088. */
  3089. function cross(out, a, b) {
  3090. var ax = a[0],
  3091. ay = a[1],
  3092. az = a[2];
  3093. var bx = b[0],
  3094. by = b[1],
  3095. bz = b[2];
  3096. out[0] = ay * bz - az * by;
  3097. out[1] = az * bx - ax * bz;
  3098. out[2] = ax * by - ay * bx;
  3099. return out;
  3100. }
  3101. /**
  3102. * Transforms the vec3 with a mat4.
  3103. * 4th vector component is implicitly '1'
  3104. *
  3105. * @param {vec3} out the receiving vector
  3106. * @param {ReadonlyVec3} a the vector to transform
  3107. * @param {ReadonlyMat4} m matrix to transform with
  3108. * @returns {vec3} out
  3109. */
  3110. function transformMat4$1(out, a, m) {
  3111. var x = a[0],
  3112. y = a[1],
  3113. z = a[2];
  3114. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3115. w = w || 1.0;
  3116. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3117. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3118. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3119. return out;
  3120. }
  3121. /**
  3122. * Transforms the vec3 with a mat3.
  3123. *
  3124. * @param {vec3} out the receiving vector
  3125. * @param {ReadonlyVec3} a the vector to transform
  3126. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3127. * @returns {vec3} out
  3128. */
  3129. function transformMat3(out, a, m) {
  3130. var x = a[0],
  3131. y = a[1],
  3132. z = a[2];
  3133. out[0] = x * m[0] + y * m[3] + z * m[6];
  3134. out[1] = x * m[1] + y * m[4] + z * m[7];
  3135. out[2] = x * m[2] + y * m[5] + z * m[8];
  3136. return out;
  3137. }
  3138. /**
  3139. * Transforms the vec3 with a quat
  3140. * Can also be used for dual quaternions. (Multiply it with the real part)
  3141. *
  3142. * @param {vec3} out the receiving vector
  3143. * @param {ReadonlyVec3} a the vector to transform
  3144. * @param {ReadonlyQuat} q quaternion to transform with
  3145. * @returns {vec3} out
  3146. */
  3147. function transformQuat$1(out, a, q) {
  3148. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3149. var qx = q[0],
  3150. qy = q[1],
  3151. qz = q[2],
  3152. qw = q[3];
  3153. var x = a[0],
  3154. y = a[1],
  3155. z = a[2]; // var qvec = [qx, qy, qz];
  3156. // var uv = vec3.cross([], qvec, a);
  3157. var uvx = qy * z - qz * y,
  3158. uvy = qz * x - qx * z,
  3159. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3160. var uuvx = qy * uvz - qz * uvy,
  3161. uuvy = qz * uvx - qx * uvz,
  3162. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3163. var w2 = qw * 2;
  3164. uvx *= w2;
  3165. uvy *= w2;
  3166. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3167. uuvx *= 2;
  3168. uuvy *= 2;
  3169. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3170. out[0] = x + uvx + uuvx;
  3171. out[1] = y + uvy + uuvy;
  3172. out[2] = z + uvz + uuvz;
  3173. return out;
  3174. }
  3175. /**
  3176. * Rotate a 3D vector around the x-axis
  3177. * @param {vec3} out The receiving vec3
  3178. * @param {ReadonlyVec3} a The vec3 point to rotate
  3179. * @param {ReadonlyVec3} b The origin of the rotation
  3180. * @param {Number} rad The angle of rotation in radians
  3181. * @returns {vec3} out
  3182. */
  3183. function rotateX$2(out, a, b, rad) {
  3184. var p = [],
  3185. r = []; //Translate point to the origin
  3186. p[0] = a[0] - b[0];
  3187. p[1] = a[1] - b[1];
  3188. p[2] = a[2] - b[2]; //perform rotation
  3189. r[0] = p[0];
  3190. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3191. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3192. out[0] = r[0] + b[0];
  3193. out[1] = r[1] + b[1];
  3194. out[2] = r[2] + b[2];
  3195. return out;
  3196. }
  3197. /**
  3198. * Rotate a 3D vector around the y-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 rotateY$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[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3212. r[1] = p[1];
  3213. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(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 z-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 rotateZ$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[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3234. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3235. r[2] = p[2]; //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. * Get the angle between two 3D vectors
  3243. * @param {ReadonlyVec3} a The first operand
  3244. * @param {ReadonlyVec3} b The second operand
  3245. * @returns {Number} The angle in radians
  3246. */
  3247. function angle(a, b) {
  3248. var ax = a[0],
  3249. ay = a[1],
  3250. az = a[2],
  3251. bx = b[0],
  3252. by = b[1],
  3253. bz = b[2],
  3254. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3255. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3256. mag = mag1 * mag2,
  3257. cosine = mag && dot$2(a, b) / mag;
  3258. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3259. }
  3260. /**
  3261. * Alias for {@link vec3.length}
  3262. * @function
  3263. */
  3264. var len = length$2;
  3265. /**
  3266. * Perform some operation over an array of vec3s.
  3267. *
  3268. * @param {Array} a the array of vectors to iterate over
  3269. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3270. * @param {Number} offset Number of elements to skip at the beginning of the array
  3271. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3272. * @param {Function} fn Function to call for each vector in the array
  3273. * @param {Object} [arg] additional argument to pass to fn
  3274. * @returns {Array} a
  3275. * @function
  3276. */
  3277. (function () {
  3278. var vec = create$3();
  3279. return function (a, stride, offset, count, fn, arg) {
  3280. var i, l;
  3281. if (!stride) {
  3282. stride = 3;
  3283. }
  3284. if (!offset) {
  3285. offset = 0;
  3286. }
  3287. if (count) {
  3288. l = Math.min(count * stride + offset, a.length);
  3289. } else {
  3290. l = a.length;
  3291. }
  3292. for (i = offset; i < l; i += stride) {
  3293. vec[0] = a[i];
  3294. vec[1] = a[i + 1];
  3295. vec[2] = a[i + 2];
  3296. fn(vec, vec, arg);
  3297. a[i] = vec[0];
  3298. a[i + 1] = vec[1];
  3299. a[i + 2] = vec[2];
  3300. }
  3301. return a;
  3302. };
  3303. })();
  3304. const ORIGIN = [0, 0, 0];
  3305. const constants$2 = {};
  3306. class Vector3 extends Vector {
  3307. static get ZERO() {
  3308. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3309. }
  3310. constructor(x = 0, y = 0, z = 0) {
  3311. super(-0, -0, -0);
  3312. if (arguments.length === 1 && isArray(x)) {
  3313. this.copy(x);
  3314. } else {
  3315. if (config.debug) {
  3316. checkNumber(x);
  3317. checkNumber(y);
  3318. checkNumber(z);
  3319. }
  3320. this[0] = x;
  3321. this[1] = y;
  3322. this[2] = z;
  3323. }
  3324. }
  3325. set(x, y, z) {
  3326. this[0] = x;
  3327. this[1] = y;
  3328. this[2] = z;
  3329. return this.check();
  3330. }
  3331. copy(array) {
  3332. this[0] = array[0];
  3333. this[1] = array[1];
  3334. this[2] = array[2];
  3335. return this.check();
  3336. }
  3337. fromObject(object) {
  3338. if (config.debug) {
  3339. checkNumber(object.x);
  3340. checkNumber(object.y);
  3341. checkNumber(object.z);
  3342. }
  3343. this[0] = object.x;
  3344. this[1] = object.y;
  3345. this[2] = object.z;
  3346. return this.check();
  3347. }
  3348. toObject(object) {
  3349. object.x = this[0];
  3350. object.y = this[1];
  3351. object.z = this[2];
  3352. return object;
  3353. }
  3354. get ELEMENTS() {
  3355. return 3;
  3356. }
  3357. get z() {
  3358. return this[2];
  3359. }
  3360. set z(value) {
  3361. this[2] = checkNumber(value);
  3362. }
  3363. angle(vector) {
  3364. return angle(this, vector);
  3365. }
  3366. cross(vector) {
  3367. cross(this, this, vector);
  3368. return this.check();
  3369. }
  3370. rotateX({
  3371. radians,
  3372. origin = ORIGIN
  3373. }) {
  3374. rotateX$2(this, this, origin, radians);
  3375. return this.check();
  3376. }
  3377. rotateY({
  3378. radians,
  3379. origin = ORIGIN
  3380. }) {
  3381. rotateY$2(this, this, origin, radians);
  3382. return this.check();
  3383. }
  3384. rotateZ({
  3385. radians,
  3386. origin = ORIGIN
  3387. }) {
  3388. rotateZ$2(this, this, origin, radians);
  3389. return this.check();
  3390. }
  3391. transform(matrix4) {
  3392. return this.transformAsPoint(matrix4);
  3393. }
  3394. transformAsPoint(matrix4) {
  3395. transformMat4$1(this, this, matrix4);
  3396. return this.check();
  3397. }
  3398. transformAsVector(matrix4) {
  3399. vec3_transformMat4AsVector(this, this, matrix4);
  3400. return this.check();
  3401. }
  3402. transformByMatrix3(matrix3) {
  3403. transformMat3(this, this, matrix3);
  3404. return this.check();
  3405. }
  3406. transformByMatrix2(matrix2) {
  3407. vec3_transformMat2(this, this, matrix2);
  3408. return this.check();
  3409. }
  3410. transformByQuaternion(quaternion) {
  3411. transformQuat$1(this, this, quaternion);
  3412. return this.check();
  3413. }
  3414. }
  3415. class Matrix extends MathArray {
  3416. get ELEMENTS() {
  3417. assert$4(false);
  3418. return 0;
  3419. }
  3420. get RANK() {
  3421. assert$4(false);
  3422. return 0;
  3423. }
  3424. toString() {
  3425. let string = '[';
  3426. if (config.printRowMajor) {
  3427. string += 'row-major:';
  3428. for (let row = 0; row < this.RANK; ++row) {
  3429. for (let col = 0; col < this.RANK; ++col) {
  3430. string += " ".concat(this[col * this.RANK + row]);
  3431. }
  3432. }
  3433. } else {
  3434. string += 'column-major:';
  3435. for (let i = 0; i < this.ELEMENTS; ++i) {
  3436. string += " ".concat(this[i]);
  3437. }
  3438. }
  3439. string += ']';
  3440. return string;
  3441. }
  3442. getElementIndex(row, col) {
  3443. return col * this.RANK + row;
  3444. }
  3445. getElement(row, col) {
  3446. return this[col * this.RANK + row];
  3447. }
  3448. setElement(row, col, value) {
  3449. this[col * this.RANK + row] = checkNumber(value);
  3450. return this;
  3451. }
  3452. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3453. const firstIndex = columnIndex * this.RANK;
  3454. for (let i = 0; i < this.RANK; ++i) {
  3455. result[i] = this[firstIndex + i];
  3456. }
  3457. return result;
  3458. }
  3459. setColumn(columnIndex, columnVector) {
  3460. const firstIndex = columnIndex * this.RANK;
  3461. for (let i = 0; i < this.RANK; ++i) {
  3462. this[firstIndex + i] = columnVector[i];
  3463. }
  3464. return this;
  3465. }
  3466. }
  3467. /**
  3468. * 3x3 Matrix
  3469. * @module mat3
  3470. */
  3471. /**
  3472. * Creates a new identity mat3
  3473. *
  3474. * @returns {mat3} a new 3x3 matrix
  3475. */
  3476. function create$2() {
  3477. var out = new ARRAY_TYPE(9);
  3478. if (ARRAY_TYPE != Float32Array) {
  3479. out[1] = 0;
  3480. out[2] = 0;
  3481. out[3] = 0;
  3482. out[5] = 0;
  3483. out[6] = 0;
  3484. out[7] = 0;
  3485. }
  3486. out[0] = 1;
  3487. out[4] = 1;
  3488. out[8] = 1;
  3489. return out;
  3490. }
  3491. /**
  3492. * Transpose the values of a mat3
  3493. *
  3494. * @param {mat3} out the receiving matrix
  3495. * @param {ReadonlyMat3} a the source matrix
  3496. * @returns {mat3} out
  3497. */
  3498. function transpose$1(out, a) {
  3499. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3500. if (out === a) {
  3501. var a01 = a[1],
  3502. a02 = a[2],
  3503. a12 = a[5];
  3504. out[1] = a[3];
  3505. out[2] = a[6];
  3506. out[3] = a01;
  3507. out[5] = a[7];
  3508. out[6] = a02;
  3509. out[7] = a12;
  3510. } else {
  3511. out[0] = a[0];
  3512. out[1] = a[3];
  3513. out[2] = a[6];
  3514. out[3] = a[1];
  3515. out[4] = a[4];
  3516. out[5] = a[7];
  3517. out[6] = a[2];
  3518. out[7] = a[5];
  3519. out[8] = a[8];
  3520. }
  3521. return out;
  3522. }
  3523. /**
  3524. * Inverts a mat3
  3525. *
  3526. * @param {mat3} out the receiving matrix
  3527. * @param {ReadonlyMat3} a the source matrix
  3528. * @returns {mat3} out
  3529. */
  3530. function invert$2(out, a) {
  3531. var a00 = a[0],
  3532. a01 = a[1],
  3533. a02 = a[2];
  3534. var a10 = a[3],
  3535. a11 = a[4],
  3536. a12 = a[5];
  3537. var a20 = a[6],
  3538. a21 = a[7],
  3539. a22 = a[8];
  3540. var b01 = a22 * a11 - a12 * a21;
  3541. var b11 = -a22 * a10 + a12 * a20;
  3542. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3543. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3544. if (!det) {
  3545. return null;
  3546. }
  3547. det = 1.0 / det;
  3548. out[0] = b01 * det;
  3549. out[1] = (-a22 * a01 + a02 * a21) * det;
  3550. out[2] = (a12 * a01 - a02 * a11) * det;
  3551. out[3] = b11 * det;
  3552. out[4] = (a22 * a00 - a02 * a20) * det;
  3553. out[5] = (-a12 * a00 + a02 * a10) * det;
  3554. out[6] = b21 * det;
  3555. out[7] = (-a21 * a00 + a01 * a20) * det;
  3556. out[8] = (a11 * a00 - a01 * a10) * det;
  3557. return out;
  3558. }
  3559. /**
  3560. * Calculates the determinant of a mat3
  3561. *
  3562. * @param {ReadonlyMat3} a the source matrix
  3563. * @returns {Number} determinant of a
  3564. */
  3565. function determinant$1(a) {
  3566. var a00 = a[0],
  3567. a01 = a[1],
  3568. a02 = a[2];
  3569. var a10 = a[3],
  3570. a11 = a[4],
  3571. a12 = a[5];
  3572. var a20 = a[6],
  3573. a21 = a[7],
  3574. a22 = a[8];
  3575. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3576. }
  3577. /**
  3578. * Multiplies two mat3's
  3579. *
  3580. * @param {mat3} out the receiving matrix
  3581. * @param {ReadonlyMat3} a the first operand
  3582. * @param {ReadonlyMat3} b the second operand
  3583. * @returns {mat3} out
  3584. */
  3585. function multiply$2(out, a, b) {
  3586. var a00 = a[0],
  3587. a01 = a[1],
  3588. a02 = a[2];
  3589. var a10 = a[3],
  3590. a11 = a[4],
  3591. a12 = a[5];
  3592. var a20 = a[6],
  3593. a21 = a[7],
  3594. a22 = a[8];
  3595. var b00 = b[0],
  3596. b01 = b[1],
  3597. b02 = b[2];
  3598. var b10 = b[3],
  3599. b11 = b[4],
  3600. b12 = b[5];
  3601. var b20 = b[6],
  3602. b21 = b[7],
  3603. b22 = b[8];
  3604. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3605. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3606. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3607. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3608. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3609. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3610. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3611. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3612. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3613. return out;
  3614. }
  3615. /**
  3616. * Translate a mat3 by the given vector
  3617. *
  3618. * @param {mat3} out the receiving matrix
  3619. * @param {ReadonlyMat3} a the matrix to translate
  3620. * @param {ReadonlyVec2} v vector to translate by
  3621. * @returns {mat3} out
  3622. */
  3623. function translate$1(out, a, v) {
  3624. var a00 = a[0],
  3625. a01 = a[1],
  3626. a02 = a[2],
  3627. a10 = a[3],
  3628. a11 = a[4],
  3629. a12 = a[5],
  3630. a20 = a[6],
  3631. a21 = a[7],
  3632. a22 = a[8],
  3633. x = v[0],
  3634. y = v[1];
  3635. out[0] = a00;
  3636. out[1] = a01;
  3637. out[2] = a02;
  3638. out[3] = a10;
  3639. out[4] = a11;
  3640. out[5] = a12;
  3641. out[6] = x * a00 + y * a10 + a20;
  3642. out[7] = x * a01 + y * a11 + a21;
  3643. out[8] = x * a02 + y * a12 + a22;
  3644. return out;
  3645. }
  3646. /**
  3647. * Rotates a mat3 by the given angle
  3648. *
  3649. * @param {mat3} out the receiving matrix
  3650. * @param {ReadonlyMat3} a the matrix to rotate
  3651. * @param {Number} rad the angle to rotate the matrix by
  3652. * @returns {mat3} out
  3653. */
  3654. function rotate$1(out, a, rad) {
  3655. var a00 = a[0],
  3656. a01 = a[1],
  3657. a02 = a[2],
  3658. a10 = a[3],
  3659. a11 = a[4],
  3660. a12 = a[5],
  3661. a20 = a[6],
  3662. a21 = a[7],
  3663. a22 = a[8],
  3664. s = Math.sin(rad),
  3665. c = Math.cos(rad);
  3666. out[0] = c * a00 + s * a10;
  3667. out[1] = c * a01 + s * a11;
  3668. out[2] = c * a02 + s * a12;
  3669. out[3] = c * a10 - s * a00;
  3670. out[4] = c * a11 - s * a01;
  3671. out[5] = c * a12 - s * a02;
  3672. out[6] = a20;
  3673. out[7] = a21;
  3674. out[8] = a22;
  3675. return out;
  3676. }
  3677. /**
  3678. * Scales the mat3 by the dimensions in the given vec2
  3679. *
  3680. * @param {mat3} out the receiving matrix
  3681. * @param {ReadonlyMat3} a the matrix to rotate
  3682. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3683. * @returns {mat3} out
  3684. **/
  3685. function scale$3(out, a, v) {
  3686. var x = v[0],
  3687. y = v[1];
  3688. out[0] = x * a[0];
  3689. out[1] = x * a[1];
  3690. out[2] = x * a[2];
  3691. out[3] = y * a[3];
  3692. out[4] = y * a[4];
  3693. out[5] = y * a[5];
  3694. out[6] = a[6];
  3695. out[7] = a[7];
  3696. out[8] = a[8];
  3697. return out;
  3698. }
  3699. /**
  3700. * Calculates a 3x3 matrix from the given quaternion
  3701. *
  3702. * @param {mat3} out mat3 receiving operation result
  3703. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3704. *
  3705. * @returns {mat3} out
  3706. */
  3707. function fromQuat$1(out, q) {
  3708. var x = q[0],
  3709. y = q[1],
  3710. z = q[2],
  3711. w = q[3];
  3712. var x2 = x + x;
  3713. var y2 = y + y;
  3714. var z2 = z + z;
  3715. var xx = x * x2;
  3716. var yx = y * x2;
  3717. var yy = y * y2;
  3718. var zx = z * x2;
  3719. var zy = z * y2;
  3720. var zz = z * z2;
  3721. var wx = w * x2;
  3722. var wy = w * y2;
  3723. var wz = w * z2;
  3724. out[0] = 1 - yy - zz;
  3725. out[3] = yx - wz;
  3726. out[6] = zx + wy;
  3727. out[1] = yx + wz;
  3728. out[4] = 1 - xx - zz;
  3729. out[7] = zy - wx;
  3730. out[2] = zx - wy;
  3731. out[5] = zy + wx;
  3732. out[8] = 1 - xx - yy;
  3733. return out;
  3734. }
  3735. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3736. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3737. const INDICES$1 = Object.freeze({
  3738. COL0ROW0: 0,
  3739. COL0ROW1: 1,
  3740. COL0ROW2: 2,
  3741. COL1ROW0: 3,
  3742. COL1ROW1: 4,
  3743. COL1ROW2: 5,
  3744. COL2ROW0: 6,
  3745. COL2ROW1: 7,
  3746. COL2ROW2: 8
  3747. });
  3748. const constants$1 = {};
  3749. class Matrix3 extends Matrix {
  3750. static get IDENTITY() {
  3751. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3752. return constants$1.IDENTITY;
  3753. }
  3754. static get ZERO() {
  3755. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3756. return constants$1.ZERO;
  3757. }
  3758. get ELEMENTS() {
  3759. return 9;
  3760. }
  3761. get RANK() {
  3762. return 3;
  3763. }
  3764. get INDICES() {
  3765. return INDICES$1;
  3766. }
  3767. constructor(array) {
  3768. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3769. if (arguments.length === 1 && Array.isArray(array)) {
  3770. this.copy(array);
  3771. } else {
  3772. this.identity();
  3773. }
  3774. }
  3775. copy(array) {
  3776. this[0] = array[0];
  3777. this[1] = array[1];
  3778. this[2] = array[2];
  3779. this[3] = array[3];
  3780. this[4] = array[4];
  3781. this[5] = array[5];
  3782. this[6] = array[6];
  3783. this[7] = array[7];
  3784. this[8] = array[8];
  3785. return this.check();
  3786. }
  3787. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3788. this[0] = m00;
  3789. this[1] = m10;
  3790. this[2] = m20;
  3791. this[3] = m01;
  3792. this[4] = m11;
  3793. this[5] = m21;
  3794. this[6] = m02;
  3795. this[7] = m12;
  3796. this[8] = m22;
  3797. return this.check();
  3798. }
  3799. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3800. this[0] = m00;
  3801. this[1] = m10;
  3802. this[2] = m20;
  3803. this[3] = m01;
  3804. this[4] = m11;
  3805. this[5] = m21;
  3806. this[6] = m02;
  3807. this[7] = m12;
  3808. this[8] = m22;
  3809. return this.check();
  3810. }
  3811. determinant() {
  3812. return determinant$1(this);
  3813. }
  3814. identity() {
  3815. return this.copy(IDENTITY$1);
  3816. }
  3817. fromQuaternion(q) {
  3818. fromQuat$1(this, q);
  3819. return this.check();
  3820. }
  3821. transpose() {
  3822. transpose$1(this, this);
  3823. return this.check();
  3824. }
  3825. invert() {
  3826. invert$2(this, this);
  3827. return this.check();
  3828. }
  3829. multiplyLeft(a) {
  3830. multiply$2(this, a, this);
  3831. return this.check();
  3832. }
  3833. multiplyRight(a) {
  3834. multiply$2(this, this, a);
  3835. return this.check();
  3836. }
  3837. rotate(radians) {
  3838. rotate$1(this, this, radians);
  3839. return this.check();
  3840. }
  3841. scale(factor) {
  3842. if (Array.isArray(factor)) {
  3843. scale$3(this, this, factor);
  3844. } else {
  3845. scale$3(this, this, [factor, factor, factor]);
  3846. }
  3847. return this.check();
  3848. }
  3849. translate(vec) {
  3850. translate$1(this, this, vec);
  3851. return this.check();
  3852. }
  3853. transform(vector, result) {
  3854. switch (vector.length) {
  3855. case 2:
  3856. result = transformMat3$1(result || [-0, -0], vector, this);
  3857. break;
  3858. case 3:
  3859. result = transformMat3(result || [-0, -0, -0], vector, this);
  3860. break;
  3861. case 4:
  3862. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3863. break;
  3864. default:
  3865. throw new Error('Illegal vector');
  3866. }
  3867. checkVector(result, vector.length);
  3868. return result;
  3869. }
  3870. transformVector(vector, result) {
  3871. deprecated('Matrix3.transformVector');
  3872. return this.transform(vector, result);
  3873. }
  3874. transformVector2(vector, result) {
  3875. deprecated('Matrix3.transformVector');
  3876. return this.transform(vector, result);
  3877. }
  3878. transformVector3(vector, result) {
  3879. deprecated('Matrix3.transformVector');
  3880. return this.transform(vector, result);
  3881. }
  3882. }
  3883. /**
  3884. * Set a mat4 to the identity matrix
  3885. *
  3886. * @param {mat4} out the receiving matrix
  3887. * @returns {mat4} out
  3888. */
  3889. function identity$1(out) {
  3890. out[0] = 1;
  3891. out[1] = 0;
  3892. out[2] = 0;
  3893. out[3] = 0;
  3894. out[4] = 0;
  3895. out[5] = 1;
  3896. out[6] = 0;
  3897. out[7] = 0;
  3898. out[8] = 0;
  3899. out[9] = 0;
  3900. out[10] = 1;
  3901. out[11] = 0;
  3902. out[12] = 0;
  3903. out[13] = 0;
  3904. out[14] = 0;
  3905. out[15] = 1;
  3906. return out;
  3907. }
  3908. /**
  3909. * Transpose the values of a mat4
  3910. *
  3911. * @param {mat4} out the receiving matrix
  3912. * @param {ReadonlyMat4} a the source matrix
  3913. * @returns {mat4} out
  3914. */
  3915. function transpose(out, a) {
  3916. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3917. if (out === a) {
  3918. var a01 = a[1],
  3919. a02 = a[2],
  3920. a03 = a[3];
  3921. var a12 = a[6],
  3922. a13 = a[7];
  3923. var a23 = a[11];
  3924. out[1] = a[4];
  3925. out[2] = a[8];
  3926. out[3] = a[12];
  3927. out[4] = a01;
  3928. out[6] = a[9];
  3929. out[7] = a[13];
  3930. out[8] = a02;
  3931. out[9] = a12;
  3932. out[11] = a[14];
  3933. out[12] = a03;
  3934. out[13] = a13;
  3935. out[14] = a23;
  3936. } else {
  3937. out[0] = a[0];
  3938. out[1] = a[4];
  3939. out[2] = a[8];
  3940. out[3] = a[12];
  3941. out[4] = a[1];
  3942. out[5] = a[5];
  3943. out[6] = a[9];
  3944. out[7] = a[13];
  3945. out[8] = a[2];
  3946. out[9] = a[6];
  3947. out[10] = a[10];
  3948. out[11] = a[14];
  3949. out[12] = a[3];
  3950. out[13] = a[7];
  3951. out[14] = a[11];
  3952. out[15] = a[15];
  3953. }
  3954. return out;
  3955. }
  3956. /**
  3957. * Inverts a mat4
  3958. *
  3959. * @param {mat4} out the receiving matrix
  3960. * @param {ReadonlyMat4} a the source matrix
  3961. * @returns {mat4} out
  3962. */
  3963. function invert$1(out, a) {
  3964. var a00 = a[0],
  3965. a01 = a[1],
  3966. a02 = a[2],
  3967. a03 = a[3];
  3968. var a10 = a[4],
  3969. a11 = a[5],
  3970. a12 = a[6],
  3971. a13 = a[7];
  3972. var a20 = a[8],
  3973. a21 = a[9],
  3974. a22 = a[10],
  3975. a23 = a[11];
  3976. var a30 = a[12],
  3977. a31 = a[13],
  3978. a32 = a[14],
  3979. a33 = a[15];
  3980. var b00 = a00 * a11 - a01 * a10;
  3981. var b01 = a00 * a12 - a02 * a10;
  3982. var b02 = a00 * a13 - a03 * a10;
  3983. var b03 = a01 * a12 - a02 * a11;
  3984. var b04 = a01 * a13 - a03 * a11;
  3985. var b05 = a02 * a13 - a03 * a12;
  3986. var b06 = a20 * a31 - a21 * a30;
  3987. var b07 = a20 * a32 - a22 * a30;
  3988. var b08 = a20 * a33 - a23 * a30;
  3989. var b09 = a21 * a32 - a22 * a31;
  3990. var b10 = a21 * a33 - a23 * a31;
  3991. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  3992. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  3993. if (!det) {
  3994. return null;
  3995. }
  3996. det = 1.0 / det;
  3997. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  3998. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  3999. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4000. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4001. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4002. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4003. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4004. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4005. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4006. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4007. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4008. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4009. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4010. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4011. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4012. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4013. return out;
  4014. }
  4015. /**
  4016. * Calculates the determinant of a mat4
  4017. *
  4018. * @param {ReadonlyMat4} a the source matrix
  4019. * @returns {Number} determinant of a
  4020. */
  4021. function determinant(a) {
  4022. var a00 = a[0],
  4023. a01 = a[1],
  4024. a02 = a[2],
  4025. a03 = a[3];
  4026. var a10 = a[4],
  4027. a11 = a[5],
  4028. a12 = a[6],
  4029. a13 = a[7];
  4030. var a20 = a[8],
  4031. a21 = a[9],
  4032. a22 = a[10],
  4033. a23 = a[11];
  4034. var a30 = a[12],
  4035. a31 = a[13],
  4036. a32 = a[14],
  4037. a33 = a[15];
  4038. var b00 = a00 * a11 - a01 * a10;
  4039. var b01 = a00 * a12 - a02 * a10;
  4040. var b02 = a00 * a13 - a03 * a10;
  4041. var b03 = a01 * a12 - a02 * a11;
  4042. var b04 = a01 * a13 - a03 * a11;
  4043. var b05 = a02 * a13 - a03 * a12;
  4044. var b06 = a20 * a31 - a21 * a30;
  4045. var b07 = a20 * a32 - a22 * a30;
  4046. var b08 = a20 * a33 - a23 * a30;
  4047. var b09 = a21 * a32 - a22 * a31;
  4048. var b10 = a21 * a33 - a23 * a31;
  4049. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4050. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4051. }
  4052. /**
  4053. * Multiplies two mat4s
  4054. *
  4055. * @param {mat4} out the receiving matrix
  4056. * @param {ReadonlyMat4} a the first operand
  4057. * @param {ReadonlyMat4} b the second operand
  4058. * @returns {mat4} out
  4059. */
  4060. function multiply$1(out, a, b) {
  4061. var a00 = a[0],
  4062. a01 = a[1],
  4063. a02 = a[2],
  4064. a03 = a[3];
  4065. var a10 = a[4],
  4066. a11 = a[5],
  4067. a12 = a[6],
  4068. a13 = a[7];
  4069. var a20 = a[8],
  4070. a21 = a[9],
  4071. a22 = a[10],
  4072. a23 = a[11];
  4073. var a30 = a[12],
  4074. a31 = a[13],
  4075. a32 = a[14],
  4076. a33 = a[15]; // Cache only the current line of the second matrix
  4077. var b0 = b[0],
  4078. b1 = b[1],
  4079. b2 = b[2],
  4080. b3 = b[3];
  4081. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4082. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4083. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4084. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4085. b0 = b[4];
  4086. b1 = b[5];
  4087. b2 = b[6];
  4088. b3 = b[7];
  4089. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4090. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4091. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4092. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4093. b0 = b[8];
  4094. b1 = b[9];
  4095. b2 = b[10];
  4096. b3 = b[11];
  4097. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4098. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4099. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4100. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4101. b0 = b[12];
  4102. b1 = b[13];
  4103. b2 = b[14];
  4104. b3 = b[15];
  4105. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4106. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4107. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4108. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4109. return out;
  4110. }
  4111. /**
  4112. * Translate a mat4 by the given vector
  4113. *
  4114. * @param {mat4} out the receiving matrix
  4115. * @param {ReadonlyMat4} a the matrix to translate
  4116. * @param {ReadonlyVec3} v vector to translate by
  4117. * @returns {mat4} out
  4118. */
  4119. function translate(out, a, v) {
  4120. var x = v[0],
  4121. y = v[1],
  4122. z = v[2];
  4123. var a00, a01, a02, a03;
  4124. var a10, a11, a12, a13;
  4125. var a20, a21, a22, a23;
  4126. if (a === out) {
  4127. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4128. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4129. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4130. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4131. } else {
  4132. a00 = a[0];
  4133. a01 = a[1];
  4134. a02 = a[2];
  4135. a03 = a[3];
  4136. a10 = a[4];
  4137. a11 = a[5];
  4138. a12 = a[6];
  4139. a13 = a[7];
  4140. a20 = a[8];
  4141. a21 = a[9];
  4142. a22 = a[10];
  4143. a23 = a[11];
  4144. out[0] = a00;
  4145. out[1] = a01;
  4146. out[2] = a02;
  4147. out[3] = a03;
  4148. out[4] = a10;
  4149. out[5] = a11;
  4150. out[6] = a12;
  4151. out[7] = a13;
  4152. out[8] = a20;
  4153. out[9] = a21;
  4154. out[10] = a22;
  4155. out[11] = a23;
  4156. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4157. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4158. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4159. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4160. }
  4161. return out;
  4162. }
  4163. /**
  4164. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4165. *
  4166. * @param {mat4} out the receiving matrix
  4167. * @param {ReadonlyMat4} a the matrix to scale
  4168. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4169. * @returns {mat4} out
  4170. **/
  4171. function scale$2(out, a, v) {
  4172. var x = v[0],
  4173. y = v[1],
  4174. z = v[2];
  4175. out[0] = a[0] * x;
  4176. out[1] = a[1] * x;
  4177. out[2] = a[2] * x;
  4178. out[3] = a[3] * x;
  4179. out[4] = a[4] * y;
  4180. out[5] = a[5] * y;
  4181. out[6] = a[6] * y;
  4182. out[7] = a[7] * y;
  4183. out[8] = a[8] * z;
  4184. out[9] = a[9] * z;
  4185. out[10] = a[10] * z;
  4186. out[11] = a[11] * z;
  4187. out[12] = a[12];
  4188. out[13] = a[13];
  4189. out[14] = a[14];
  4190. out[15] = a[15];
  4191. return out;
  4192. }
  4193. /**
  4194. * Rotates a mat4 by the given angle around the given axis
  4195. *
  4196. * @param {mat4} out the receiving matrix
  4197. * @param {ReadonlyMat4} a the matrix to rotate
  4198. * @param {Number} rad the angle to rotate the matrix by
  4199. * @param {ReadonlyVec3} axis the axis to rotate around
  4200. * @returns {mat4} out
  4201. */
  4202. function rotate(out, a, rad, axis) {
  4203. var x = axis[0],
  4204. y = axis[1],
  4205. z = axis[2];
  4206. var len = Math.hypot(x, y, z);
  4207. var s, c, t;
  4208. var a00, a01, a02, a03;
  4209. var a10, a11, a12, a13;
  4210. var a20, a21, a22, a23;
  4211. var b00, b01, b02;
  4212. var b10, b11, b12;
  4213. var b20, b21, b22;
  4214. if (len < EPSILON) {
  4215. return null;
  4216. }
  4217. len = 1 / len;
  4218. x *= len;
  4219. y *= len;
  4220. z *= len;
  4221. s = Math.sin(rad);
  4222. c = Math.cos(rad);
  4223. t = 1 - c;
  4224. a00 = a[0];
  4225. a01 = a[1];
  4226. a02 = a[2];
  4227. a03 = a[3];
  4228. a10 = a[4];
  4229. a11 = a[5];
  4230. a12 = a[6];
  4231. a13 = a[7];
  4232. a20 = a[8];
  4233. a21 = a[9];
  4234. a22 = a[10];
  4235. a23 = a[11]; // Construct the elements of the rotation matrix
  4236. b00 = x * x * t + c;
  4237. b01 = y * x * t + z * s;
  4238. b02 = z * x * t - y * s;
  4239. b10 = x * y * t - z * s;
  4240. b11 = y * y * t + c;
  4241. b12 = z * y * t + x * s;
  4242. b20 = x * z * t + y * s;
  4243. b21 = y * z * t - x * s;
  4244. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4245. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4246. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4247. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4248. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4249. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4250. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4251. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4252. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4253. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4254. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4255. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4256. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4257. if (a !== out) {
  4258. // If the source and destination differ, copy the unchanged last row
  4259. out[12] = a[12];
  4260. out[13] = a[13];
  4261. out[14] = a[14];
  4262. out[15] = a[15];
  4263. }
  4264. return out;
  4265. }
  4266. /**
  4267. * Rotates a matrix by the given angle around the X axis
  4268. *
  4269. * @param {mat4} out the receiving matrix
  4270. * @param {ReadonlyMat4} a the matrix to rotate
  4271. * @param {Number} rad the angle to rotate the matrix by
  4272. * @returns {mat4} out
  4273. */
  4274. function rotateX$1(out, a, rad) {
  4275. var s = Math.sin(rad);
  4276. var c = Math.cos(rad);
  4277. var a10 = a[4];
  4278. var a11 = a[5];
  4279. var a12 = a[6];
  4280. var a13 = a[7];
  4281. var a20 = a[8];
  4282. var a21 = a[9];
  4283. var a22 = a[10];
  4284. var a23 = a[11];
  4285. if (a !== out) {
  4286. // If the source and destination differ, copy the unchanged rows
  4287. out[0] = a[0];
  4288. out[1] = a[1];
  4289. out[2] = a[2];
  4290. out[3] = a[3];
  4291. out[12] = a[12];
  4292. out[13] = a[13];
  4293. out[14] = a[14];
  4294. out[15] = a[15];
  4295. } // Perform axis-specific matrix multiplication
  4296. out[4] = a10 * c + a20 * s;
  4297. out[5] = a11 * c + a21 * s;
  4298. out[6] = a12 * c + a22 * s;
  4299. out[7] = a13 * c + a23 * s;
  4300. out[8] = a20 * c - a10 * s;
  4301. out[9] = a21 * c - a11 * s;
  4302. out[10] = a22 * c - a12 * s;
  4303. out[11] = a23 * c - a13 * s;
  4304. return out;
  4305. }
  4306. /**
  4307. * Rotates a matrix by the given angle around the Y axis
  4308. *
  4309. * @param {mat4} out the receiving matrix
  4310. * @param {ReadonlyMat4} a the matrix to rotate
  4311. * @param {Number} rad the angle to rotate the matrix by
  4312. * @returns {mat4} out
  4313. */
  4314. function rotateY$1(out, a, rad) {
  4315. var s = Math.sin(rad);
  4316. var c = Math.cos(rad);
  4317. var a00 = a[0];
  4318. var a01 = a[1];
  4319. var a02 = a[2];
  4320. var a03 = a[3];
  4321. var a20 = a[8];
  4322. var a21 = a[9];
  4323. var a22 = a[10];
  4324. var a23 = a[11];
  4325. if (a !== out) {
  4326. // If the source and destination differ, copy the unchanged rows
  4327. out[4] = a[4];
  4328. out[5] = a[5];
  4329. out[6] = a[6];
  4330. out[7] = a[7];
  4331. out[12] = a[12];
  4332. out[13] = a[13];
  4333. out[14] = a[14];
  4334. out[15] = a[15];
  4335. } // Perform axis-specific matrix multiplication
  4336. out[0] = a00 * c - a20 * s;
  4337. out[1] = a01 * c - a21 * s;
  4338. out[2] = a02 * c - a22 * s;
  4339. out[3] = a03 * c - a23 * s;
  4340. out[8] = a00 * s + a20 * c;
  4341. out[9] = a01 * s + a21 * c;
  4342. out[10] = a02 * s + a22 * c;
  4343. out[11] = a03 * s + a23 * c;
  4344. return out;
  4345. }
  4346. /**
  4347. * Rotates a matrix by the given angle around the Z axis
  4348. *
  4349. * @param {mat4} out the receiving matrix
  4350. * @param {ReadonlyMat4} a the matrix to rotate
  4351. * @param {Number} rad the angle to rotate the matrix by
  4352. * @returns {mat4} out
  4353. */
  4354. function rotateZ$1(out, a, rad) {
  4355. var s = Math.sin(rad);
  4356. var c = Math.cos(rad);
  4357. var a00 = a[0];
  4358. var a01 = a[1];
  4359. var a02 = a[2];
  4360. var a03 = a[3];
  4361. var a10 = a[4];
  4362. var a11 = a[5];
  4363. var a12 = a[6];
  4364. var a13 = a[7];
  4365. if (a !== out) {
  4366. // If the source and destination differ, copy the unchanged last row
  4367. out[8] = a[8];
  4368. out[9] = a[9];
  4369. out[10] = a[10];
  4370. out[11] = a[11];
  4371. out[12] = a[12];
  4372. out[13] = a[13];
  4373. out[14] = a[14];
  4374. out[15] = a[15];
  4375. } // Perform axis-specific matrix multiplication
  4376. out[0] = a00 * c + a10 * s;
  4377. out[1] = a01 * c + a11 * s;
  4378. out[2] = a02 * c + a12 * s;
  4379. out[3] = a03 * c + a13 * s;
  4380. out[4] = a10 * c - a00 * s;
  4381. out[5] = a11 * c - a01 * s;
  4382. out[6] = a12 * c - a02 * s;
  4383. out[7] = a13 * c - a03 * s;
  4384. return out;
  4385. }
  4386. /**
  4387. * Returns the scaling factor component of a transformation
  4388. * matrix. If a matrix is built with fromRotationTranslationScale
  4389. * with a normalized Quaternion paramter, the returned vector will be
  4390. * the same as the scaling vector
  4391. * originally supplied.
  4392. * @param {vec3} out Vector to receive scaling factor component
  4393. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4394. * @return {vec3} out
  4395. */
  4396. function getScaling(out, mat) {
  4397. var m11 = mat[0];
  4398. var m12 = mat[1];
  4399. var m13 = mat[2];
  4400. var m21 = mat[4];
  4401. var m22 = mat[5];
  4402. var m23 = mat[6];
  4403. var m31 = mat[8];
  4404. var m32 = mat[9];
  4405. var m33 = mat[10];
  4406. out[0] = Math.hypot(m11, m12, m13);
  4407. out[1] = Math.hypot(m21, m22, m23);
  4408. out[2] = Math.hypot(m31, m32, m33);
  4409. return out;
  4410. }
  4411. /**
  4412. * Calculates a 4x4 matrix from the given quaternion
  4413. *
  4414. * @param {mat4} out mat4 receiving operation result
  4415. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4416. *
  4417. * @returns {mat4} out
  4418. */
  4419. function fromQuat(out, q) {
  4420. var x = q[0],
  4421. y = q[1],
  4422. z = q[2],
  4423. w = q[3];
  4424. var x2 = x + x;
  4425. var y2 = y + y;
  4426. var z2 = z + z;
  4427. var xx = x * x2;
  4428. var yx = y * x2;
  4429. var yy = y * y2;
  4430. var zx = z * x2;
  4431. var zy = z * y2;
  4432. var zz = z * z2;
  4433. var wx = w * x2;
  4434. var wy = w * y2;
  4435. var wz = w * z2;
  4436. out[0] = 1 - yy - zz;
  4437. out[1] = yx + wz;
  4438. out[2] = zx - wy;
  4439. out[3] = 0;
  4440. out[4] = yx - wz;
  4441. out[5] = 1 - xx - zz;
  4442. out[6] = zy + wx;
  4443. out[7] = 0;
  4444. out[8] = zx + wy;
  4445. out[9] = zy - wx;
  4446. out[10] = 1 - xx - yy;
  4447. out[11] = 0;
  4448. out[12] = 0;
  4449. out[13] = 0;
  4450. out[14] = 0;
  4451. out[15] = 1;
  4452. return out;
  4453. }
  4454. /**
  4455. * Generates a frustum matrix with the given bounds
  4456. *
  4457. * @param {mat4} out mat4 frustum matrix will be written into
  4458. * @param {Number} left Left bound of the frustum
  4459. * @param {Number} right Right bound of the frustum
  4460. * @param {Number} bottom Bottom bound of the frustum
  4461. * @param {Number} top Top bound of the frustum
  4462. * @param {Number} near Near bound of the frustum
  4463. * @param {Number} far Far bound of the frustum
  4464. * @returns {mat4} out
  4465. */
  4466. function frustum(out, left, right, bottom, top, near, far) {
  4467. var rl = 1 / (right - left);
  4468. var tb = 1 / (top - bottom);
  4469. var nf = 1 / (near - far);
  4470. out[0] = near * 2 * rl;
  4471. out[1] = 0;
  4472. out[2] = 0;
  4473. out[3] = 0;
  4474. out[4] = 0;
  4475. out[5] = near * 2 * tb;
  4476. out[6] = 0;
  4477. out[7] = 0;
  4478. out[8] = (right + left) * rl;
  4479. out[9] = (top + bottom) * tb;
  4480. out[10] = (far + near) * nf;
  4481. out[11] = -1;
  4482. out[12] = 0;
  4483. out[13] = 0;
  4484. out[14] = far * near * 2 * nf;
  4485. out[15] = 0;
  4486. return out;
  4487. }
  4488. /**
  4489. * Generates a perspective projection matrix with the given bounds.
  4490. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4491. *
  4492. * @param {mat4} out mat4 frustum matrix will be written into
  4493. * @param {number} fovy Vertical field of view in radians
  4494. * @param {number} aspect Aspect ratio. typically viewport width/height
  4495. * @param {number} near Near bound of the frustum
  4496. * @param {number} far Far bound of the frustum, can be null or Infinity
  4497. * @returns {mat4} out
  4498. */
  4499. function perspective(out, fovy, aspect, near, far) {
  4500. var f = 1.0 / Math.tan(fovy / 2),
  4501. nf;
  4502. out[0] = f / aspect;
  4503. out[1] = 0;
  4504. out[2] = 0;
  4505. out[3] = 0;
  4506. out[4] = 0;
  4507. out[5] = f;
  4508. out[6] = 0;
  4509. out[7] = 0;
  4510. out[8] = 0;
  4511. out[9] = 0;
  4512. out[11] = -1;
  4513. out[12] = 0;
  4514. out[13] = 0;
  4515. out[15] = 0;
  4516. if (far != null && far !== Infinity) {
  4517. nf = 1 / (near - far);
  4518. out[10] = (far + near) * nf;
  4519. out[14] = 2 * far * near * nf;
  4520. } else {
  4521. out[10] = -1;
  4522. out[14] = -2 * near;
  4523. }
  4524. return out;
  4525. }
  4526. /**
  4527. * Generates a orthogonal projection matrix with the given bounds
  4528. *
  4529. * @param {mat4} out mat4 frustum matrix will be written into
  4530. * @param {number} left Left bound of the frustum
  4531. * @param {number} right Right bound of the frustum
  4532. * @param {number} bottom Bottom bound of the frustum
  4533. * @param {number} top Top bound of the frustum
  4534. * @param {number} near Near bound of the frustum
  4535. * @param {number} far Far bound of the frustum
  4536. * @returns {mat4} out
  4537. */
  4538. function ortho(out, left, right, bottom, top, near, far) {
  4539. var lr = 1 / (left - right);
  4540. var bt = 1 / (bottom - top);
  4541. var nf = 1 / (near - far);
  4542. out[0] = -2 * lr;
  4543. out[1] = 0;
  4544. out[2] = 0;
  4545. out[3] = 0;
  4546. out[4] = 0;
  4547. out[5] = -2 * bt;
  4548. out[6] = 0;
  4549. out[7] = 0;
  4550. out[8] = 0;
  4551. out[9] = 0;
  4552. out[10] = 2 * nf;
  4553. out[11] = 0;
  4554. out[12] = (left + right) * lr;
  4555. out[13] = (top + bottom) * bt;
  4556. out[14] = (far + near) * nf;
  4557. out[15] = 1;
  4558. return out;
  4559. }
  4560. /**
  4561. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4562. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4563. *
  4564. * @param {mat4} out mat4 frustum matrix will be written into
  4565. * @param {ReadonlyVec3} eye Position of the viewer
  4566. * @param {ReadonlyVec3} center Point the viewer is looking at
  4567. * @param {ReadonlyVec3} up vec3 pointing up
  4568. * @returns {mat4} out
  4569. */
  4570. function lookAt(out, eye, center, up) {
  4571. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4572. var eyex = eye[0];
  4573. var eyey = eye[1];
  4574. var eyez = eye[2];
  4575. var upx = up[0];
  4576. var upy = up[1];
  4577. var upz = up[2];
  4578. var centerx = center[0];
  4579. var centery = center[1];
  4580. var centerz = center[2];
  4581. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4582. return identity$1(out);
  4583. }
  4584. z0 = eyex - centerx;
  4585. z1 = eyey - centery;
  4586. z2 = eyez - centerz;
  4587. len = 1 / Math.hypot(z0, z1, z2);
  4588. z0 *= len;
  4589. z1 *= len;
  4590. z2 *= len;
  4591. x0 = upy * z2 - upz * z1;
  4592. x1 = upz * z0 - upx * z2;
  4593. x2 = upx * z1 - upy * z0;
  4594. len = Math.hypot(x0, x1, x2);
  4595. if (!len) {
  4596. x0 = 0;
  4597. x1 = 0;
  4598. x2 = 0;
  4599. } else {
  4600. len = 1 / len;
  4601. x0 *= len;
  4602. x1 *= len;
  4603. x2 *= len;
  4604. }
  4605. y0 = z1 * x2 - z2 * x1;
  4606. y1 = z2 * x0 - z0 * x2;
  4607. y2 = z0 * x1 - z1 * x0;
  4608. len = Math.hypot(y0, y1, y2);
  4609. if (!len) {
  4610. y0 = 0;
  4611. y1 = 0;
  4612. y2 = 0;
  4613. } else {
  4614. len = 1 / len;
  4615. y0 *= len;
  4616. y1 *= len;
  4617. y2 *= len;
  4618. }
  4619. out[0] = x0;
  4620. out[1] = y0;
  4621. out[2] = z0;
  4622. out[3] = 0;
  4623. out[4] = x1;
  4624. out[5] = y1;
  4625. out[6] = z1;
  4626. out[7] = 0;
  4627. out[8] = x2;
  4628. out[9] = y2;
  4629. out[10] = z2;
  4630. out[11] = 0;
  4631. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4632. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4633. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4634. out[15] = 1;
  4635. return out;
  4636. }
  4637. /**
  4638. * 4 Dimensional Vector
  4639. * @module vec4
  4640. */
  4641. /**
  4642. * Creates a new, empty vec4
  4643. *
  4644. * @returns {vec4} a new 4D vector
  4645. */
  4646. function create$1() {
  4647. var out = new ARRAY_TYPE(4);
  4648. if (ARRAY_TYPE != Float32Array) {
  4649. out[0] = 0;
  4650. out[1] = 0;
  4651. out[2] = 0;
  4652. out[3] = 0;
  4653. }
  4654. return out;
  4655. }
  4656. /**
  4657. * Adds two vec4's
  4658. *
  4659. * @param {vec4} out the receiving vector
  4660. * @param {ReadonlyVec4} a the first operand
  4661. * @param {ReadonlyVec4} b the second operand
  4662. * @returns {vec4} out
  4663. */
  4664. function add$1(out, a, b) {
  4665. out[0] = a[0] + b[0];
  4666. out[1] = a[1] + b[1];
  4667. out[2] = a[2] + b[2];
  4668. out[3] = a[3] + b[3];
  4669. return out;
  4670. }
  4671. /**
  4672. * Scales a vec4 by a scalar number
  4673. *
  4674. * @param {vec4} out the receiving vector
  4675. * @param {ReadonlyVec4} a the vector to scale
  4676. * @param {Number} b amount to scale the vector by
  4677. * @returns {vec4} out
  4678. */
  4679. function scale$1(out, a, b) {
  4680. out[0] = a[0] * b;
  4681. out[1] = a[1] * b;
  4682. out[2] = a[2] * b;
  4683. out[3] = a[3] * b;
  4684. return out;
  4685. }
  4686. /**
  4687. * Calculates the length of a vec4
  4688. *
  4689. * @param {ReadonlyVec4} a vector to calculate length of
  4690. * @returns {Number} length of a
  4691. */
  4692. function length$1(a) {
  4693. var x = a[0];
  4694. var y = a[1];
  4695. var z = a[2];
  4696. var w = a[3];
  4697. return Math.hypot(x, y, z, w);
  4698. }
  4699. /**
  4700. * Calculates the squared length of a vec4
  4701. *
  4702. * @param {ReadonlyVec4} a vector to calculate squared length of
  4703. * @returns {Number} squared length of a
  4704. */
  4705. function squaredLength$1(a) {
  4706. var x = a[0];
  4707. var y = a[1];
  4708. var z = a[2];
  4709. var w = a[3];
  4710. return x * x + y * y + z * z + w * w;
  4711. }
  4712. /**
  4713. * Normalize a vec4
  4714. *
  4715. * @param {vec4} out the receiving vector
  4716. * @param {ReadonlyVec4} a vector to normalize
  4717. * @returns {vec4} out
  4718. */
  4719. function normalize$1(out, a) {
  4720. var x = a[0];
  4721. var y = a[1];
  4722. var z = a[2];
  4723. var w = a[3];
  4724. var len = x * x + y * y + z * z + w * w;
  4725. if (len > 0) {
  4726. len = 1 / Math.sqrt(len);
  4727. }
  4728. out[0] = x * len;
  4729. out[1] = y * len;
  4730. out[2] = z * len;
  4731. out[3] = w * len;
  4732. return out;
  4733. }
  4734. /**
  4735. * Calculates the dot product of two vec4's
  4736. *
  4737. * @param {ReadonlyVec4} a the first operand
  4738. * @param {ReadonlyVec4} b the second operand
  4739. * @returns {Number} dot product of a and b
  4740. */
  4741. function dot$1(a, b) {
  4742. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4743. }
  4744. /**
  4745. * Performs a linear interpolation between two vec4's
  4746. *
  4747. * @param {vec4} out the receiving vector
  4748. * @param {ReadonlyVec4} a the first operand
  4749. * @param {ReadonlyVec4} b the second operand
  4750. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4751. * @returns {vec4} out
  4752. */
  4753. function lerp$1(out, a, b, t) {
  4754. var ax = a[0];
  4755. var ay = a[1];
  4756. var az = a[2];
  4757. var aw = a[3];
  4758. out[0] = ax + t * (b[0] - ax);
  4759. out[1] = ay + t * (b[1] - ay);
  4760. out[2] = az + t * (b[2] - az);
  4761. out[3] = aw + t * (b[3] - aw);
  4762. return out;
  4763. }
  4764. /**
  4765. * Transforms the vec4 with a mat4.
  4766. *
  4767. * @param {vec4} out the receiving vector
  4768. * @param {ReadonlyVec4} a the vector to transform
  4769. * @param {ReadonlyMat4} m matrix to transform with
  4770. * @returns {vec4} out
  4771. */
  4772. function transformMat4(out, a, m) {
  4773. var x = a[0],
  4774. y = a[1],
  4775. z = a[2],
  4776. w = a[3];
  4777. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4778. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4779. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4780. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4781. return out;
  4782. }
  4783. /**
  4784. * Transforms the vec4 with a quat
  4785. *
  4786. * @param {vec4} out the receiving vector
  4787. * @param {ReadonlyVec4} a the vector to transform
  4788. * @param {ReadonlyQuat} q quaternion to transform with
  4789. * @returns {vec4} out
  4790. */
  4791. function transformQuat(out, a, q) {
  4792. var x = a[0],
  4793. y = a[1],
  4794. z = a[2];
  4795. var qx = q[0],
  4796. qy = q[1],
  4797. qz = q[2],
  4798. qw = q[3]; // calculate quat * vec
  4799. var ix = qw * x + qy * z - qz * y;
  4800. var iy = qw * y + qz * x - qx * z;
  4801. var iz = qw * z + qx * y - qy * x;
  4802. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4803. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4804. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4805. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4806. out[3] = a[3];
  4807. return out;
  4808. }
  4809. /**
  4810. * Perform some operation over an array of vec4s.
  4811. *
  4812. * @param {Array} a the array of vectors to iterate over
  4813. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4814. * @param {Number} offset Number of elements to skip at the beginning of the array
  4815. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4816. * @param {Function} fn Function to call for each vector in the array
  4817. * @param {Object} [arg] additional argument to pass to fn
  4818. * @returns {Array} a
  4819. * @function
  4820. */
  4821. (function () {
  4822. var vec = create$1();
  4823. return function (a, stride, offset, count, fn, arg) {
  4824. var i, l;
  4825. if (!stride) {
  4826. stride = 4;
  4827. }
  4828. if (!offset) {
  4829. offset = 0;
  4830. }
  4831. if (count) {
  4832. l = Math.min(count * stride + offset, a.length);
  4833. } else {
  4834. l = a.length;
  4835. }
  4836. for (i = offset; i < l; i += stride) {
  4837. vec[0] = a[i];
  4838. vec[1] = a[i + 1];
  4839. vec[2] = a[i + 2];
  4840. vec[3] = a[i + 3];
  4841. fn(vec, vec, arg);
  4842. a[i] = vec[0];
  4843. a[i + 1] = vec[1];
  4844. a[i + 2] = vec[2];
  4845. a[i + 3] = vec[3];
  4846. }
  4847. return a;
  4848. };
  4849. })();
  4850. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4851. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4852. const INDICES = Object.freeze({
  4853. COL0ROW0: 0,
  4854. COL0ROW1: 1,
  4855. COL0ROW2: 2,
  4856. COL0ROW3: 3,
  4857. COL1ROW0: 4,
  4858. COL1ROW1: 5,
  4859. COL1ROW2: 6,
  4860. COL1ROW3: 7,
  4861. COL2ROW0: 8,
  4862. COL2ROW1: 9,
  4863. COL2ROW2: 10,
  4864. COL2ROW3: 11,
  4865. COL3ROW0: 12,
  4866. COL3ROW1: 13,
  4867. COL3ROW2: 14,
  4868. COL3ROW3: 15
  4869. });
  4870. const constants = {};
  4871. class Matrix4 extends Matrix {
  4872. static get IDENTITY() {
  4873. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4874. return constants.IDENTITY;
  4875. }
  4876. static get ZERO() {
  4877. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4878. return constants.ZERO;
  4879. }
  4880. get INDICES() {
  4881. return INDICES;
  4882. }
  4883. get ELEMENTS() {
  4884. return 16;
  4885. }
  4886. get RANK() {
  4887. return 4;
  4888. }
  4889. constructor(array) {
  4890. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4891. if (arguments.length === 1 && Array.isArray(array)) {
  4892. this.copy(array);
  4893. } else {
  4894. this.identity();
  4895. }
  4896. }
  4897. copy(array) {
  4898. this[0] = array[0];
  4899. this[1] = array[1];
  4900. this[2] = array[2];
  4901. this[3] = array[3];
  4902. this[4] = array[4];
  4903. this[5] = array[5];
  4904. this[6] = array[6];
  4905. this[7] = array[7];
  4906. this[8] = array[8];
  4907. this[9] = array[9];
  4908. this[10] = array[10];
  4909. this[11] = array[11];
  4910. this[12] = array[12];
  4911. this[13] = array[13];
  4912. this[14] = array[14];
  4913. this[15] = array[15];
  4914. return this.check();
  4915. }
  4916. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4917. this[0] = m00;
  4918. this[1] = m10;
  4919. this[2] = m20;
  4920. this[3] = m30;
  4921. this[4] = m01;
  4922. this[5] = m11;
  4923. this[6] = m21;
  4924. this[7] = m31;
  4925. this[8] = m02;
  4926. this[9] = m12;
  4927. this[10] = m22;
  4928. this[11] = m32;
  4929. this[12] = m03;
  4930. this[13] = m13;
  4931. this[14] = m23;
  4932. this[15] = m33;
  4933. return this.check();
  4934. }
  4935. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4936. this[0] = m00;
  4937. this[1] = m10;
  4938. this[2] = m20;
  4939. this[3] = m30;
  4940. this[4] = m01;
  4941. this[5] = m11;
  4942. this[6] = m21;
  4943. this[7] = m31;
  4944. this[8] = m02;
  4945. this[9] = m12;
  4946. this[10] = m22;
  4947. this[11] = m32;
  4948. this[12] = m03;
  4949. this[13] = m13;
  4950. this[14] = m23;
  4951. this[15] = m33;
  4952. return this.check();
  4953. }
  4954. toRowMajor(result) {
  4955. result[0] = this[0];
  4956. result[1] = this[4];
  4957. result[2] = this[8];
  4958. result[3] = this[12];
  4959. result[4] = this[1];
  4960. result[5] = this[5];
  4961. result[6] = this[9];
  4962. result[7] = this[13];
  4963. result[8] = this[2];
  4964. result[9] = this[6];
  4965. result[10] = this[10];
  4966. result[11] = this[14];
  4967. result[12] = this[3];
  4968. result[13] = this[7];
  4969. result[14] = this[11];
  4970. result[15] = this[15];
  4971. return result;
  4972. }
  4973. identity() {
  4974. return this.copy(IDENTITY);
  4975. }
  4976. fromQuaternion(q) {
  4977. fromQuat(this, q);
  4978. return this.check();
  4979. }
  4980. frustum({
  4981. left,
  4982. right,
  4983. bottom,
  4984. top,
  4985. near,
  4986. far
  4987. }) {
  4988. if (far === Infinity) {
  4989. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  4990. } else {
  4991. frustum(this, left, right, bottom, top, near, far);
  4992. }
  4993. return this.check();
  4994. }
  4995. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  4996. const column0Row0 = 2.0 * near / (right - left);
  4997. const column1Row1 = 2.0 * near / (top - bottom);
  4998. const column2Row0 = (right + left) / (right - left);
  4999. const column2Row1 = (top + bottom) / (top - bottom);
  5000. const column2Row2 = -1.0;
  5001. const column2Row3 = -1.0;
  5002. const column3Row2 = -2.0 * near;
  5003. result[0] = column0Row0;
  5004. result[1] = 0.0;
  5005. result[2] = 0.0;
  5006. result[3] = 0.0;
  5007. result[4] = 0.0;
  5008. result[5] = column1Row1;
  5009. result[6] = 0.0;
  5010. result[7] = 0.0;
  5011. result[8] = column2Row0;
  5012. result[9] = column2Row1;
  5013. result[10] = column2Row2;
  5014. result[11] = column2Row3;
  5015. result[12] = 0.0;
  5016. result[13] = 0.0;
  5017. result[14] = column3Row2;
  5018. result[15] = 0.0;
  5019. return result;
  5020. }
  5021. lookAt(eye, center, up) {
  5022. if (arguments.length === 1) {
  5023. ({
  5024. eye,
  5025. center,
  5026. up
  5027. } = eye);
  5028. }
  5029. center = center || [0, 0, 0];
  5030. up = up || [0, 1, 0];
  5031. lookAt(this, eye, center, up);
  5032. return this.check();
  5033. }
  5034. ortho({
  5035. left,
  5036. right,
  5037. bottom,
  5038. top,
  5039. near = 0.1,
  5040. far = 500
  5041. }) {
  5042. ortho(this, left, right, bottom, top, near, far);
  5043. return this.check();
  5044. }
  5045. orthographic({
  5046. fovy = 45 * Math.PI / 180,
  5047. aspect = 1,
  5048. focalDistance = 1,
  5049. near = 0.1,
  5050. far = 500
  5051. }) {
  5052. if (fovy > Math.PI * 2) {
  5053. throw Error('radians');
  5054. }
  5055. const halfY = fovy / 2;
  5056. const top = focalDistance * Math.tan(halfY);
  5057. const right = top * aspect;
  5058. return new Matrix4().ortho({
  5059. left: -right,
  5060. right,
  5061. bottom: -top,
  5062. top,
  5063. near,
  5064. far
  5065. });
  5066. }
  5067. perspective({
  5068. fovy = undefined,
  5069. fov = 45 * Math.PI / 180,
  5070. aspect = 1,
  5071. near = 0.1,
  5072. far = 500
  5073. } = {}) {
  5074. fovy = fovy || fov;
  5075. if (fovy > Math.PI * 2) {
  5076. throw Error('radians');
  5077. }
  5078. perspective(this, fovy, aspect, near, far);
  5079. return this.check();
  5080. }
  5081. determinant() {
  5082. return determinant(this);
  5083. }
  5084. getScale(result = [-0, -0, -0]) {
  5085. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5086. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5087. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5088. return result;
  5089. }
  5090. getTranslation(result = [-0, -0, -0]) {
  5091. result[0] = this[12];
  5092. result[1] = this[13];
  5093. result[2] = this[14];
  5094. return result;
  5095. }
  5096. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5097. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5098. const inverseScale0 = 1 / scale[0];
  5099. const inverseScale1 = 1 / scale[1];
  5100. const inverseScale2 = 1 / scale[2];
  5101. result[0] = this[0] * inverseScale0;
  5102. result[1] = this[1] * inverseScale1;
  5103. result[2] = this[2] * inverseScale2;
  5104. result[3] = 0;
  5105. result[4] = this[4] * inverseScale0;
  5106. result[5] = this[5] * inverseScale1;
  5107. result[6] = this[6] * inverseScale2;
  5108. result[7] = 0;
  5109. result[8] = this[8] * inverseScale0;
  5110. result[9] = this[9] * inverseScale1;
  5111. result[10] = this[10] * inverseScale2;
  5112. result[11] = 0;
  5113. result[12] = 0;
  5114. result[13] = 0;
  5115. result[14] = 0;
  5116. result[15] = 1;
  5117. return result;
  5118. }
  5119. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5120. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5121. const inverseScale0 = 1 / scale[0];
  5122. const inverseScale1 = 1 / scale[1];
  5123. const inverseScale2 = 1 / scale[2];
  5124. result[0] = this[0] * inverseScale0;
  5125. result[1] = this[1] * inverseScale1;
  5126. result[2] = this[2] * inverseScale2;
  5127. result[3] = this[4] * inverseScale0;
  5128. result[4] = this[5] * inverseScale1;
  5129. result[5] = this[6] * inverseScale2;
  5130. result[6] = this[8] * inverseScale0;
  5131. result[7] = this[9] * inverseScale1;
  5132. result[8] = this[10] * inverseScale2;
  5133. return result;
  5134. }
  5135. transpose() {
  5136. transpose(this, this);
  5137. return this.check();
  5138. }
  5139. invert() {
  5140. invert$1(this, this);
  5141. return this.check();
  5142. }
  5143. multiplyLeft(a) {
  5144. multiply$1(this, a, this);
  5145. return this.check();
  5146. }
  5147. multiplyRight(a) {
  5148. multiply$1(this, this, a);
  5149. return this.check();
  5150. }
  5151. rotateX(radians) {
  5152. rotateX$1(this, this, radians);
  5153. return this.check();
  5154. }
  5155. rotateY(radians) {
  5156. rotateY$1(this, this, radians);
  5157. return this.check();
  5158. }
  5159. rotateZ(radians) {
  5160. rotateZ$1(this, this, radians);
  5161. return this.check();
  5162. }
  5163. rotateXYZ([rx, ry, rz]) {
  5164. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5165. }
  5166. rotateAxis(radians, axis) {
  5167. rotate(this, this, radians, axis);
  5168. return this.check();
  5169. }
  5170. scale(factor) {
  5171. if (Array.isArray(factor)) {
  5172. scale$2(this, this, factor);
  5173. } else {
  5174. scale$2(this, this, [factor, factor, factor]);
  5175. }
  5176. return this.check();
  5177. }
  5178. translate(vec) {
  5179. translate(this, this, vec);
  5180. return this.check();
  5181. }
  5182. transform(vector, result) {
  5183. if (vector.length === 4) {
  5184. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5185. checkVector(result, 4);
  5186. return result;
  5187. }
  5188. return this.transformAsPoint(vector, result);
  5189. }
  5190. transformAsPoint(vector, result) {
  5191. const {
  5192. length
  5193. } = vector;
  5194. switch (length) {
  5195. case 2:
  5196. result = transformMat4$2(result || [-0, -0], vector, this);
  5197. break;
  5198. case 3:
  5199. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5200. break;
  5201. default:
  5202. throw new Error('Illegal vector');
  5203. }
  5204. checkVector(result, vector.length);
  5205. return result;
  5206. }
  5207. transformAsVector(vector, result) {
  5208. switch (vector.length) {
  5209. case 2:
  5210. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5211. break;
  5212. case 3:
  5213. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5214. break;
  5215. default:
  5216. throw new Error('Illegal vector');
  5217. }
  5218. checkVector(result, vector.length);
  5219. return result;
  5220. }
  5221. makeRotationX(radians) {
  5222. return this.identity().rotateX(radians);
  5223. }
  5224. makeTranslation(x, y, z) {
  5225. return this.identity().translate([x, y, z]);
  5226. }
  5227. transformPoint(vector, result) {
  5228. deprecated('Matrix4.transformPoint', '3.0');
  5229. return this.transformAsPoint(vector, result);
  5230. }
  5231. transformVector(vector, result) {
  5232. deprecated('Matrix4.transformVector', '3.0');
  5233. return this.transformAsPoint(vector, result);
  5234. }
  5235. transformDirection(vector, result) {
  5236. deprecated('Matrix4.transformDirection', '3.0');
  5237. return this.transformAsVector(vector, result);
  5238. }
  5239. }
  5240. /**
  5241. * Quaternion
  5242. * @module quat
  5243. */
  5244. /**
  5245. * Creates a new identity quat
  5246. *
  5247. * @returns {quat} a new quaternion
  5248. */
  5249. function create() {
  5250. var out = new ARRAY_TYPE(4);
  5251. if (ARRAY_TYPE != Float32Array) {
  5252. out[0] = 0;
  5253. out[1] = 0;
  5254. out[2] = 0;
  5255. }
  5256. out[3] = 1;
  5257. return out;
  5258. }
  5259. /**
  5260. * Set a quat to the identity quaternion
  5261. *
  5262. * @param {quat} out the receiving quaternion
  5263. * @returns {quat} out
  5264. */
  5265. function identity(out) {
  5266. out[0] = 0;
  5267. out[1] = 0;
  5268. out[2] = 0;
  5269. out[3] = 1;
  5270. return out;
  5271. }
  5272. /**
  5273. * Sets a quat from the given angle and rotation axis,
  5274. * then returns it.
  5275. *
  5276. * @param {quat} out the receiving quaternion
  5277. * @param {ReadonlyVec3} axis the axis around which to rotate
  5278. * @param {Number} rad the angle in radians
  5279. * @returns {quat} out
  5280. **/
  5281. function setAxisAngle(out, axis, rad) {
  5282. rad = rad * 0.5;
  5283. var s = Math.sin(rad);
  5284. out[0] = s * axis[0];
  5285. out[1] = s * axis[1];
  5286. out[2] = s * axis[2];
  5287. out[3] = Math.cos(rad);
  5288. return out;
  5289. }
  5290. /**
  5291. * Multiplies two quat's
  5292. *
  5293. * @param {quat} out the receiving quaternion
  5294. * @param {ReadonlyQuat} a the first operand
  5295. * @param {ReadonlyQuat} b the second operand
  5296. * @returns {quat} out
  5297. */
  5298. function multiply(out, a, b) {
  5299. var ax = a[0],
  5300. ay = a[1],
  5301. az = a[2],
  5302. aw = a[3];
  5303. var bx = b[0],
  5304. by = b[1],
  5305. bz = b[2],
  5306. bw = b[3];
  5307. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5308. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5309. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5310. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5311. return out;
  5312. }
  5313. /**
  5314. * Rotates a quaternion by the given angle about the X axis
  5315. *
  5316. * @param {quat} out quat receiving operation result
  5317. * @param {ReadonlyQuat} a quat to rotate
  5318. * @param {number} rad angle (in radians) to rotate
  5319. * @returns {quat} out
  5320. */
  5321. function rotateX(out, a, rad) {
  5322. rad *= 0.5;
  5323. var ax = a[0],
  5324. ay = a[1],
  5325. az = a[2],
  5326. aw = a[3];
  5327. var bx = Math.sin(rad),
  5328. bw = Math.cos(rad);
  5329. out[0] = ax * bw + aw * bx;
  5330. out[1] = ay * bw + az * bx;
  5331. out[2] = az * bw - ay * bx;
  5332. out[3] = aw * bw - ax * bx;
  5333. return out;
  5334. }
  5335. /**
  5336. * Rotates a quaternion by the given angle about the Y 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 rotateY(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 by = Math.sin(rad),
  5350. bw = Math.cos(rad);
  5351. out[0] = ax * bw - az * by;
  5352. out[1] = ay * bw + aw * by;
  5353. out[2] = az * bw + ax * by;
  5354. out[3] = aw * bw - ay * by;
  5355. return out;
  5356. }
  5357. /**
  5358. * Rotates a quaternion by the given angle about the Z 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 rotateZ(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 bz = Math.sin(rad),
  5372. bw = Math.cos(rad);
  5373. out[0] = ax * bw + ay * bz;
  5374. out[1] = ay * bw - ax * bz;
  5375. out[2] = az * bw + aw * bz;
  5376. out[3] = aw * bw - az * bz;
  5377. return out;
  5378. }
  5379. /**
  5380. * Calculates the W component of a quat from the X, Y, and Z components.
  5381. * Assumes that quaternion is 1 unit in length.
  5382. * Any existing W component will be ignored.
  5383. *
  5384. * @param {quat} out the receiving quaternion
  5385. * @param {ReadonlyQuat} a quat to calculate W component of
  5386. * @returns {quat} out
  5387. */
  5388. function calculateW(out, a) {
  5389. var x = a[0],
  5390. y = a[1],
  5391. z = a[2];
  5392. out[0] = x;
  5393. out[1] = y;
  5394. out[2] = z;
  5395. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5396. return out;
  5397. }
  5398. /**
  5399. * Performs a spherical linear interpolation between two quat
  5400. *
  5401. * @param {quat} out the receiving quaternion
  5402. * @param {ReadonlyQuat} a the first operand
  5403. * @param {ReadonlyQuat} b the second operand
  5404. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5405. * @returns {quat} out
  5406. */
  5407. function slerp(out, a, b, t) {
  5408. // benchmarks:
  5409. // http://jsperf.com/quaternion-slerp-implementations
  5410. var ax = a[0],
  5411. ay = a[1],
  5412. az = a[2],
  5413. aw = a[3];
  5414. var bx = b[0],
  5415. by = b[1],
  5416. bz = b[2],
  5417. bw = b[3];
  5418. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5419. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5420. if (cosom < 0.0) {
  5421. cosom = -cosom;
  5422. bx = -bx;
  5423. by = -by;
  5424. bz = -bz;
  5425. bw = -bw;
  5426. } // calculate coefficients
  5427. if (1.0 - cosom > EPSILON) {
  5428. // standard case (slerp)
  5429. omega = Math.acos(cosom);
  5430. sinom = Math.sin(omega);
  5431. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5432. scale1 = Math.sin(t * omega) / sinom;
  5433. } else {
  5434. // "from" and "to" quaternions are very close
  5435. // ... so we can do a linear interpolation
  5436. scale0 = 1.0 - t;
  5437. scale1 = t;
  5438. } // calculate final values
  5439. out[0] = scale0 * ax + scale1 * bx;
  5440. out[1] = scale0 * ay + scale1 * by;
  5441. out[2] = scale0 * az + scale1 * bz;
  5442. out[3] = scale0 * aw + scale1 * bw;
  5443. return out;
  5444. }
  5445. /**
  5446. * Calculates the inverse of a quat
  5447. *
  5448. * @param {quat} out the receiving quaternion
  5449. * @param {ReadonlyQuat} a quat to calculate inverse of
  5450. * @returns {quat} out
  5451. */
  5452. function invert(out, a) {
  5453. var a0 = a[0],
  5454. a1 = a[1],
  5455. a2 = a[2],
  5456. a3 = a[3];
  5457. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5458. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5459. out[0] = -a0 * invDot;
  5460. out[1] = -a1 * invDot;
  5461. out[2] = -a2 * invDot;
  5462. out[3] = a3 * invDot;
  5463. return out;
  5464. }
  5465. /**
  5466. * Calculates the conjugate of a quat
  5467. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5468. *
  5469. * @param {quat} out the receiving quaternion
  5470. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5471. * @returns {quat} out
  5472. */
  5473. function conjugate(out, a) {
  5474. out[0] = -a[0];
  5475. out[1] = -a[1];
  5476. out[2] = -a[2];
  5477. out[3] = a[3];
  5478. return out;
  5479. }
  5480. /**
  5481. * Creates a quaternion from the given 3x3 rotation matrix.
  5482. *
  5483. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5484. * to renormalize the quaternion yourself where necessary.
  5485. *
  5486. * @param {quat} out the receiving quaternion
  5487. * @param {ReadonlyMat3} m rotation matrix
  5488. * @returns {quat} out
  5489. * @function
  5490. */
  5491. function fromMat3(out, m) {
  5492. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5493. // article "Quaternion Calculus and Fast Animation".
  5494. var fTrace = m[0] + m[4] + m[8];
  5495. var fRoot;
  5496. if (fTrace > 0.0) {
  5497. // |w| > 1/2, may as well choose w > 1/2
  5498. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5499. out[3] = 0.5 * fRoot;
  5500. fRoot = 0.5 / fRoot; // 1/(4w)
  5501. out[0] = (m[5] - m[7]) * fRoot;
  5502. out[1] = (m[6] - m[2]) * fRoot;
  5503. out[2] = (m[1] - m[3]) * fRoot;
  5504. } else {
  5505. // |w| <= 1/2
  5506. var i = 0;
  5507. if (m[4] > m[0]) i = 1;
  5508. if (m[8] > m[i * 3 + i]) i = 2;
  5509. var j = (i + 1) % 3;
  5510. var k = (i + 2) % 3;
  5511. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5512. out[i] = 0.5 * fRoot;
  5513. fRoot = 0.5 / fRoot;
  5514. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5515. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5516. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5517. }
  5518. return out;
  5519. }
  5520. /**
  5521. * Adds two quat's
  5522. *
  5523. * @param {quat} out the receiving quaternion
  5524. * @param {ReadonlyQuat} a the first operand
  5525. * @param {ReadonlyQuat} b the second operand
  5526. * @returns {quat} out
  5527. * @function
  5528. */
  5529. var add = add$1;
  5530. /**
  5531. * Scales a quat by a scalar number
  5532. *
  5533. * @param {quat} out the receiving vector
  5534. * @param {ReadonlyQuat} a the vector to scale
  5535. * @param {Number} b amount to scale the vector by
  5536. * @returns {quat} out
  5537. * @function
  5538. */
  5539. var scale = scale$1;
  5540. /**
  5541. * Calculates the dot product of two quat's
  5542. *
  5543. * @param {ReadonlyQuat} a the first operand
  5544. * @param {ReadonlyQuat} b the second operand
  5545. * @returns {Number} dot product of a and b
  5546. * @function
  5547. */
  5548. var dot = dot$1;
  5549. /**
  5550. * Performs a linear interpolation between two quat's
  5551. *
  5552. * @param {quat} out the receiving quaternion
  5553. * @param {ReadonlyQuat} a the first operand
  5554. * @param {ReadonlyQuat} b the second operand
  5555. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5556. * @returns {quat} out
  5557. * @function
  5558. */
  5559. var lerp = lerp$1;
  5560. /**
  5561. * Calculates the length of a quat
  5562. *
  5563. * @param {ReadonlyQuat} a vector to calculate length of
  5564. * @returns {Number} length of a
  5565. */
  5566. var length = length$1;
  5567. /**
  5568. * Calculates the squared length of a quat
  5569. *
  5570. * @param {ReadonlyQuat} a vector to calculate squared length of
  5571. * @returns {Number} squared length of a
  5572. * @function
  5573. */
  5574. var squaredLength = squaredLength$1;
  5575. /**
  5576. * Normalize a quat
  5577. *
  5578. * @param {quat} out the receiving quaternion
  5579. * @param {ReadonlyQuat} a quaternion to normalize
  5580. * @returns {quat} out
  5581. * @function
  5582. */
  5583. var normalize = normalize$1;
  5584. /**
  5585. * Sets a quaternion to represent the shortest rotation from one
  5586. * vector to another.
  5587. *
  5588. * Both vectors are assumed to be unit length.
  5589. *
  5590. * @param {quat} out the receiving quaternion.
  5591. * @param {ReadonlyVec3} a the initial vector
  5592. * @param {ReadonlyVec3} b the destination vector
  5593. * @returns {quat} out
  5594. */
  5595. var rotationTo = function () {
  5596. var tmpvec3 = create$3();
  5597. var xUnitVec3 = fromValues(1, 0, 0);
  5598. var yUnitVec3 = fromValues(0, 1, 0);
  5599. return function (out, a, b) {
  5600. var dot = dot$2(a, b);
  5601. if (dot < -0.999999) {
  5602. cross(tmpvec3, xUnitVec3, a);
  5603. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5604. normalize$2(tmpvec3, tmpvec3);
  5605. setAxisAngle(out, tmpvec3, Math.PI);
  5606. return out;
  5607. } else if (dot > 0.999999) {
  5608. out[0] = 0;
  5609. out[1] = 0;
  5610. out[2] = 0;
  5611. out[3] = 1;
  5612. return out;
  5613. } else {
  5614. cross(tmpvec3, a, b);
  5615. out[0] = tmpvec3[0];
  5616. out[1] = tmpvec3[1];
  5617. out[2] = tmpvec3[2];
  5618. out[3] = 1 + dot;
  5619. return normalize(out, out);
  5620. }
  5621. };
  5622. }();
  5623. /**
  5624. * Performs a spherical linear interpolation with two control points
  5625. *
  5626. * @param {quat} out the receiving quaternion
  5627. * @param {ReadonlyQuat} a the first operand
  5628. * @param {ReadonlyQuat} b the second operand
  5629. * @param {ReadonlyQuat} c the third operand
  5630. * @param {ReadonlyQuat} d the fourth operand
  5631. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5632. * @returns {quat} out
  5633. */
  5634. (function () {
  5635. var temp1 = create();
  5636. var temp2 = create();
  5637. return function (out, a, b, c, d, t) {
  5638. slerp(temp1, a, d, t);
  5639. slerp(temp2, b, c, t);
  5640. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5641. return out;
  5642. };
  5643. })();
  5644. /**
  5645. * Sets the specified quaternion with values corresponding to the given
  5646. * axes. Each axis is a vec3 and is expected to be unit length and
  5647. * perpendicular to all other specified axes.
  5648. *
  5649. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5650. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5651. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5652. * @returns {quat} out
  5653. */
  5654. (function () {
  5655. var matr = create$2();
  5656. return function (out, view, right, up) {
  5657. matr[0] = right[0];
  5658. matr[3] = right[1];
  5659. matr[6] = right[2];
  5660. matr[1] = up[0];
  5661. matr[4] = up[1];
  5662. matr[7] = up[2];
  5663. matr[2] = -view[0];
  5664. matr[5] = -view[1];
  5665. matr[8] = -view[2];
  5666. return normalize(out, fromMat3(out, matr));
  5667. };
  5668. })();
  5669. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5670. class Quaternion extends MathArray {
  5671. constructor(x = 0, y = 0, z = 0, w = 1) {
  5672. super(-0, -0, -0, -0);
  5673. if (Array.isArray(x) && arguments.length === 1) {
  5674. this.copy(x);
  5675. } else {
  5676. this.set(x, y, z, w);
  5677. }
  5678. }
  5679. copy(array) {
  5680. this[0] = array[0];
  5681. this[1] = array[1];
  5682. this[2] = array[2];
  5683. this[3] = array[3];
  5684. return this.check();
  5685. }
  5686. set(x, y, z, w) {
  5687. this[0] = x;
  5688. this[1] = y;
  5689. this[2] = z;
  5690. this[3] = w;
  5691. return this.check();
  5692. }
  5693. fromMatrix3(m) {
  5694. fromMat3(this, m);
  5695. return this.check();
  5696. }
  5697. identity() {
  5698. identity(this);
  5699. return this.check();
  5700. }
  5701. fromAxisRotation(axis, rad) {
  5702. setAxisAngle(this, axis, rad);
  5703. return this.check();
  5704. }
  5705. setAxisAngle(axis, rad) {
  5706. return this.fromAxisRotation(axis, rad);
  5707. }
  5708. get ELEMENTS() {
  5709. return 4;
  5710. }
  5711. get x() {
  5712. return this[0];
  5713. }
  5714. set x(value) {
  5715. this[0] = checkNumber(value);
  5716. }
  5717. get y() {
  5718. return this[1];
  5719. }
  5720. set y(value) {
  5721. this[1] = checkNumber(value);
  5722. }
  5723. get z() {
  5724. return this[2];
  5725. }
  5726. set z(value) {
  5727. this[2] = checkNumber(value);
  5728. }
  5729. get w() {
  5730. return this[3];
  5731. }
  5732. set w(value) {
  5733. this[3] = checkNumber(value);
  5734. }
  5735. len() {
  5736. return length(this);
  5737. }
  5738. lengthSquared() {
  5739. return squaredLength(this);
  5740. }
  5741. dot(a, b) {
  5742. if (b !== undefined) {
  5743. throw new Error('Quaternion.dot only takes one argument');
  5744. }
  5745. return dot(this, a);
  5746. }
  5747. rotationTo(vectorA, vectorB) {
  5748. rotationTo(this, vectorA, vectorB);
  5749. return this.check();
  5750. }
  5751. add(a, b) {
  5752. if (b !== undefined) {
  5753. throw new Error('Quaternion.add only takes one argument');
  5754. }
  5755. add(this, this, a);
  5756. return this.check();
  5757. }
  5758. calculateW() {
  5759. calculateW(this, this);
  5760. return this.check();
  5761. }
  5762. conjugate() {
  5763. conjugate(this, this);
  5764. return this.check();
  5765. }
  5766. invert() {
  5767. invert(this, this);
  5768. return this.check();
  5769. }
  5770. lerp(a, b, t) {
  5771. lerp(this, a, b, t);
  5772. return this.check();
  5773. }
  5774. multiplyRight(a, b) {
  5775. assert$4(!b);
  5776. multiply(this, this, a);
  5777. return this.check();
  5778. }
  5779. multiplyLeft(a, b) {
  5780. assert$4(!b);
  5781. multiply(this, a, this);
  5782. return this.check();
  5783. }
  5784. normalize() {
  5785. const length = this.len();
  5786. const l = length > 0 ? 1 / length : 0;
  5787. this[0] = this[0] * l;
  5788. this[1] = this[1] * l;
  5789. this[2] = this[2] * l;
  5790. this[3] = this[3] * l;
  5791. if (length === 0) {
  5792. this[3] = 1;
  5793. }
  5794. return this.check();
  5795. }
  5796. rotateX(rad) {
  5797. rotateX(this, this, rad);
  5798. return this.check();
  5799. }
  5800. rotateY(rad) {
  5801. rotateY(this, this, rad);
  5802. return this.check();
  5803. }
  5804. rotateZ(rad) {
  5805. rotateZ(this, this, rad);
  5806. return this.check();
  5807. }
  5808. scale(b) {
  5809. scale(this, this, b);
  5810. return this.check();
  5811. }
  5812. slerp(start, target, ratio) {
  5813. switch (arguments.length) {
  5814. case 1:
  5815. ({
  5816. start = IDENTITY_QUATERNION,
  5817. target,
  5818. ratio
  5819. } = arguments[0]);
  5820. break;
  5821. case 2:
  5822. [target, ratio] = arguments;
  5823. start = this;
  5824. break;
  5825. }
  5826. slerp(this, start, target, ratio);
  5827. return this.check();
  5828. }
  5829. transformVector4(vector, result = vector) {
  5830. transformQuat(result, vector, this);
  5831. return checkVector(result, 4);
  5832. }
  5833. lengthSq() {
  5834. return this.lengthSquared();
  5835. }
  5836. setFromAxisAngle(axis, rad) {
  5837. return this.setAxisAngle(axis, rad);
  5838. }
  5839. premultiply(a, b) {
  5840. return this.multiplyLeft(a, b);
  5841. }
  5842. multiply(a, b) {
  5843. return this.multiplyRight(a, b);
  5844. }
  5845. }
  5846. var _MathUtils = {
  5847. EPSILON1: 1e-1,
  5848. EPSILON2: 1e-2,
  5849. EPSILON3: 1e-3,
  5850. EPSILON4: 1e-4,
  5851. EPSILON5: 1e-5,
  5852. EPSILON6: 1e-6,
  5853. EPSILON7: 1e-7,
  5854. EPSILON8: 1e-8,
  5855. EPSILON9: 1e-9,
  5856. EPSILON10: 1e-10,
  5857. EPSILON11: 1e-11,
  5858. EPSILON12: 1e-12,
  5859. EPSILON13: 1e-13,
  5860. EPSILON14: 1e-14,
  5861. EPSILON15: 1e-15,
  5862. EPSILON16: 1e-16,
  5863. EPSILON17: 1e-17,
  5864. EPSILON18: 1e-18,
  5865. EPSILON19: 1e-19,
  5866. EPSILON20: 1e-20,
  5867. PI_OVER_TWO: Math.PI / 2,
  5868. PI_OVER_FOUR: Math.PI / 4,
  5869. PI_OVER_SIX: Math.PI / 6,
  5870. TWO_PI: Math.PI * 2
  5871. };
  5872. const WGS84_RADIUS_X$1 = 6378137.0;
  5873. const WGS84_RADIUS_Y$1 = 6378137.0;
  5874. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5875. const noop = x => x;
  5876. const scratchVector$6 = new Vector3();
  5877. function fromCartographic(cartographic, result, map = noop) {
  5878. if (isArray(cartographic)) {
  5879. result[0] = map(cartographic[0]);
  5880. result[1] = map(cartographic[1]);
  5881. result[2] = cartographic[2];
  5882. } else if ('longitude' in cartographic) {
  5883. result[0] = map(cartographic.longitude);
  5884. result[1] = map(cartographic.latitude);
  5885. result[2] = cartographic.height;
  5886. } else {
  5887. result[0] = map(cartographic.x);
  5888. result[1] = map(cartographic.y);
  5889. result[2] = cartographic.z;
  5890. }
  5891. return result;
  5892. }
  5893. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5894. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5895. }
  5896. function toCartographic(vector, cartographic, map = noop) {
  5897. if (isArray(cartographic)) {
  5898. cartographic[0] = map(vector[0]);
  5899. cartographic[1] = map(vector[1]);
  5900. cartographic[2] = vector[2];
  5901. } else if ('longitude' in cartographic) {
  5902. cartographic.longitude = map(vector[0]);
  5903. cartographic.latitude = map(vector[1]);
  5904. cartographic.height = vector[2];
  5905. } else {
  5906. cartographic.x = map(vector[0]);
  5907. cartographic.y = map(vector[1]);
  5908. cartographic.z = vector[2];
  5909. }
  5910. return cartographic;
  5911. }
  5912. function toCartographicFromRadians(vector, cartographic) {
  5913. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5914. }
  5915. const scratchVector$5 = new Vector3();
  5916. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5917. const scaleToGeodeticSurfaceGradient = new Vector3();
  5918. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5919. const {
  5920. oneOverRadii,
  5921. oneOverRadiiSquared,
  5922. centerToleranceSquared
  5923. } = ellipsoid;
  5924. scratchVector$5.from(cartesian);
  5925. const positionX = cartesian.x;
  5926. const positionY = cartesian.y;
  5927. const positionZ = cartesian.z;
  5928. const oneOverRadiiX = oneOverRadii.x;
  5929. const oneOverRadiiY = oneOverRadii.y;
  5930. const oneOverRadiiZ = oneOverRadii.z;
  5931. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5932. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5933. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5934. const squaredNorm = x2 + y2 + z2;
  5935. const ratio = Math.sqrt(1.0 / squaredNorm);
  5936. if (!Number.isFinite(ratio)) {
  5937. return undefined;
  5938. }
  5939. const intersection = scaleToGeodeticSurfaceIntersection;
  5940. intersection.copy(cartesian).scale(ratio);
  5941. if (squaredNorm < centerToleranceSquared) {
  5942. return intersection.to(result);
  5943. }
  5944. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5945. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5946. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5947. const gradient = scaleToGeodeticSurfaceGradient;
  5948. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5949. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5950. let correction = 0.0;
  5951. let xMultiplier;
  5952. let yMultiplier;
  5953. let zMultiplier;
  5954. let func;
  5955. do {
  5956. lambda -= correction;
  5957. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5958. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5959. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5960. const xMultiplier2 = xMultiplier * xMultiplier;
  5961. const yMultiplier2 = yMultiplier * yMultiplier;
  5962. const zMultiplier2 = zMultiplier * zMultiplier;
  5963. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5964. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5965. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5966. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5967. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5968. const derivative = -2.0 * denominator;
  5969. correction = func / derivative;
  5970. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5971. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5972. }
  5973. const EPSILON14 = 1e-14;
  5974. const scratchOrigin = new Vector3();
  5975. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5976. up: {
  5977. south: 'east',
  5978. north: 'west',
  5979. west: 'south',
  5980. east: 'north'
  5981. },
  5982. down: {
  5983. south: 'west',
  5984. north: 'east',
  5985. west: 'north',
  5986. east: 'south'
  5987. },
  5988. south: {
  5989. up: 'west',
  5990. down: 'east',
  5991. west: 'down',
  5992. east: 'up'
  5993. },
  5994. north: {
  5995. up: 'east',
  5996. down: 'west',
  5997. west: 'up',
  5998. east: 'down'
  5999. },
  6000. west: {
  6001. up: 'north',
  6002. down: 'south',
  6003. north: 'down',
  6004. south: 'up'
  6005. },
  6006. east: {
  6007. up: 'south',
  6008. down: 'north',
  6009. north: 'up',
  6010. south: 'down'
  6011. }
  6012. };
  6013. const degeneratePositionLocalFrame = {
  6014. north: [-1, 0, 0],
  6015. east: [0, 1, 0],
  6016. up: [0, 0, 1],
  6017. south: [1, 0, 0],
  6018. west: [0, -1, 0],
  6019. down: [0, 0, -1]
  6020. };
  6021. const scratchAxisVectors = {
  6022. east: new Vector3(),
  6023. north: new Vector3(),
  6024. up: new Vector3(),
  6025. west: new Vector3(),
  6026. south: new Vector3(),
  6027. down: new Vector3()
  6028. };
  6029. const scratchVector1 = new Vector3();
  6030. const scratchVector2$1 = new Vector3();
  6031. const scratchVector3$1 = new Vector3();
  6032. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6033. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6034. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6035. let firstAxisVector;
  6036. let secondAxisVector;
  6037. let thirdAxisVector;
  6038. const origin = scratchOrigin.copy(cartesianOrigin);
  6039. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6040. if (atPole) {
  6041. const sign = Math.sign(origin.z);
  6042. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6043. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6044. firstAxisVector.scale(sign);
  6045. }
  6046. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6047. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6048. secondAxisVector.scale(sign);
  6049. }
  6050. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6051. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6052. thirdAxisVector.scale(sign);
  6053. }
  6054. } else {
  6055. const {
  6056. up,
  6057. east,
  6058. north
  6059. } = scratchAxisVectors;
  6060. east.set(-origin.y, origin.x, 0.0).normalize();
  6061. ellipsoid.geodeticSurfaceNormal(origin, up);
  6062. north.copy(up).cross(east);
  6063. const {
  6064. down,
  6065. west,
  6066. south
  6067. } = scratchAxisVectors;
  6068. down.copy(up).scale(-1);
  6069. west.copy(east).scale(-1);
  6070. south.copy(north).scale(-1);
  6071. firstAxisVector = scratchAxisVectors[firstAxis];
  6072. secondAxisVector = scratchAxisVectors[secondAxis];
  6073. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6074. }
  6075. result[0] = firstAxisVector.x;
  6076. result[1] = firstAxisVector.y;
  6077. result[2] = firstAxisVector.z;
  6078. result[3] = 0.0;
  6079. result[4] = secondAxisVector.x;
  6080. result[5] = secondAxisVector.y;
  6081. result[6] = secondAxisVector.z;
  6082. result[7] = 0.0;
  6083. result[8] = thirdAxisVector.x;
  6084. result[9] = thirdAxisVector.y;
  6085. result[10] = thirdAxisVector.z;
  6086. result[11] = 0.0;
  6087. result[12] = origin.x;
  6088. result[13] = origin.y;
  6089. result[14] = origin.z;
  6090. result[15] = 1.0;
  6091. return result;
  6092. }
  6093. const scratchVector$4 = new Vector3();
  6094. const scratchNormal$2 = new Vector3();
  6095. const scratchK = new Vector3();
  6096. const scratchPosition$2 = new Vector3();
  6097. const scratchHeight = new Vector3();
  6098. const scratchCartesian = new Vector3();
  6099. let wgs84;
  6100. class Ellipsoid {
  6101. static get WGS84() {
  6102. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6103. return wgs84;
  6104. }
  6105. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6106. assert$4(x >= 0.0);
  6107. assert$4(y >= 0.0);
  6108. assert$4(z >= 0.0);
  6109. this.radii = new Vector3(x, y, z);
  6110. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6111. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6112. 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);
  6113. 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));
  6114. this.minimumRadius = Math.min(x, y, z);
  6115. this.maximumRadius = Math.max(x, y, z);
  6116. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6117. if (this.radiiSquared.z !== 0) {
  6118. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6119. }
  6120. Object.freeze(this);
  6121. }
  6122. equals(right) {
  6123. return this === right || Boolean(right && this.radii.equals(right.radii));
  6124. }
  6125. toString() {
  6126. return this.radii.toString();
  6127. }
  6128. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6129. const normal = scratchNormal$2;
  6130. const k = scratchK;
  6131. const [,, height] = cartographic;
  6132. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6133. k.copy(this.radiiSquared).scale(normal);
  6134. const gamma = Math.sqrt(normal.dot(k));
  6135. k.scale(1 / gamma);
  6136. normal.scale(height);
  6137. k.add(normal);
  6138. return k.to(result);
  6139. }
  6140. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6141. scratchCartesian.from(cartesian);
  6142. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6143. if (!point) {
  6144. return undefined;
  6145. }
  6146. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6147. const h = scratchHeight;
  6148. h.copy(scratchCartesian).subtract(point);
  6149. const longitude = Math.atan2(normal.y, normal.x);
  6150. const latitude = Math.asin(normal.z);
  6151. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6152. return toCartographicFromRadians([longitude, latitude, height], result);
  6153. }
  6154. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6155. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6156. }
  6157. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6158. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6159. }
  6160. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6161. return scratchVector$4.from(cartesian).normalize().to(result);
  6162. }
  6163. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6164. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6165. const longitude = cartographicVectorRadians[0];
  6166. const latitude = cartographicVectorRadians[1];
  6167. const cosLatitude = Math.cos(latitude);
  6168. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6169. return scratchVector$4.to(result);
  6170. }
  6171. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6172. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6173. }
  6174. scaleToGeodeticSurface(cartesian, result) {
  6175. return scaleToGeodeticSurface(cartesian, this, result);
  6176. }
  6177. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6178. scratchPosition$2.from(cartesian);
  6179. const positionX = scratchPosition$2.x;
  6180. const positionY = scratchPosition$2.y;
  6181. const positionZ = scratchPosition$2.z;
  6182. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6183. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6184. return scratchPosition$2.multiplyScalar(beta).to(result);
  6185. }
  6186. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6187. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6188. }
  6189. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6190. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6191. }
  6192. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6193. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6194. assert$4(this.radii.z > 0);
  6195. scratchPosition$2.from(position);
  6196. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6197. if (Math.abs(z) >= this.radii.z - buffer) {
  6198. return undefined;
  6199. }
  6200. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6201. }
  6202. }
  6203. class DoublyLinkedListNode {
  6204. constructor(item, previous, next) {
  6205. _defineProperty(this, "item", void 0);
  6206. _defineProperty(this, "previous", void 0);
  6207. _defineProperty(this, "next", void 0);
  6208. this.item = item;
  6209. this.previous = previous;
  6210. this.next = next;
  6211. }
  6212. }
  6213. class DoublyLinkedList {
  6214. constructor() {
  6215. _defineProperty(this, "head", null);
  6216. _defineProperty(this, "tail", null);
  6217. _defineProperty(this, "_length", 0);
  6218. }
  6219. get length() {
  6220. return this._length;
  6221. }
  6222. add(item) {
  6223. const node = new DoublyLinkedListNode(item, this.tail, null);
  6224. if (this.tail) {
  6225. this.tail.next = node;
  6226. this.tail = node;
  6227. } else {
  6228. this.head = node;
  6229. this.tail = node;
  6230. }
  6231. ++this._length;
  6232. return node;
  6233. }
  6234. remove(node) {
  6235. if (!node) {
  6236. return;
  6237. }
  6238. if (node.previous && node.next) {
  6239. node.previous.next = node.next;
  6240. node.next.previous = node.previous;
  6241. } else if (node.previous) {
  6242. node.previous.next = null;
  6243. this.tail = node.previous;
  6244. } else if (node.next) {
  6245. node.next.previous = null;
  6246. this.head = node.next;
  6247. } else {
  6248. this.head = null;
  6249. this.tail = null;
  6250. }
  6251. node.next = null;
  6252. node.previous = null;
  6253. --this._length;
  6254. }
  6255. splice(node, nextNode) {
  6256. if (node === nextNode) {
  6257. return;
  6258. }
  6259. this.remove(nextNode);
  6260. this._insert(node, nextNode);
  6261. }
  6262. _insert(node, nextNode) {
  6263. const oldNodeNext = node.next;
  6264. node.next = nextNode;
  6265. if (this.tail === node) {
  6266. this.tail = nextNode;
  6267. } else {
  6268. oldNodeNext.previous = nextNode;
  6269. }
  6270. nextNode.next = oldNodeNext;
  6271. nextNode.previous = node;
  6272. ++this._length;
  6273. }
  6274. }
  6275. function defined$5(x) {
  6276. return x !== undefined && x !== null;
  6277. }
  6278. class TilesetCache {
  6279. constructor() {
  6280. _defineProperty(this, "_list", void 0);
  6281. _defineProperty(this, "_sentinel", void 0);
  6282. _defineProperty(this, "_trimTiles", void 0);
  6283. this._list = new DoublyLinkedList();
  6284. this._sentinel = this._list.add('sentinel');
  6285. this._trimTiles = false;
  6286. }
  6287. reset() {
  6288. this._list.splice(this._list.tail, this._sentinel);
  6289. }
  6290. touch(tile) {
  6291. const node = tile._cacheNode;
  6292. if (defined$5(node)) {
  6293. this._list.splice(this._sentinel, node);
  6294. }
  6295. }
  6296. add(tileset, tile, addCallback) {
  6297. if (!defined$5(tile._cacheNode)) {
  6298. tile._cacheNode = this._list.add(tile);
  6299. if (addCallback) {
  6300. addCallback(tileset, tile);
  6301. }
  6302. }
  6303. }
  6304. unloadTile(tileset, tile, unloadCallback) {
  6305. const node = tile._cacheNode;
  6306. if (!defined$5(node)) {
  6307. return;
  6308. }
  6309. this._list.remove(node);
  6310. tile._cacheNode = undefined;
  6311. if (unloadCallback) {
  6312. unloadCallback(tileset, tile);
  6313. }
  6314. }
  6315. unloadTiles(tileset, unloadCallback) {
  6316. const trimTiles = this._trimTiles;
  6317. this._trimTiles = false;
  6318. const list = this._list;
  6319. const maximumMemoryUsageInBytes = (Potree.settings.tiles3DMaxMemory || tileset.maximumMemoryUsage) * 1024 * 1024;
  6320. const sentinel = this._sentinel;
  6321. let node = list.head;
  6322. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6323. const tile = node.item;
  6324. node = node.next;
  6325. this.unloadTile(tileset, tile, unloadCallback);
  6326. } */
  6327. //改
  6328. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  6329. const tile = node.item;
  6330. node = node.next;
  6331. this.unloadTile(tileset, tile, unloadCallback);
  6332. }
  6333. }
  6334. trim() {
  6335. this._trimTiles = true;
  6336. }
  6337. }
  6338. function calculateTransformProps(tileHeader, tile) {
  6339. assert$7(tileHeader);
  6340. assert$7(tile);
  6341. const {
  6342. rtcCenter,
  6343. gltfUpAxis
  6344. } = tile;
  6345. const {
  6346. computedTransform,
  6347. boundingVolume: {
  6348. center
  6349. }
  6350. } = tileHeader;
  6351. let modelMatrix = new Matrix4(computedTransform);
  6352. if (rtcCenter) {
  6353. modelMatrix.translate(rtcCenter);
  6354. }
  6355. switch (gltfUpAxis) {
  6356. case 'Z':
  6357. break;
  6358. case 'Y':
  6359. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6360. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6361. break;
  6362. case 'X':
  6363. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6364. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6365. break;
  6366. }
  6367. if (tile.isQuantized) {
  6368. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6369. }
  6370. const cartesianOrigin = new Vector3(center);
  6371. tile.cartesianModelMatrix = modelMatrix;
  6372. tile.cartesianOrigin = cartesianOrigin;
  6373. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6374. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6375. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6376. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6377. tile.cartographicOrigin = cartographicOrigin;
  6378. if (!tile.coordinateSystem) {
  6379. tile.modelMatrix = tile.cartographicModelMatrix;
  6380. }
  6381. }
  6382. const INTERSECTION = Object.freeze({
  6383. OUTSIDE: -1,
  6384. INTERSECTING: 0,
  6385. INSIDE: 1
  6386. });
  6387. new Vector3();
  6388. new Vector3();
  6389. const scratchVector$3 = new Vector3();
  6390. const scratchVector2 = new Vector3();
  6391. class BoundingSphere {
  6392. constructor(center = [0, 0, 0], radius = 0.0) {
  6393. this.radius = -0;
  6394. this.center = new Vector3();
  6395. this.fromCenterRadius(center, radius);
  6396. }
  6397. fromCenterRadius(center, radius) {
  6398. this.center.from(center);
  6399. this.radius = radius;
  6400. return this;
  6401. }
  6402. fromCornerPoints(corner, oppositeCorner) {
  6403. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6404. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6405. this.radius = this.center.distance(oppositeCorner);
  6406. return this;
  6407. }
  6408. equals(right) {
  6409. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6410. }
  6411. clone() {
  6412. return new BoundingSphere(this.center, this.radius);
  6413. }
  6414. union(boundingSphere) {
  6415. const leftCenter = this.center;
  6416. const leftRadius = this.radius;
  6417. const rightCenter = boundingSphere.center;
  6418. const rightRadius = boundingSphere.radius;
  6419. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6420. const centerSeparation = toRightCenter.magnitude();
  6421. if (leftRadius >= centerSeparation + rightRadius) {
  6422. return this.clone();
  6423. }
  6424. if (rightRadius >= centerSeparation + leftRadius) {
  6425. return boundingSphere.clone();
  6426. }
  6427. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6428. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6429. this.center.copy(scratchVector2);
  6430. this.radius = halfDistanceBetweenTangentPoints;
  6431. return this;
  6432. }
  6433. expand(point) {
  6434. point = scratchVector$3.from(point);
  6435. const radius = point.subtract(this.center).magnitude();
  6436. if (radius > this.radius) {
  6437. this.radius = radius;
  6438. }
  6439. return this;
  6440. }
  6441. transform(transform) {
  6442. this.center.transform(transform);
  6443. const scale = getScaling(scratchVector$3, transform);
  6444. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6445. return this;
  6446. }
  6447. distanceSquaredTo(point) {
  6448. const d = this.distanceTo(point);
  6449. return d * d;
  6450. }
  6451. distanceTo(point) {
  6452. point = scratchVector$3.from(point);
  6453. const delta = point.subtract(this.center);
  6454. return Math.max(0, delta.len() - this.radius);
  6455. }
  6456. intersectPlane(plane) {
  6457. const center = this.center;
  6458. const radius = this.radius;
  6459. const normal = plane.normal;
  6460. const distanceToPlane = normal.dot(center) + plane.distance;
  6461. if (distanceToPlane < -radius) {
  6462. return INTERSECTION.OUTSIDE;
  6463. }
  6464. if (distanceToPlane < radius) {
  6465. return INTERSECTION.INTERSECTING;
  6466. }
  6467. return INTERSECTION.INSIDE;
  6468. }
  6469. }
  6470. const scratchVector3 = new Vector3();
  6471. const scratchOffset = new Vector3();
  6472. const scratchVectorU = new Vector3();
  6473. const scratchVectorV = new Vector3();
  6474. const scratchVectorW = new Vector3();
  6475. const scratchCorner = new Vector3();
  6476. const scratchToCenter = new Vector3();
  6477. const MATRIX3 = {
  6478. COLUMN0ROW0: 0,
  6479. COLUMN0ROW1: 1,
  6480. COLUMN0ROW2: 2,
  6481. COLUMN1ROW0: 3,
  6482. COLUMN1ROW1: 4,
  6483. COLUMN1ROW2: 5,
  6484. COLUMN2ROW0: 6,
  6485. COLUMN2ROW1: 7,
  6486. COLUMN2ROW2: 8
  6487. };
  6488. class OrientedBoundingBox {
  6489. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6490. this.center = new Vector3().from(center);
  6491. this.halfAxes = new Matrix3(halfAxes);
  6492. }
  6493. get halfSize() {
  6494. const xAxis = this.halfAxes.getColumn(0);
  6495. const yAxis = this.halfAxes.getColumn(1);
  6496. const zAxis = this.halfAxes.getColumn(2);
  6497. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6498. }
  6499. get quaternion() {
  6500. const xAxis = this.halfAxes.getColumn(0);
  6501. const yAxis = this.halfAxes.getColumn(1);
  6502. const zAxis = this.halfAxes.getColumn(2);
  6503. const normXAxis = new Vector3(xAxis).normalize();
  6504. const normYAxis = new Vector3(yAxis).normalize();
  6505. const normZAxis = new Vector3(zAxis).normalize();
  6506. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6507. }
  6508. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6509. const quaternionObject = new Quaternion(quaternion);
  6510. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6511. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6512. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6513. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6514. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6515. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6516. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6517. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6518. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6519. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6520. this.center = new Vector3().from(center);
  6521. this.halfAxes = directionsMatrix;
  6522. return this;
  6523. }
  6524. clone() {
  6525. return new OrientedBoundingBox(this.center, this.halfAxes);
  6526. }
  6527. equals(right) {
  6528. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6529. }
  6530. getBoundingSphere(result = new BoundingSphere()) {
  6531. const halfAxes = this.halfAxes;
  6532. const u = halfAxes.getColumn(0, scratchVectorU);
  6533. const v = halfAxes.getColumn(1, scratchVectorV);
  6534. const w = halfAxes.getColumn(2, scratchVectorW);
  6535. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6536. result.center.copy(this.center);
  6537. result.radius = cornerVector.magnitude();
  6538. return result;
  6539. }
  6540. intersectPlane(plane) {
  6541. const center = this.center;
  6542. const normal = plane.normal;
  6543. const halfAxes = this.halfAxes;
  6544. const normalX = normal.x;
  6545. const normalY = normal.y;
  6546. const normalZ = normal.z;
  6547. 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]);
  6548. const distanceToPlane = normal.dot(center) + plane.distance;
  6549. if (distanceToPlane <= -radEffective) {
  6550. return INTERSECTION.OUTSIDE;
  6551. } else if (distanceToPlane >= radEffective) {
  6552. return INTERSECTION.INSIDE;
  6553. }
  6554. return INTERSECTION.INTERSECTING; //在相机frustum内
  6555. }
  6556. distanceTo(point) {
  6557. return Math.sqrt(this.distanceSquaredTo(point));
  6558. }
  6559. distanceSquaredTo(point) {
  6560. const offset = scratchOffset.from(point).subtract(this.center);
  6561. const halfAxes = this.halfAxes;
  6562. const u = halfAxes.getColumn(0, scratchVectorU);
  6563. const v = halfAxes.getColumn(1, scratchVectorV);
  6564. const w = halfAxes.getColumn(2, scratchVectorW);
  6565. const uHalf = u.magnitude();
  6566. const vHalf = v.magnitude();
  6567. const wHalf = w.magnitude();
  6568. u.normalize();
  6569. v.normalize();
  6570. w.normalize();
  6571. let distanceSquared = 0.0;
  6572. let d;
  6573. d = Math.abs(offset.dot(u)) - uHalf;
  6574. if (d > 0) {
  6575. distanceSquared += d * d;
  6576. }
  6577. d = Math.abs(offset.dot(v)) - vHalf;
  6578. if (d > 0) {
  6579. distanceSquared += d * d;
  6580. }
  6581. d = Math.abs(offset.dot(w)) - wHalf;
  6582. if (d > 0) {
  6583. distanceSquared += d * d;
  6584. }
  6585. return distanceSquared;
  6586. }
  6587. computePlaneDistances(position, direction, result = [-0, -0]) {
  6588. let minDist = Number.POSITIVE_INFINITY;
  6589. let maxDist = Number.NEGATIVE_INFINITY;
  6590. const center = this.center;
  6591. const halfAxes = this.halfAxes;
  6592. const u = halfAxes.getColumn(0, scratchVectorU);
  6593. const v = halfAxes.getColumn(1, scratchVectorV);
  6594. const w = halfAxes.getColumn(2, scratchVectorW);
  6595. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6596. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6597. let mag = direction.dot(toCenter);
  6598. minDist = Math.min(mag, minDist);
  6599. maxDist = Math.max(mag, maxDist);
  6600. corner.copy(center).add(u).add(v).subtract(w);
  6601. toCenter.copy(corner).subtract(position);
  6602. mag = direction.dot(toCenter);
  6603. minDist = Math.min(mag, minDist);
  6604. maxDist = Math.max(mag, maxDist);
  6605. corner.copy(center).add(u).subtract(v).add(w);
  6606. toCenter.copy(corner).subtract(position);
  6607. mag = direction.dot(toCenter);
  6608. minDist = Math.min(mag, minDist);
  6609. maxDist = Math.max(mag, maxDist);
  6610. corner.copy(center).add(u).subtract(v).subtract(w);
  6611. toCenter.copy(corner).subtract(position);
  6612. mag = direction.dot(toCenter);
  6613. minDist = Math.min(mag, minDist);
  6614. maxDist = Math.max(mag, maxDist);
  6615. center.copy(corner).subtract(u).add(v).add(w);
  6616. toCenter.copy(corner).subtract(position);
  6617. mag = direction.dot(toCenter);
  6618. minDist = Math.min(mag, minDist);
  6619. maxDist = Math.max(mag, maxDist);
  6620. center.copy(corner).subtract(u).add(v).subtract(w);
  6621. toCenter.copy(corner).subtract(position);
  6622. mag = direction.dot(toCenter);
  6623. minDist = Math.min(mag, minDist);
  6624. maxDist = Math.max(mag, maxDist);
  6625. center.copy(corner).subtract(u).subtract(v).add(w);
  6626. toCenter.copy(corner).subtract(position);
  6627. mag = direction.dot(toCenter);
  6628. minDist = Math.min(mag, minDist);
  6629. maxDist = Math.max(mag, maxDist);
  6630. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6631. toCenter.copy(corner).subtract(position);
  6632. mag = direction.dot(toCenter);
  6633. minDist = Math.min(mag, minDist);
  6634. maxDist = Math.max(mag, maxDist);
  6635. result[0] = minDist;
  6636. result[1] = maxDist;
  6637. return result;
  6638. }
  6639. transform(transformation) {
  6640. this.center.transformAsPoint(transformation);
  6641. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6642. xAxis.transformAsPoint(transformation);
  6643. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6644. yAxis.transformAsPoint(transformation);
  6645. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6646. zAxis.transformAsPoint(transformation);
  6647. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6648. return this;
  6649. }
  6650. getTransform() {
  6651. throw new Error('not implemented');
  6652. }
  6653. }
  6654. const scratchPosition$1 = new Vector3();
  6655. const scratchNormal$1 = new Vector3();
  6656. class Plane {
  6657. constructor(normal = [0, 0, 1], distance = 0) {
  6658. this.normal = new Vector3();
  6659. this.distance = -0;
  6660. this.fromNormalDistance(normal, distance);
  6661. }
  6662. fromNormalDistance(normal, distance) {
  6663. assert$4(Number.isFinite(distance));
  6664. this.normal.from(normal).normalize();
  6665. this.distance = distance;
  6666. return this;
  6667. }
  6668. fromPointNormal(point, normal) {
  6669. point = scratchPosition$1.from(point);
  6670. this.normal.from(normal).normalize();
  6671. const distance = -this.normal.dot(point);
  6672. this.distance = distance;
  6673. return this;
  6674. }
  6675. fromCoefficients(a, b, c, d) {
  6676. this.normal.set(a, b, c);
  6677. assert$4(equals(this.normal.len(), 1));
  6678. this.distance = d;
  6679. return this;
  6680. }
  6681. clone(plane) {
  6682. return new Plane(this.normal, this.distance);
  6683. }
  6684. equals(right) {
  6685. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6686. }
  6687. getPointDistance(point) {
  6688. return this.normal.dot(point) + this.distance;
  6689. }
  6690. transform(matrix4) {
  6691. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6692. const point = this.normal.scale(-this.distance).transform(matrix4);
  6693. return this.fromPointNormal(point, normal);
  6694. }
  6695. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6696. point = scratchPosition$1.from(point);
  6697. const pointDistance = this.getPointDistance(point);
  6698. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6699. return point.subtract(scaledNormal).to(result);
  6700. }
  6701. }
  6702. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6703. const scratchPlaneCenter = new Vector3();
  6704. const scratchPlaneNormal$1 = new Vector3();
  6705. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6706. class CullingVolume {
  6707. static get MASK_OUTSIDE() {
  6708. return 0xffffffff;
  6709. }
  6710. static get MASK_INSIDE() {
  6711. return 0x00000000;
  6712. }
  6713. static get MASK_INDETERMINATE() {
  6714. return 0x7fffffff;
  6715. }
  6716. constructor(planes = []) {
  6717. this.planes = planes;
  6718. assert$4(this.planes.every(plane => plane instanceof Plane));
  6719. }
  6720. fromBoundingSphere(boundingSphere) {
  6721. this.planes.length = 2 * faces.length;
  6722. const center = boundingSphere.center;
  6723. const radius = boundingSphere.radius;
  6724. let planeIndex = 0;
  6725. for (const faceNormal of faces) {
  6726. let plane0 = this.planes[planeIndex];
  6727. let plane1 = this.planes[planeIndex + 1];
  6728. if (!plane0) {
  6729. plane0 = this.planes[planeIndex] = new Plane();
  6730. }
  6731. if (!plane1) {
  6732. plane1 = this.planes[planeIndex + 1] = new Plane();
  6733. }
  6734. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6735. -faceNormal.dot(plane0Center);
  6736. plane0.fromPointNormal(plane0Center, faceNormal);
  6737. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6738. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6739. -negatedFaceNormal.dot(plane1Center);
  6740. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6741. planeIndex += 2;
  6742. }
  6743. return this;
  6744. }
  6745. computeVisibility(boundingVolume) {
  6746. assert$4(boundingVolume);
  6747. let intersect = INTERSECTION.INSIDE;
  6748. for (const plane of this.planes) {
  6749. const result = boundingVolume.intersectPlane(plane);
  6750. switch (result) {
  6751. case INTERSECTION.OUTSIDE:
  6752. return INTERSECTION.OUTSIDE;
  6753. case INTERSECTION.INTERSECTING:
  6754. intersect = INTERSECTION.INTERSECTING;
  6755. break;
  6756. }
  6757. }
  6758. return intersect;
  6759. }
  6760. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6761. assert$4(boundingVolume, 'boundingVolume is required.');
  6762. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6763. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6764. return parentPlaneMask;
  6765. }
  6766. let mask = CullingVolume.MASK_INSIDE;
  6767. const planes = this.planes;
  6768. for (let k = 0; k < this.planes.length; ++k) {
  6769. const flag = k < 31 ? 1 << k : 0;
  6770. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6771. continue;
  6772. }
  6773. const plane = planes[k];
  6774. const result = boundingVolume.intersectPlane(plane);
  6775. if (result === INTERSECTION.OUTSIDE) {
  6776. return CullingVolume.MASK_OUTSIDE;
  6777. } else if (result === INTERSECTION.INTERSECTING) {
  6778. mask |= flag;
  6779. }
  6780. }
  6781. return mask;
  6782. }
  6783. }
  6784. const scratchPlaneUpVector = new Vector3();
  6785. const scratchPlaneRightVector = new Vector3();
  6786. const scratchPlaneNearCenter = new Vector3();
  6787. const scratchPlaneFarCenter = new Vector3();
  6788. const scratchPlaneNormal = new Vector3();
  6789. class PerspectiveOffCenterFrustum {
  6790. constructor(options = {}) {
  6791. options = {
  6792. near: 1.0,
  6793. far: 500000000.0,
  6794. ...options
  6795. };
  6796. this.left = options.left;
  6797. this._left = undefined;
  6798. this.right = options.right;
  6799. this._right = undefined;
  6800. this.top = options.top;
  6801. this._top = undefined;
  6802. this.bottom = options.bottom;
  6803. this._bottom = undefined;
  6804. this.near = options.near;
  6805. this._near = this.near;
  6806. this.far = options.far;
  6807. this._far = this.far;
  6808. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6809. this._perspectiveMatrix = new Matrix4();
  6810. this._infinitePerspective = new Matrix4();
  6811. }
  6812. clone() {
  6813. return new PerspectiveOffCenterFrustum({
  6814. right: this.right,
  6815. left: this.left,
  6816. top: this.top,
  6817. bottom: this.bottom,
  6818. near: this.near,
  6819. far: this.far
  6820. });
  6821. }
  6822. equals(other) {
  6823. 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;
  6824. }
  6825. get projectionMatrix() {
  6826. update$1(this);
  6827. return this._perspectiveMatrix;
  6828. }
  6829. get infiniteProjectionMatrix() {
  6830. update$1(this);
  6831. return this._infinitePerspective;
  6832. }
  6833. computeCullingVolume(position, direction, up) {
  6834. assert$4(position, 'position is required.');
  6835. assert$4(direction, 'direction is required.');
  6836. assert$4(up, 'up is required.');
  6837. const planes = this._cullingVolume.planes;
  6838. up = scratchPlaneUpVector.copy(up).normalize();
  6839. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6840. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6841. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6842. let normal = scratchPlaneNormal;
  6843. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6844. planes[0].fromPointNormal(position, normal);
  6845. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6846. planes[1].fromPointNormal(position, normal);
  6847. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6848. planes[2].fromPointNormal(position, normal);
  6849. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6850. planes[3].fromPointNormal(position, normal);
  6851. normal = new Vector3().copy(direction);
  6852. planes[4].fromPointNormal(nearCenter, normal);
  6853. normal.negate();
  6854. planes[5].fromPointNormal(farCenter, normal);
  6855. return this._cullingVolume;
  6856. }
  6857. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6858. update$1(this);
  6859. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6860. assert$4(drawingBufferWidth > 0);
  6861. assert$4(drawingBufferHeight > 0);
  6862. assert$4(distance > 0);
  6863. assert$4(result);
  6864. const inverseNear = 1.0 / this.near;
  6865. let tanTheta = this.top * inverseNear;
  6866. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6867. tanTheta = this.right * inverseNear;
  6868. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6869. result.x = pixelWidth;
  6870. result.y = pixelHeight;
  6871. return result;
  6872. }
  6873. }
  6874. function update$1(frustum) {
  6875. 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));
  6876. const {
  6877. top,
  6878. bottom,
  6879. right,
  6880. left,
  6881. near,
  6882. far
  6883. } = frustum;
  6884. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6885. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6886. frustum._left = left;
  6887. frustum._right = right;
  6888. frustum._top = top;
  6889. frustum._bottom = bottom;
  6890. frustum._near = near;
  6891. frustum._far = far;
  6892. frustum._perspectiveMatrix = new Matrix4().frustum({
  6893. left,
  6894. right,
  6895. bottom,
  6896. top,
  6897. near,
  6898. far
  6899. });
  6900. frustum._infinitePerspective = new Matrix4().frustum({
  6901. left,
  6902. right,
  6903. bottom,
  6904. top,
  6905. near,
  6906. far: Infinity
  6907. });
  6908. }
  6909. }
  6910. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6911. class PerspectiveFrustum {
  6912. constructor(options = {}) {
  6913. options = {
  6914. near: 1.0,
  6915. far: 500000000.0,
  6916. xOffset: 0.0,
  6917. yOffset: 0.0,
  6918. ...options
  6919. };
  6920. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6921. this.fov = options.fov;
  6922. this._fov = undefined;
  6923. this._fovy = undefined;
  6924. this._sseDenominator = undefined;
  6925. this.aspectRatio = options.aspectRatio;
  6926. this._aspectRatio = undefined;
  6927. this.near = options.near;
  6928. this._near = this.near;
  6929. this.far = options.far;
  6930. this._far = this.far;
  6931. this.xOffset = options.xOffset;
  6932. this._xOffset = this.xOffset;
  6933. this.yOffset = options.yOffset;
  6934. this._yOffset = this.yOffset;
  6935. }
  6936. clone() {
  6937. return new PerspectiveFrustum({
  6938. aspectRatio: this.aspectRatio,
  6939. fov: this.fov,
  6940. near: this.near,
  6941. far: this.far
  6942. });
  6943. }
  6944. equals(other) {
  6945. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  6946. return false;
  6947. }
  6948. update(this);
  6949. update(other);
  6950. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  6951. }
  6952. get projectionMatrix() {
  6953. update(this);
  6954. return this._offCenterFrustum.projectionMatrix;
  6955. }
  6956. get infiniteProjectionMatrix() {
  6957. update(this);
  6958. return this._offCenterFrustum.infiniteProjectionMatrix;
  6959. }
  6960. get fovy() {
  6961. update(this);
  6962. return this._fovy;
  6963. }
  6964. get sseDenominator() {
  6965. update(this);
  6966. return this._sseDenominator;
  6967. }
  6968. computeCullingVolume(position, direction, up) {
  6969. update(this);
  6970. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  6971. }
  6972. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6973. update(this);
  6974. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  6975. }
  6976. }
  6977. function update(frustum) {
  6978. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  6979. const f = frustum._offCenterFrustum;
  6980. 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) {
  6981. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  6982. //assert$4(frustum.aspectRatio > 0);
  6983. if(frustum.aspectRatio == 0){
  6984. console.log(1)
  6985. }
  6986. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  6987. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  6988. frustum._fov = frustum.fov;
  6989. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  6990. frustum._near = frustum.near;
  6991. frustum._far = frustum.far;
  6992. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  6993. frustum._xOffset = frustum.xOffset;
  6994. frustum._yOffset = frustum.yOffset;
  6995. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  6996. f.bottom = -f.top;
  6997. f.right = frustum._aspectRatio * f.top;
  6998. f.left = -f.right;
  6999. f.near = frustum.near;
  7000. f.far = frustum.far;
  7001. f.right += frustum.xOffset;
  7002. f.left += frustum.xOffset;
  7003. f.top += frustum.yOffset;
  7004. f.bottom += frustum.yOffset;
  7005. }
  7006. }
  7007. new Vector3();
  7008. new Vector3();
  7009. new Vector3();
  7010. new Vector3();
  7011. new Vector3();
  7012. new Vector3();
  7013. new Vector3();
  7014. new Vector3();
  7015. new Vector3();
  7016. new Vector3();
  7017. new Vector3();
  7018. new Vector3();
  7019. new Matrix3();
  7020. new Matrix3();
  7021. new Matrix3();
  7022. new Matrix3();
  7023. new Matrix3();
  7024. new Vector3();
  7025. new Vector3();
  7026. new Vector3();
  7027. new Vector3();
  7028. new Vector3();
  7029. new Matrix3();
  7030. ({
  7031. diagonal: new Matrix3(),
  7032. unitary: new Matrix3()
  7033. });
  7034. const scratchVector$2 = new Vector3();
  7035. const scratchPosition = new Vector3();
  7036. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7037. function getFrameState(viewport, frameNumber) {
  7038. const {
  7039. cameraDirection,
  7040. cameraUp,
  7041. height
  7042. } = viewport;
  7043. const {
  7044. metersPerUnit
  7045. } = viewport.distanceScales;
  7046. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7047. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7048. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7049. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7050. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7051. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7052. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7053. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7054. return {
  7055. camera: {
  7056. position: cameraPositionCartesian,
  7057. direction: cameraDirectionCartesian,
  7058. up: cameraUpCartesian
  7059. },
  7060. viewport,
  7061. height,
  7062. cullingVolume,
  7063. frameNumber,
  7064. sseDenominator: 1.15
  7065. };
  7066. }
  7067. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7068. const frustumPlanes = viewport.getFrustumPlanes();
  7069. let i = 0;
  7070. for (const dir in frustumPlanes) {
  7071. const plane = frustumPlanes[dir];
  7072. const distanceToCenter = plane.normal.dot(viewport.center);
  7073. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7074. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7075. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7076. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7077. }
  7078. }
  7079. const WGS84_RADIUS_X = 6378137.0;
  7080. const WGS84_RADIUS_Y = 6378137.0;
  7081. const WGS84_RADIUS_Z = 6356752.3142451793;
  7082. const scratchVector$1 = new Vector3();
  7083. function getZoomFromBoundingVolume(boundingVolume) {
  7084. const {
  7085. halfAxes,
  7086. radius,
  7087. width,
  7088. height
  7089. } = boundingVolume;
  7090. if (halfAxes) {
  7091. const obbSize = getObbSize(halfAxes);
  7092. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7093. } else if (radius) {
  7094. return Math.log2(WGS84_RADIUS_Z / radius);
  7095. } else if (height && width) {
  7096. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7097. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7098. return (zoomX + zoomY) / 2;
  7099. }
  7100. return 1;
  7101. }
  7102. function getObbSize(halfAxes) {
  7103. halfAxes.getColumn(0, scratchVector$1);
  7104. const axeY = halfAxes.getColumn(1);
  7105. const axeZ = halfAxes.getColumn(2);
  7106. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7107. const size = farthestVertex.len();
  7108. return size;
  7109. }
  7110. const TILE_CONTENT_STATE = {
  7111. UNLOADED: 0,
  7112. LOADING: 1,
  7113. PROCESSING: 2,
  7114. READY: 3,
  7115. EXPIRED: 4,
  7116. FAILED: 5
  7117. };
  7118. const TILE_REFINEMENT = {
  7119. ADD: 1,
  7120. REPLACE: 2
  7121. };
  7122. const TILE_TYPE = {
  7123. EMPTY: 'empty',
  7124. SCENEGRAPH: 'scenegraph',
  7125. POINTCLOUD: 'pointcloud',
  7126. MESH: 'mesh'
  7127. };
  7128. const TILESET_TYPE = {
  7129. I3S: 'I3S',
  7130. TILES3D: 'TILES3D'
  7131. };
  7132. const LOD_METRIC_TYPE = {
  7133. GEOMETRIC_ERROR: 'geometricError',
  7134. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7135. };
  7136. const TILE3D_OPTIMIZATION_HINT = {
  7137. NOT_COMPUTED: -1,
  7138. USE_OPTIMIZATION: 1,
  7139. SKIP_OPTIMIZATION: 0
  7140. };
  7141. function defined$3(x) {
  7142. return x !== undefined && x !== null;
  7143. }
  7144. const scratchScale = new Vector3();
  7145. const scratchNorthWest = new Vector3();
  7146. const scratchSouthEast = new Vector3();
  7147. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7148. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7149. if (boundingVolumeHeader.box) {
  7150. return createBox(boundingVolumeHeader.box, transform, result);
  7151. }
  7152. if (boundingVolumeHeader.region) {
  7153. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7154. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7155. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7156. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7157. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7158. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7159. }
  7160. if (boundingVolumeHeader.sphere) {
  7161. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7162. }
  7163. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7164. }
  7165. function createBox(box, transform, result) {
  7166. const center = new Vector3(box[0], box[1], box[2]);
  7167. result && (result.oriCenter = center)//add
  7168. transform.transform(center, center);
  7169. let origin = [];
  7170. if (box.length === 10) {
  7171. const halfSize = box.slice(3, 6);
  7172. const quaternion = new Quaternion();
  7173. quaternion.fromArray(box, 6);
  7174. const x = new Vector3([1, 0, 0]);
  7175. const y = new Vector3([0, 1, 0]);
  7176. const z = new Vector3([0, 0, 1]);
  7177. x.transformByQuaternion(quaternion);
  7178. x.scale(halfSize[0]);
  7179. y.transformByQuaternion(quaternion);
  7180. y.scale(halfSize[1]);
  7181. z.transformByQuaternion(quaternion);
  7182. z.scale(halfSize[2]);
  7183. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7184. } else {
  7185. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7186. }
  7187. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7188. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7189. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7190. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7191. if (defined$3(result)) {
  7192. result.center = center;
  7193. result.halfAxes = halfAxes;
  7194. return result;
  7195. }
  7196. return new OrientedBoundingBox(center, halfAxes);
  7197. }
  7198. function createSphere(sphere, transform, result) {
  7199. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7200. transform.transform(center, center);
  7201. const scale = transform.getScale(scratchScale);
  7202. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7203. const radius = sphere[3] * uniformScale;
  7204. if (defined$3(result)) {
  7205. result.center = center;
  7206. result.radius = radius;
  7207. return result;
  7208. }
  7209. return new BoundingSphere(center, radius);
  7210. }
  7211. new Vector3();
  7212. new Vector3();
  7213. new Matrix4();
  7214. new Vector3();
  7215. new Vector3();
  7216. new Vector3();
  7217. function fog(distanceToCamera, density) {
  7218. const scalar = distanceToCamera * density;
  7219. return 1.0 - Math.exp(-(scalar * scalar));
  7220. }
  7221. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7222. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7223. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7224. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7225. const dynamicError = fog(distanceToCamera, density) * factor;
  7226. return dynamicError;
  7227. }
  7228. return 0;
  7229. }
  7230. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7231. const tileset = tile.tileset;
  7232. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7233. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7234. if (lodMetricValue === 0.0) {
  7235. return 0.0;
  7236. }
  7237. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7238. const {
  7239. height,
  7240. sseDenominator
  7241. } = frameState;
  7242. const {
  7243. viewDistanceScale
  7244. } = tileset.options;
  7245. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7246. error -= getDynamicScreenSpaceError(tileset, distance);
  7247. return error;
  7248. }
  7249. function getLodStatus(tile, frameState) {
  7250. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7251. return 'DIG';
  7252. }
  7253. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7254. if (screenSize < 2) {
  7255. return 'OUT';
  7256. }
  7257. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7258. return 'DRAW';
  7259. } else if (tile.header.children) {
  7260. return 'DIG';
  7261. }
  7262. return 'OUT';
  7263. }
  7264. function getProjectedRadius(tile, frameState) {
  7265. const originalViewport = frameState.viewport;
  7266. const ViewportClass = originalViewport.constructor;
  7267. const {
  7268. longitude,
  7269. latitude,
  7270. height,
  7271. width,
  7272. bearing,
  7273. zoom
  7274. } = originalViewport;
  7275. const viewport = new ViewportClass({
  7276. longitude,
  7277. latitude,
  7278. height,
  7279. width,
  7280. bearing,
  7281. zoom,
  7282. pitch: 0
  7283. });
  7284. const mbsLat = tile.header.mbs[1];
  7285. const mbsLon = tile.header.mbs[0];
  7286. const mbsZ = tile.header.mbs[2];
  7287. const mbsR = tile.header.mbs[3];
  7288. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7289. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7290. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7291. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7292. const enuToCartesianMatrix = new Matrix4();
  7293. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7294. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7295. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7296. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7297. const extraZ = projection * projection / cameraPositionEnu[2];
  7298. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7299. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7300. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7301. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7302. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7303. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7304. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7305. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7306. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7307. return projectedRadius;
  7308. }
  7309. function get3dTilesOptions(tileset) {
  7310. return {
  7311. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7312. };
  7313. }
  7314. class ManagedArray {
  7315. constructor(length = 0) {
  7316. _defineProperty(this, "_map", new Map());
  7317. _defineProperty(this, "_array", void 0);
  7318. _defineProperty(this, "_length", void 0);
  7319. this._array = new Array(length);
  7320. this._length = length;
  7321. }
  7322. get length() {
  7323. return this._length;
  7324. }
  7325. set length(length) {
  7326. this._length = length;
  7327. if (length > this._array.length) {
  7328. this._array.length = length;
  7329. }
  7330. }
  7331. get values() {
  7332. return this._array;
  7333. }
  7334. get(index) {
  7335. assert$7(index < this._array.length);
  7336. return this._array[index];
  7337. }
  7338. set(index, element) {
  7339. assert$7(index >= 0);
  7340. if (index >= this.length) {
  7341. this.length = index + 1;
  7342. }
  7343. if (this._map.has(this._array[index])) {
  7344. this._map.delete(this._array[index]);
  7345. }
  7346. this._array[index] = element;
  7347. this._map.set(element, index);
  7348. }
  7349. delete(element) {
  7350. const index = this._map.get(element);
  7351. if (index >= 0) {
  7352. this._array.splice(index, 1);
  7353. this._map.delete(element);
  7354. this.length--;
  7355. }
  7356. }
  7357. peek() {
  7358. return this._array[this._length - 1];
  7359. }
  7360. push(element) {
  7361. if (!this._map.has(element)) {
  7362. const index = this.length++;
  7363. this._array[index] = element;
  7364. this._map.set(element, index);
  7365. }
  7366. }
  7367. pop() {
  7368. const element = this._array[--this.length];
  7369. this._map.delete(element);
  7370. return element;
  7371. }
  7372. reserve(length) {
  7373. assert$7(length >= 0);
  7374. if (length > this._array.length) {
  7375. this._array.length = length;
  7376. }
  7377. }
  7378. resize(length) {
  7379. assert$7(length >= 0);
  7380. this.length = length;
  7381. }
  7382. trim(length) {
  7383. if (length === null || length === undefined) {
  7384. length = this.length;
  7385. }
  7386. this._array.length = length;
  7387. }
  7388. reset() {
  7389. this._array = [];
  7390. this._map = new Map();
  7391. this._length = 0;
  7392. }
  7393. find(target) {
  7394. return this._map.has(target);
  7395. }
  7396. }
  7397. const DEFAULT_PROPS$1 = {
  7398. loadSiblings: false,
  7399. skipLevelOfDetail: false,
  7400. maximumScreenSpaceError: 2,
  7401. updateTransforms: true,
  7402. onTraversalEnd: () => {},
  7403. viewportTraversersMap: {},
  7404. basePath: ''
  7405. };
  7406. class TilesetTraverser {
  7407. constructor(options) {
  7408. _defineProperty(this, "options", void 0);
  7409. _defineProperty(this, "root", void 0);
  7410. _defineProperty(this, "requestedTiles", void 0);
  7411. _defineProperty(this, "selectedTiles", void 0);
  7412. _defineProperty(this, "emptyTiles", void 0);
  7413. _defineProperty(this, "_traversalStack", void 0);
  7414. _defineProperty(this, "_emptyTraversalStack", void 0);
  7415. _defineProperty(this, "_frameNumber", void 0);
  7416. this.options = { ...DEFAULT_PROPS$1,
  7417. ...options
  7418. };
  7419. this._traversalStack = new ManagedArray();
  7420. this._emptyTraversalStack = new ManagedArray();
  7421. this._frameNumber = null;
  7422. this.root = null;
  7423. this.selectedTiles = {};
  7424. this.requestedTiles = {};
  7425. this.emptyTiles = {};
  7426. }
  7427. traverse(root, frameState, options) {
  7428. this.root = root;
  7429. this.options = { ...this.options,
  7430. ...options
  7431. };
  7432. this.reset();
  7433. this.updateTile(root, frameState);
  7434. this._frameNumber = frameState.frameNumber;
  7435. this.executeTraversal(root, frameState);
  7436. }
  7437. reset() {
  7438. this.requestedTiles = {};
  7439. this.selectedTiles = {};
  7440. this.emptyTiles = {};
  7441. this._traversalStack.reset();
  7442. this._emptyTraversalStack.reset();
  7443. }
  7444. executeTraversal(root, frameState) {// 遍历root
  7445. const stack = this._traversalStack;
  7446. root._selectionDepth = 1;
  7447. stack.push(root);
  7448. while (stack.length > 0) {
  7449. const tile = stack.pop();
  7450. let shouldRefine = false;
  7451. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7452. if (this.canTraverse(tile, frameState) && tile.depth < this.options.maxDepth) {//add maxDepth
  7453. this.updateChildTiles(tile, frameState);
  7454. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7455. }
  7456. const parent = tile.parent;
  7457. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7458. const stoppedRefining = !shouldRefine;
  7459. if (!tile.hasRenderContent) {
  7460. this.emptyTiles[tile.id] = tile;
  7461. this.loadTile(tile, frameState);
  7462. if (stoppedRefining) {
  7463. this.selectTile(tile, frameState);
  7464. }
  7465. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7466. this.loadTile(tile, frameState);
  7467. this.selectTile(tile, frameState);
  7468. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7469. this.loadTile(tile, frameState);
  7470. if (stoppedRefining) {
  7471. this.selectTile(tile, frameState);
  7472. }
  7473. }
  7474. this.touchTile(tile, frameState);
  7475. tile._shouldRefine = shouldRefine && parentRefines;
  7476. }
  7477. this.options.onTraversalEnd(frameState);
  7478. }
  7479. updateChildTiles(tile, frameState) {
  7480. const children = tile.children;
  7481. for (const child of children) {
  7482. this.updateTile(child, frameState);
  7483. }
  7484. return true;
  7485. }
  7486. updateAndPushChildren(tile, frameState, stack, depth) {
  7487. const {
  7488. loadSiblings,
  7489. skipLevelOfDetail
  7490. } = this.options;
  7491. const children = tile.children;
  7492. children.sort(this.compareDistanceToCamera.bind(this));
  7493. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7494. let hasVisibleChild = false;
  7495. let refines = true;
  7496. for (const child of children) {
  7497. child._selectionDepth = depth;
  7498. if (child.isVisibleAndInRequestVolume) {
  7499. if (stack.find(child)) {
  7500. stack.delete(child);
  7501. }
  7502. stack.push(child);
  7503. hasVisibleChild = true;
  7504. } else if (checkRefines || loadSiblings) {
  7505. this.loadTile(child, frameState);
  7506. this.touchTile(child, frameState);
  7507. }
  7508. if (checkRefines) {
  7509. let childRefines;
  7510. if (!child._inRequestVolume) {
  7511. childRefines = false;
  7512. } else if (!child.hasRenderContent) {
  7513. childRefines = this.executeEmptyTraversal(child, frameState);
  7514. } else {
  7515. childRefines = child.contentAvailable;
  7516. }
  7517. refines = refines && childRefines;
  7518. if (!refines) {
  7519. return false;
  7520. }
  7521. }
  7522. }
  7523. if (!hasVisibleChild) {
  7524. refines = false;
  7525. }
  7526. return refines;
  7527. }
  7528. updateTile(tile, frameState) {
  7529. this.updateTileVisibility(tile, frameState);
  7530. }
  7531. selectTile(tile, frameState) {
  7532. if (this.shouldSelectTile(tile)) {
  7533. tile._selectedFrame = frameState.frameNumber;
  7534. this.selectedTiles[tile.id] = tile;
  7535. }
  7536. }
  7537. loadTile(tile, frameState) {
  7538. if (this.shouldLoadTile(tile)) {
  7539. tile._requestedFrame = frameState.frameNumber;
  7540. tile._priority = tile._getPriority();
  7541. this.requestedTiles[tile.id] = tile;
  7542. }
  7543. }
  7544. touchTile(tile, frameState) {
  7545. tile.tileset._cache.touch(tile);
  7546. tile._touchedFrame = frameState.frameNumber;
  7547. }
  7548. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7549. if (!tile.hasChildren) {
  7550. return false;
  7551. }
  7552. if (tile.hasTilesetContent) {
  7553. return !tile.contentExpired;
  7554. }
  7555. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7556. return false;
  7557. }
  7558. return this.shouldRefine(tile, frameState, useParentMetric);
  7559. }
  7560. shouldLoadTile(tile) {
  7561. return tile.hasUnloadedContent || tile.contentExpired;
  7562. }
  7563. shouldSelectTile(tile) {
  7564. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7565. }
  7566. shouldRefine(tile, frameState, useParentMetric) {
  7567. let screenSpaceError = tile._screenSpaceError;
  7568. if (useParentMetric) {
  7569. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7570. }
  7571. return screenSpaceError > this.options.maximumScreenSpaceError;
  7572. }
  7573. updateTileVisibility(tile, frameState) {
  7574. const viewportIds = [];
  7575. if (this.options.viewportTraversersMap) {
  7576. for (const key in this.options.viewportTraversersMap) {
  7577. const value = this.options.viewportTraversersMap[key];
  7578. if (value === frameState.viewport.id) {
  7579. viewportIds.push(key);
  7580. }
  7581. }
  7582. } else {
  7583. viewportIds.push(frameState.viewport.id);
  7584. }
  7585. tile.updateVisibility(frameState, viewportIds);
  7586. }
  7587. compareDistanceToCamera(b, a) {
  7588. return b._distanceToCamera - a._distanceToCamera;
  7589. }
  7590. anyChildrenVisible(tile, frameState) {
  7591. let anyVisible = false;
  7592. for (const child of tile.children) {
  7593. child.updateVisibility(frameState);
  7594. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7595. }
  7596. return anyVisible;
  7597. }
  7598. executeEmptyTraversal(root, frameState) {
  7599. let allDescendantsLoaded = true;
  7600. const stack = this._emptyTraversalStack;
  7601. stack.push(root);
  7602. while (stack.length > 0 && allDescendantsLoaded) {
  7603. const tile = stack.pop();
  7604. this.updateTile(tile, frameState);
  7605. if (!tile.isVisibleAndInRequestVolume) {
  7606. this.loadTile(tile, frameState);
  7607. }
  7608. this.touchTile(tile, frameState);
  7609. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7610. if (traverse) {
  7611. const children = tile.children;
  7612. for (const child of children) {
  7613. if (stack.find(child)) {
  7614. stack.delete(child);
  7615. }
  7616. stack.push(child);
  7617. }
  7618. } else if (!tile.contentAvailable) {
  7619. allDescendantsLoaded = false;
  7620. }
  7621. }
  7622. return allDescendantsLoaded;
  7623. }
  7624. }
  7625. const scratchVector = new Vector3();
  7626. function defined$2(x) {
  7627. return x !== undefined && x !== null;
  7628. }
  7629. class TileHeader {
  7630. constructor(tileset, header, parentHeader, extendedId = '') {
  7631. _defineProperty(this, "tileset", void 0);
  7632. _defineProperty(this, "header", void 0);
  7633. _defineProperty(this, "id", void 0);
  7634. _defineProperty(this, "url", void 0);
  7635. _defineProperty(this, "parent", void 0);
  7636. _defineProperty(this, "refine", void 0);
  7637. _defineProperty(this, "type", void 0);
  7638. _defineProperty(this, "contentUrl", void 0);
  7639. _defineProperty(this, "lodMetricType", void 0);
  7640. _defineProperty(this, "lodMetricValue", void 0);
  7641. _defineProperty(this, "boundingVolume", void 0);
  7642. _defineProperty(this, "content", void 0);
  7643. _defineProperty(this, "contentState", void 0);
  7644. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7645. _defineProperty(this, "children", void 0);
  7646. _defineProperty(this, "depth", void 0);
  7647. _defineProperty(this, "viewportIds", void 0);
  7648. _defineProperty(this, "transform", void 0);
  7649. _defineProperty(this, "extensions", void 0);
  7650. _defineProperty(this, "userData", void 0);
  7651. _defineProperty(this, "computedTransform", void 0);
  7652. _defineProperty(this, "hasEmptyContent", void 0);
  7653. _defineProperty(this, "hasTilesetContent", void 0);
  7654. _defineProperty(this, "traverser", void 0);
  7655. _defineProperty(this, "_cacheNode", void 0);
  7656. _defineProperty(this, "_frameNumber", void 0);
  7657. _defineProperty(this, "_lodJudge", void 0);
  7658. _defineProperty(this, "_expireDate", void 0);
  7659. _defineProperty(this, "_expiredContent", void 0);
  7660. _defineProperty(this, "_shouldRefine", void 0);
  7661. _defineProperty(this, "_distanceToCamera", void 0);
  7662. _defineProperty(this, "_centerZDepth", void 0);
  7663. _defineProperty(this, "_screenSpaceError", void 0);
  7664. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7665. _defineProperty(this, "_visible", void 0);
  7666. _defineProperty(this, "_inRequestVolume", void 0);
  7667. _defineProperty(this, "_stackLength", void 0);
  7668. _defineProperty(this, "_selectionDepth", void 0);
  7669. _defineProperty(this, "_touchedFrame", void 0);
  7670. _defineProperty(this, "_visitedFrame", void 0);
  7671. _defineProperty(this, "_selectedFrame", void 0);
  7672. _defineProperty(this, "_requestedFrame", void 0);
  7673. _defineProperty(this, "_priority", void 0);
  7674. _defineProperty(this, "_contentBoundingVolume", void 0);
  7675. _defineProperty(this, "_viewerRequestVolume", void 0);
  7676. _defineProperty(this, "_initialTransform", void 0);
  7677. _defineProperty(this, "tilesetMatrix", void 0);//add
  7678. this.header = header;
  7679. this.tileset = tileset;
  7680. this.id = extendedId || header.id;
  7681. this.url = header.url;
  7682. this.parent = parentHeader;
  7683. this.refine = this._getRefine(header.refine);
  7684. this.type = header.type;
  7685. this.contentUrl = header.contentUrl;
  7686. this.lodMetricType = 'geometricError';
  7687. this.lodMetricValue = 0;
  7688. this.boundingVolume = null;
  7689. this.content = null;
  7690. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7691. this.gpuMemoryUsageInBytes = 0;
  7692. this.children = [];
  7693. this.hasEmptyContent = false;
  7694. this.hasTilesetContent = false;
  7695. this.depth = 0;
  7696. this.viewportIds = [];
  7697. this.userData = {};
  7698. this.extensions = null;
  7699. this._priority = 0;
  7700. this._touchedFrame = 0;
  7701. this._visitedFrame = 0;
  7702. this._selectedFrame = 0;
  7703. this._requestedFrame = 0;
  7704. this._screenSpaceError = 0;
  7705. this._cacheNode = null;
  7706. this._frameNumber = null;
  7707. this._cacheNode = null;
  7708. this.traverser = new TilesetTraverser({});
  7709. this._shouldRefine = false;
  7710. this._distanceToCamera = 0;
  7711. this._centerZDepth = 0;
  7712. this._visible = undefined;
  7713. this._inRequestVolume = false;
  7714. this._stackLength = 0;
  7715. this._selectionDepth = 0;
  7716. this._initialTransform = new Matrix4();
  7717. this.transform = new Matrix4();
  7718. this._initializeLodMetric(header);
  7719. this._initializeTransforms(header);
  7720. this._initializeBoundingVolumes(header);
  7721. this._initializeContent(header);
  7722. this._initializeRenderingState(header);
  7723. this._lodJudge = null;
  7724. this._expireDate = null;
  7725. this._expiredContent = null;
  7726. Object.seal(this);
  7727. }
  7728. destroy() {
  7729. this.header = null;
  7730. }
  7731. isDestroyed() {
  7732. return this.header === null;
  7733. }
  7734. get selected() {
  7735. return this._selectedFrame === this.tileset._frameNumber;
  7736. }
  7737. get isVisible() {
  7738. return this._visible;
  7739. }
  7740. get isVisibleAndInRequestVolume() {
  7741. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  7742. if(window.tileVisi2)v = this._visible && v
  7743. return v
  7744. }
  7745. get hasRenderContent() {
  7746. return !this.hasEmptyContent && !this.hasTilesetContent;
  7747. }
  7748. get hasChildren() {
  7749. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7750. }
  7751. get contentReady() {
  7752. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7753. }
  7754. get contentAvailable() {
  7755. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7756. }
  7757. get hasUnloadedContent() {
  7758. return this.hasRenderContent && this.contentUnloaded;
  7759. }
  7760. get contentUnloaded() {
  7761. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7762. }
  7763. get contentExpired() {
  7764. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7765. }
  7766. get contentFailed() {
  7767. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7768. }
  7769. getScreenSpaceError(frameState, useParentLodMetric) {
  7770. switch (this.tileset.type) {
  7771. case TILESET_TYPE.I3S:
  7772. return getProjectedRadius(this, frameState);
  7773. case TILESET_TYPE.TILES3D:
  7774. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7775. default:
  7776. throw new Error('Unsupported tileset type');
  7777. }
  7778. }
  7779. _getPriority() {
  7780. const traverser = this.tileset._traverser;
  7781. const {
  7782. skipLevelOfDetail
  7783. } = traverser.options;
  7784. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7785. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7786. return -1;
  7787. }
  7788. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7789. return -1;
  7790. }
  7791. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7792. return -1;
  7793. }
  7794. const parent = this.parent;
  7795. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7796. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7797. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7798. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7799. if(!this._visible){
  7800. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  7801. }
  7802. return v
  7803. }
  7804. async loadContent() {
  7805. if (this.hasEmptyContent) {
  7806. return false;
  7807. }
  7808. if (this.content) {
  7809. return true;
  7810. }
  7811. const expired = this.contentExpired;
  7812. if (expired) {
  7813. this._expireDate = null;
  7814. }
  7815. this.contentState = TILE_CONTENT_STATE.LOADING;
  7816. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7817. if (!requestToken) {
  7818. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7819. return false;
  7820. }
  7821. try {
  7822. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  7823. const loader = this.tileset.loader;
  7824. const options = { ...this.tileset.loadOptions,
  7825. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7826. isTileset: this.type === 'json',
  7827. ...this._getLoaderSpecificOptions(loader.id)
  7828. }
  7829. };
  7830. this.content = await load(contentUrl, loader, options);
  7831. // !zeg改
  7832. if (this.tileset.options.maxDepth < this.depth) {
  7833. this.unloadContent()
  7834. return false
  7835. }
  7836. if (this.tileset.options.contentLoader) {
  7837. await this.tileset.options.contentLoader(this);
  7838. }
  7839. if (this._isTileset()) {
  7840. this.tileset._initializeTileHeaders(this.content, this);
  7841. }
  7842. this.contentState = TILE_CONTENT_STATE.READY;
  7843. this._onContentLoaded();
  7844. return true;
  7845. } catch (error) {
  7846. this.contentState = TILE_CONTENT_STATE.FAILED;
  7847. throw error;
  7848. } finally {
  7849. requestToken.done();
  7850. }
  7851. }
  7852. unloadContent() {
  7853. if (this.content && this.content.destroy) {
  7854. this.content.destroy();
  7855. }
  7856. this.content = null;
  7857. if (this.header.content && this.header.content.destroy) {
  7858. this.header.content.destroy();
  7859. }
  7860. this.header.content = null;
  7861. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7862. return true;
  7863. }
  7864. updateVisibility(frameState, viewportIds) {
  7865. if (this._frameNumber === frameState.frameNumber) {
  7866. return;
  7867. }
  7868. const parent = this.parent;
  7869. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7870. if (this.tileset._traverser.options.updateTransforms) {
  7871. const parentTransform = parent ? parent.computedTransform : new Matrix4().elements //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  7872. this._updateTransform(parentTransform);
  7873. }
  7874. this._distanceToCamera = this.distanceToTile(frameState);
  7875. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7876. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7877. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7878. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7879. this._frameNumber = frameState.frameNumber;
  7880. this.viewportIds = viewportIds;
  7881. }
  7882. visibility(frameState, parentVisibilityPlaneMask) {
  7883. const {
  7884. cullingVolume
  7885. } = frameState;
  7886. const {
  7887. boundingVolume
  7888. } = this;
  7889. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7890. }
  7891. contentVisibility() {
  7892. return true;
  7893. }
  7894. distanceToTile(frameState) {
  7895. const boundingVolume = this.boundingVolume;
  7896. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7897. }
  7898. cameraSpaceZDepth({
  7899. camera
  7900. }) {
  7901. const boundingVolume = this.boundingVolume;
  7902. scratchVector.subVectors(boundingVolume.center, camera.position);
  7903. return camera.direction.dot(scratchVector);
  7904. }
  7905. insideViewerRequestVolume(frameState) {
  7906. const viewerRequestVolume = this._viewerRequestVolume;
  7907. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7908. }
  7909. updateExpiration() {
  7910. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7911. const now = Date.now();
  7912. if (Date.lessThan(this._expireDate, now)) {
  7913. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7914. this._expiredContent = this.content;
  7915. }
  7916. }
  7917. }
  7918. get extras() {
  7919. return this.header.extras;
  7920. }
  7921. _initializeLodMetric(header) {
  7922. if ('lodMetricType' in header) {
  7923. this.lodMetricType = header.lodMetricType;
  7924. } else {
  7925. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7926. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7927. }
  7928. if ('lodMetricValue' in header) {
  7929. this.lodMetricValue = header.lodMetricValue;
  7930. } else {
  7931. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  7932. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  7933. }
  7934. }
  7935. _initializeTransforms(tileHeader) {
  7936. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  7937. const parent = this.parent;
  7938. const tileset = this.tileset;
  7939. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4().elements // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  7940. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  7941. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  7942. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  7943. }
  7944. _initializeBoundingVolumes(tileHeader) {
  7945. this._contentBoundingVolume = null;
  7946. this._viewerRequestVolume = null;
  7947. this._updateBoundingVolume(tileHeader);
  7948. }
  7949. _initializeContent(tileHeader) {
  7950. this.content = {
  7951. _tileset: this.tileset,
  7952. _tile: this
  7953. };
  7954. this.hasEmptyContent = true;
  7955. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7956. this.hasTilesetContent = false;
  7957. if (tileHeader.contentUrl) {
  7958. this.content = null;
  7959. this.hasEmptyContent = false;
  7960. }
  7961. }
  7962. _initializeRenderingState(header) {
  7963. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  7964. this._shouldRefine = false;
  7965. this._distanceToCamera = 0;
  7966. this._centerZDepth = 0;
  7967. this._screenSpaceError = 0;
  7968. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  7969. this._visible = undefined;
  7970. this._inRequestVolume = false;
  7971. this._stackLength = 0;
  7972. this._selectionDepth = 0;
  7973. this._frameNumber = 0;
  7974. this._touchedFrame = 0;
  7975. this._visitedFrame = 0;
  7976. this._selectedFrame = 0;
  7977. this._requestedFrame = 0;
  7978. this._priority = 0.0;
  7979. }
  7980. _getRefine(refine) {
  7981. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  7982. }
  7983. _isTileset() {
  7984. return this.contentUrl.indexOf('.json') !== -1;
  7985. }
  7986. _onContentLoaded() {
  7987. switch (this.content && this.content.type) {
  7988. case 'vctr':
  7989. case 'geom':
  7990. this.tileset._traverser.disableSkipLevelOfDetail = true;
  7991. break;
  7992. }
  7993. if (this._isTileset()) {
  7994. this.hasTilesetContent = true;
  7995. }
  7996. }
  7997. _updateBoundingVolume(header) {
  7998. let computedTransform = new Matrix4(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  7999. //console.log('_updateBoundingVolume computedTransform', this.tileset.modelMatrix, computedTransform)
  8000. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  8001. const content = header.content;
  8002. if (!content) {
  8003. return;
  8004. }
  8005. if (content.boundingVolume) {
  8006. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  8007. }
  8008. if (header.viewerRequestVolume) {
  8009. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  8010. }
  8011. }
  8012. _updateTransform(parentTransform = new Matrix4()) {
  8013. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8014. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix) //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  8015. if (!didTransformChange) {
  8016. return;
  8017. }
  8018. this.tileset.modelMatrix
  8019. this.computedTransform = computedTransform;
  8020. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  8021. this._updateBoundingVolume(this.header);
  8022. }
  8023. _getLoaderSpecificOptions(loaderId) {
  8024. switch (loaderId) {
  8025. case 'i3s':
  8026. return { ...this.tileset.options.i3s,
  8027. tile: this.header,
  8028. tileset: this.tileset.tileset,
  8029. isTileHeader: false
  8030. };
  8031. case '3d-tiles':
  8032. case 'cesium-ion':
  8033. default:
  8034. return get3dTilesOptions(this.tileset.tileset);
  8035. }
  8036. }
  8037. }
  8038. class Tileset3DTraverser extends TilesetTraverser {
  8039. compareDistanceToCamera(a, b) {
  8040. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8041. }
  8042. updateTileVisibility(tile, frameState) {
  8043. super.updateTileVisibility(tile, frameState);
  8044. if (!tile.isVisibleAndInRequestVolume) {
  8045. return;
  8046. }
  8047. const hasChildren = tile.children.length > 0;
  8048. if (tile.hasTilesetContent && hasChildren) {
  8049. const firstChild = tile.children[0];
  8050. this.updateTileVisibility(firstChild, frameState);
  8051. tile._visible = firstChild._visible;
  8052. return;
  8053. }
  8054. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8055. tile._visible = false;
  8056. return;
  8057. }
  8058. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8059. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8060. if (replace && useOptimization && hasChildren) {
  8061. if (!this.anyChildrenVisible(tile, frameState)) {
  8062. tile._visible = false;
  8063. return;
  8064. }
  8065. }
  8066. }
  8067. meetsScreenSpaceErrorEarly(tile, frameState) {
  8068. const {
  8069. parent
  8070. } = tile;
  8071. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8072. return false;
  8073. }
  8074. return !this.shouldRefine(tile, frameState, true);
  8075. }
  8076. }
  8077. const STATUS = {
  8078. REQUESTED: 'REQUESTED',
  8079. COMPLETED: 'COMPLETED',
  8080. ERROR: 'ERROR'
  8081. };
  8082. class I3STileManager {
  8083. constructor() {
  8084. _defineProperty(this, "_statusMap", void 0);
  8085. this._statusMap = {};
  8086. }
  8087. add(request, key, callback, frameState) {
  8088. if (!this._statusMap[key]) {
  8089. this._statusMap[key] = {
  8090. request,
  8091. callback,
  8092. key,
  8093. frameState,
  8094. status: STATUS.REQUESTED
  8095. };
  8096. request().then(data => {
  8097. this._statusMap[key].status = STATUS.COMPLETED;
  8098. this._statusMap[key].callback(data, frameState);
  8099. }).catch(error => {
  8100. this._statusMap[key].status = STATUS.ERROR;
  8101. callback(error);
  8102. });
  8103. }
  8104. }
  8105. update(key, frameState) {
  8106. if (this._statusMap[key]) {
  8107. this._statusMap[key].frameState = frameState;
  8108. }
  8109. }
  8110. find(key) {
  8111. return this._statusMap[key];
  8112. }
  8113. }
  8114. class I3STilesetTraverser extends TilesetTraverser {
  8115. constructor(options) {
  8116. super(options);
  8117. _defineProperty(this, "_tileManager", void 0);
  8118. this._tileManager = new I3STileManager();
  8119. }
  8120. shouldRefine(tile, frameState) {
  8121. tile._lodJudge = getLodStatus(tile, frameState);
  8122. return tile._lodJudge === 'DIG';
  8123. }
  8124. updateChildTiles(tile, frameState) {
  8125. const children = tile.header.children || [];
  8126. const childTiles = tile.children;
  8127. const tileset = tile.tileset;
  8128. for (const child of children) {
  8129. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8130. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8131. if (!childTile) {
  8132. let request = () => this._loadTile(child.id, tileset);
  8133. const cachedRequest = this._tileManager.find(extendedId);
  8134. if (!cachedRequest) {
  8135. if (tileset.tileset.nodePages) {
  8136. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8137. }
  8138. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8139. } else {
  8140. this._tileManager.update(extendedId, frameState);
  8141. }
  8142. } else if (childTile) {
  8143. this.updateTile(childTile, frameState);
  8144. }
  8145. }
  8146. return false;
  8147. }
  8148. async _loadTile(nodeId, tileset) {
  8149. const {
  8150. loader
  8151. } = tileset;
  8152. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8153. const options = { ...tileset.loadOptions,
  8154. i3s: { ...tileset.loadOptions.i3s,
  8155. isTileHeader: true,
  8156. loadContent: false
  8157. }
  8158. };
  8159. return await load(nodeUrl, loader, options);
  8160. }
  8161. _onTileLoad(header, tile, extendedId) {
  8162. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8163. tile.children.push(childTile);
  8164. const frameState = this._tileManager.find(childTile.id).frameState;
  8165. this.updateTile(childTile, frameState);
  8166. if (this._frameNumber === frameState.frameNumber) {
  8167. this.executeTraversal(childTile, frameState);
  8168. }
  8169. }
  8170. }
  8171. const DEFAULT_PROPS = {
  8172. description: '',
  8173. ellipsoid: Ellipsoid.WGS84,
  8174. modelMatrix: new Matrix4(),
  8175. throttleRequests: true,
  8176. maxRequests: 64,
  8177. maximumMemoryUsage: 32,
  8178. onTileLoad: () => {},
  8179. onTileUnload: () => {},
  8180. onTileError: () => {},
  8181. onTraversalComplete: selectedTiles => selectedTiles,
  8182. contentLoader: undefined,
  8183. viewDistanceScale: 1.0,
  8184. maximumScreenSpaceError: 8,
  8185. loadTiles: true,
  8186. updateTransforms: true,
  8187. viewportTraversersMap: null,
  8188. loadOptions: {
  8189. fetch: {}
  8190. },
  8191. attributions: [],
  8192. basePath: '',
  8193. i3s: {}
  8194. };
  8195. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8196. const TILES_IN_MEMORY = 'Tiles In Memory';
  8197. const TILES_IN_VIEW = 'Tiles In View';
  8198. const TILES_RENDERABLE = 'Tiles To Render';
  8199. const TILES_LOADED = 'Tiles Loaded';
  8200. const TILES_LOADING = 'Tiles Loading';
  8201. const TILES_UNLOADED = 'Tiles Unloaded';
  8202. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8203. const POINTS_COUNT = 'Points';
  8204. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8205. let tilesetSid = 0//add
  8206. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8207. constructor(json, options) {
  8208. super()
  8209. _defineProperty(this, "options", void 0);
  8210. _defineProperty(this, "loadOptions", void 0);
  8211. _defineProperty(this, "type", void 0);
  8212. _defineProperty(this, "tileset", void 0);
  8213. _defineProperty(this, "loader", void 0);
  8214. _defineProperty(this, "url", void 0);
  8215. _defineProperty(this, "basePath", void 0);
  8216. _defineProperty(this, "modelMatrix", void 0);
  8217. _defineProperty(this, "ellipsoid", void 0);
  8218. _defineProperty(this, "lodMetricType", void 0);
  8219. _defineProperty(this, "lodMetricValue", void 0);
  8220. _defineProperty(this, "refine", void 0);
  8221. _defineProperty(this, "root", void 0);
  8222. _defineProperty(this, "roots", void 0);
  8223. _defineProperty(this, "asset", void 0);
  8224. _defineProperty(this, "description", void 0);
  8225. _defineProperty(this, "properties", void 0);
  8226. _defineProperty(this, "extras", void 0);
  8227. _defineProperty(this, "attributions", void 0);
  8228. _defineProperty(this, "credits", void 0);
  8229. _defineProperty(this, "stats", void 0);
  8230. _defineProperty(this, "traverseCounter", void 0);
  8231. _defineProperty(this, "geometricError", void 0);
  8232. _defineProperty(this, "selectedTiles", void 0);
  8233. _defineProperty(this, "cartographicCenter", void 0);
  8234. _defineProperty(this, "cartesianCenter", void 0);
  8235. _defineProperty(this, "zoom", void 0);
  8236. _defineProperty(this, "boundingVolume", void 0);
  8237. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8238. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8239. _defineProperty(this, "_traverser", void 0);
  8240. _defineProperty(this, "_cache", void 0);
  8241. _defineProperty(this, "_requestScheduler", void 0);
  8242. _defineProperty(this, "_frameNumber", void 0);
  8243. _defineProperty(this, "_queryParamsString", void 0);
  8244. _defineProperty(this, "_queryParams", void 0);
  8245. _defineProperty(this, "_extensionsUsed", void 0);
  8246. _defineProperty(this, "_tiles", void 0);
  8247. _defineProperty(this, "_pendingCount", void 0);
  8248. _defineProperty(this, "lastUpdatedVieports", void 0);
  8249. _defineProperty(this, "_requestedTiles", void 0);
  8250. _defineProperty(this, "_emptyTiles", void 0);
  8251. _defineProperty(this, "frameStateData", void 0);
  8252. _defineProperty(this, "maximumMemoryUsage", void 0);
  8253. _defineProperty(this, "visible", true);//add
  8254. assert$7(json);
  8255. this.options = { ...DEFAULT_PROPS,
  8256. ...options
  8257. };
  8258. this.tileset = json;
  8259. this.loader = json.loader;
  8260. this.type = json.type;
  8261. this.url = json.url;
  8262. this.basePath = json.basePath || dirname(this.url);
  8263. this.modelMatrix = this.options.modelMatrix;
  8264. this.ellipsoid = this.options.ellipsoid;
  8265. this.lodMetricType = json.lodMetricType;
  8266. this.lodMetricValue = json.lodMetricValue;
  8267. this.refine = json.root.refine;
  8268. this.loadOptions = this.options.loadOptions || {};
  8269. this.root = null;
  8270. this.roots = {};
  8271. this.cartographicCenter = null;
  8272. this.cartesianCenter = null;
  8273. this.zoom = 1;
  8274. this.boundingVolume = null;
  8275. this.traverseCounter = 0;
  8276. this.geometricError = 0;
  8277. this._traverser = this._initializeTraverser();
  8278. this._cache = new TilesetCache();
  8279. this._requestScheduler = new RequestScheduler({
  8280. throttleRequests: this.options.throttleRequests,
  8281. maxRequests: this.options.maxRequests
  8282. });
  8283. this._frameNumber = 0;
  8284. this._pendingCount = 0;
  8285. this._tiles = {};
  8286. this.selectedTiles = [];
  8287. this._emptyTiles = [];
  8288. this._requestedTiles = [];
  8289. this.frameStateData = {};
  8290. this.lastUpdatedVieports = null;
  8291. this._queryParams = {};
  8292. this._queryParamsString = '';
  8293. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8294. this.gpuMemoryUsageInBytes = 0;
  8295. this.stats = new Stats({
  8296. id: this.url
  8297. });
  8298. this._initializeStats();
  8299. this._extensionsUsed = undefined;
  8300. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8301. this.extras = null;
  8302. this.asset = {};
  8303. this.credits = {};
  8304. this.description = this.options.description || '';
  8305. this._initializeTileSet(json);
  8306. }
  8307. destroy() {
  8308. this._destroy();
  8309. }
  8310. isLoaded() {
  8311. return this._pendingCount === 0 && this._frameNumber !== 0;
  8312. }
  8313. get tiles() {
  8314. return Object.values(this._tiles);
  8315. }
  8316. get frameNumber() {
  8317. return this._frameNumber;
  8318. }
  8319. get queryParams() {
  8320. if (!this._queryParamsString) {
  8321. this._queryParamsString = getQueryParamString(this._queryParams);
  8322. }
  8323. return this._queryParamsString;
  8324. }
  8325. setProps(props) {
  8326. this.options = { ...this.options,
  8327. ...props
  8328. };
  8329. }
  8330. setOptions(options) {
  8331. this.options = { ...this.options,
  8332. ...options
  8333. };
  8334. }
  8335. getTileUrl(tilePath) {
  8336. const isDataUrl = tilePath.startsWith('data:');
  8337. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8338. if (isDataUrl) {
  8339. return tilePath;
  8340. }
  8341. return "".concat(tilePath).concat(this.queryParams);
  8342. }
  8343. hasExtension(extensionName) {
  8344. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8345. }
  8346. update(viewports) {
  8347. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8348. return;
  8349. }
  8350. if (this.traverseCounter > 0) {
  8351. return;
  8352. }
  8353. if (!viewports && this.lastUpdatedVieports) {
  8354. viewports = this.lastUpdatedVieports;
  8355. } else {
  8356. this.lastUpdatedVieports = viewports;
  8357. }
  8358. if (!(viewports instanceof Array)) {
  8359. viewports = [viewports];
  8360. }
  8361. this._cache.reset();
  8362. this._frameNumber++;
  8363. this.traverseCounter = viewports.length;
  8364. const viewportsToTraverse = [];
  8365. for (const viewport of viewports) {
  8366. const id = viewport.id;
  8367. if (this._needTraverse(id)) {
  8368. viewportsToTraverse.push(id);
  8369. } else {
  8370. this.traverseCounter--;
  8371. }
  8372. }
  8373. for (const viewport of viewports) {
  8374. const id = viewport.id;
  8375. if (!this.roots[id]) {
  8376. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8377. }
  8378. if (!viewportsToTraverse.includes(id)) {
  8379. continue;
  8380. }
  8381. const frameState = getFrameState(viewport, this._frameNumber);
  8382. this._traverser.traverse(this.roots[id], frameState, this.options);
  8383. }
  8384. }
  8385. _needTraverse(viewportId) {
  8386. let traverserId = viewportId;
  8387. if (this.options.viewportTraversersMap) {
  8388. traverserId = this.options.viewportTraversersMap[viewportId];
  8389. }
  8390. if (traverserId !== viewportId) {
  8391. return false;
  8392. }
  8393. return true;
  8394. }
  8395. _onTraversalEnd(frameState) {
  8396. const id = frameState.viewport.id;
  8397. if (!this.frameStateData[id]) {
  8398. this.frameStateData[id] = {
  8399. selectedTiles: [],
  8400. _requestedTiles: [],
  8401. _emptyTiles: []
  8402. };
  8403. }
  8404. const currentFrameStateData = this.frameStateData[id];
  8405. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8406. currentFrameStateData.selectedTiles = selectedTiles;
  8407. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8408. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8409. this.traverseCounter--;
  8410. if (this.traverseCounter > 0) {
  8411. return;
  8412. }
  8413. this._updateTiles();
  8414. }
  8415. _updateTiles() {
  8416. this.selectedTiles = [];
  8417. this._requestedTiles = [];
  8418. this._emptyTiles = [];
  8419. for (const frameStateKey in this.frameStateData) {
  8420. const frameStateDataValue = this.frameStateData[frameStateKey];
  8421. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8422. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8423. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8424. }
  8425. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8426. for (const tile of this.selectedTiles) {
  8427. this._tiles[tile.id] = tile;
  8428. }
  8429. this._loadTiles();
  8430. this._unloadTiles();
  8431. this._updateStats();
  8432. }
  8433. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8434. if (oldSelectedTiles.length !== selectedTiles.length) {
  8435. return true;
  8436. }
  8437. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8438. const set2 = new Set(selectedTiles.map(t => t.id));
  8439. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8440. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8441. return changed;
  8442. }
  8443. _loadTiles() {
  8444. for (const tile of this._requestedTiles) {
  8445. if (tile.contentUnloaded) {
  8446. this._loadTile(tile);
  8447. }
  8448. }
  8449. }
  8450. _unloadTiles() {
  8451. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8452. }
  8453. _updateStats() {
  8454. let tilesRenderable = 0;
  8455. let pointsRenderable = 0;
  8456. for (const tile of this.selectedTiles) {
  8457. if (tile.contentAvailable && tile.content) {
  8458. tilesRenderable++;
  8459. if (tile.content.pointCount) {
  8460. pointsRenderable += tile.content.pointCount;
  8461. }
  8462. }
  8463. }
  8464. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8465. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8466. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8467. }
  8468. _initializeTileSet(tilesetJson) {
  8469. this.root = this._initializeTileHeaders(tilesetJson, null);
  8470. if (this.type === TILESET_TYPE.TILES3D) {
  8471. this._initializeCesiumTileset(tilesetJson);
  8472. }
  8473. if (this.type === TILESET_TYPE.I3S) {
  8474. this._initializeI3STileset();
  8475. }
  8476. this._calculateViewProps();
  8477. }
  8478. _calculateViewProps() {
  8479. const root = this.root;
  8480. assert$7(root);
  8481. const {
  8482. center
  8483. } = root.boundingVolume;
  8484. if (!center) {
  8485. console.warn('center was not pre-calculated for the root tile');
  8486. this.cartographicCenter = new Vector3();
  8487. this.zoom = 1;
  8488. return;
  8489. }
  8490. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8491. this.cartesianCenter = center;
  8492. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8493. }
  8494. _initializeStats() {
  8495. this.stats.get(TILES_TOTAL);
  8496. this.stats.get(TILES_LOADING);
  8497. this.stats.get(TILES_IN_MEMORY);
  8498. this.stats.get(TILES_IN_VIEW);
  8499. this.stats.get(TILES_RENDERABLE);
  8500. this.stats.get(TILES_LOADED);
  8501. this.stats.get(TILES_UNLOADED);
  8502. this.stats.get(TILES_LOAD_FAILED);
  8503. this.stats.get(POINTS_COUNT, 'memory');
  8504. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8505. }
  8506. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8507. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8508. if (parentTileHeader) {
  8509. parentTileHeader.children.push(rootTile);
  8510. rootTile.depth = parentTileHeader.depth + 1;
  8511. }
  8512. if (this.type === TILESET_TYPE.TILES3D) {
  8513. const stack = [];
  8514. stack.push(rootTile);
  8515. while (stack.length > 0) {
  8516. const tile = stack.pop();
  8517. this.stats.get(TILES_TOTAL).incrementCount();
  8518. const children = tile.header.children || [];
  8519. // !zeg改
  8520. if(tile.depth < this.options.maxDepth){
  8521. for (const childHeader of children) {
  8522. const childTile = new TileHeader(this, childHeader, tile);
  8523. tile.children.push(childTile);
  8524. childTile.depth = tile.depth + 1;
  8525. stack.push(childTile);
  8526. }
  8527. }
  8528. window.maxDepth = Math.max(window.maxDepth||0,tile.depth)
  8529. }
  8530. }
  8531. return rootTile;
  8532. }
  8533. _initializeTraverser() {
  8534. let TraverserClass;
  8535. const type = this.type;
  8536. switch (type) {
  8537. case TILESET_TYPE.TILES3D:
  8538. TraverserClass = Tileset3DTraverser;
  8539. break;
  8540. case TILESET_TYPE.I3S:
  8541. TraverserClass = I3STilesetTraverser;
  8542. break;
  8543. default:
  8544. TraverserClass = TilesetTraverser;
  8545. }
  8546. return new TraverserClass({
  8547. basePath: this.basePath,
  8548. onTraversalEnd: this._onTraversalEnd.bind(this)
  8549. });
  8550. }
  8551. _destroyTileHeaders(parentTile) {
  8552. this._destroySubtree(parentTile);
  8553. }
  8554. async _loadTile(tile) {
  8555. let loaded;
  8556. try {
  8557. this._onStartTileLoading();
  8558. loaded = await tile.loadContent();
  8559. } catch (error) {
  8560. this._onTileLoadError(tile, error);
  8561. } finally {
  8562. this._onEndTileLoading(tile);//
  8563. this._onTileLoad(tile, loaded);
  8564. }
  8565. }
  8566. _onTileLoadError(tile, error) {
  8567. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8568. const message = error.message || error.toString();
  8569. const url = tile.url;
  8570. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8571. this.options.onTileError(tile, message, url);
  8572. }
  8573. _onTileLoad(tile, loaded) {
  8574. if (!loaded) {
  8575. return;
  8576. }
  8577. if (tile && tile.content) {
  8578. calculateTransformProps(tile, tile.content);
  8579. }
  8580. this._addTileToCache(tile);
  8581. this.options.onTileLoad(tile);
  8582. }
  8583. _onStartTileLoading() {
  8584. this._pendingCount++;
  8585. this.stats.get(TILES_LOADING).incrementCount();
  8586. }
  8587. _onEndTileLoading(tile) {
  8588. this._pendingCount--;
  8589. this.stats.get(TILES_LOADING).decrementCount();
  8590. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8591. }
  8592. _addTileToCache(tile) {
  8593. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8594. }
  8595. _updateCacheStats(tile) {
  8596. this.stats.get(TILES_LOADED).incrementCount();
  8597. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8598. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8599. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8600. }
  8601. _unloadTile(tile) {
  8602. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8603. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8604. this.stats.get(TILES_UNLOADED).incrementCount();
  8605. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8606. this.options.onTileUnload(tile);
  8607. tile.unloadContent();
  8608. }
  8609. _destroy() {
  8610. const stack = [];
  8611. if (this.root) {
  8612. stack.push(this.root);
  8613. }
  8614. while (stack.length > 0) {
  8615. const tile = stack.pop();
  8616. for (const child of tile.children) {
  8617. stack.push(child);
  8618. }
  8619. this._destroyTile(tile);
  8620. }
  8621. this.root = null;
  8622. }
  8623. _destroySubtree(tile) {
  8624. const root = tile;
  8625. const stack = [];
  8626. stack.push(root);
  8627. while (stack.length > 0) {
  8628. tile = stack.pop();
  8629. for (const child of tile.children) {
  8630. stack.push(child);
  8631. }
  8632. if (tile !== root) {
  8633. this._destroyTile(tile);
  8634. }
  8635. }
  8636. root.children = [];
  8637. }
  8638. _destroyTile(tile) {
  8639. this._cache.unloadTile(this, tile);
  8640. this._unloadTile(tile);
  8641. tile.destroy();
  8642. }
  8643. _initializeCesiumTileset(tilesetJson) {
  8644. this.asset = tilesetJson.asset;
  8645. if (!this.asset) {
  8646. throw new Error('Tileset must have an asset property.');
  8647. }
  8648. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8649. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8650. }
  8651. if ('tilesetVersion' in this.asset) {
  8652. this._queryParams.v = this.asset.tilesetVersion;
  8653. }
  8654. this.credits = {
  8655. attributions: this.options.attributions || []
  8656. };
  8657. this.description = this.options.description || '';
  8658. this.properties = tilesetJson.properties;
  8659. this.geometricError = tilesetJson.geometricError;
  8660. this._extensionsUsed = tilesetJson.extensionsUsed;
  8661. this.extras = tilesetJson.extras;
  8662. }
  8663. _initializeI3STileset() {
  8664. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8665. this._queryParams.token = this.loadOptions.i3s.token;
  8666. }
  8667. }
  8668. }
  8669. function getQueryParamString(queryParams) {
  8670. const queryParamStrings = [];
  8671. for (const key of Object.keys(queryParams)) {
  8672. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8673. }
  8674. switch (queryParamStrings.length) {
  8675. case 0:
  8676. return '';
  8677. case 1:
  8678. return "?".concat(queryParamStrings[0]);
  8679. default:
  8680. return "?".concat(queryParamStrings.join('&'));
  8681. }
  8682. }
  8683. const VERSION$5 = "3.1.4" ;
  8684. const TILE3D_TYPE = {
  8685. COMPOSITE: 'cmpt',
  8686. POINT_CLOUD: 'pnts',
  8687. BATCHED_3D_MODEL: 'b3dm',
  8688. INSTANCED_3D_MODEL: 'i3dm',
  8689. GEOMETRY: 'geom',
  8690. VECTOR: 'vect',
  8691. GLTF: 'glTF'
  8692. };
  8693. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8694. assert$7(arrayBuffer instanceof ArrayBuffer);
  8695. const textDecoder = new TextDecoder('utf8');
  8696. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8697. const string = textDecoder.decode(typedArray);
  8698. return string;
  8699. }
  8700. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8701. const dataView = new DataView(arrayBuffer);
  8702. 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)));
  8703. }
  8704. const VERSION$4 = "3.1.4" ;
  8705. const DEFAULT_DRACO_OPTIONS = {
  8706. draco: {
  8707. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8708. libraryPath: 'libs/',
  8709. extraAttributes: {},
  8710. attributeNameEntry: undefined
  8711. }
  8712. };
  8713. const DracoLoader$1 = {
  8714. name: 'Draco',
  8715. id: 'draco',
  8716. module: 'draco',
  8717. shapes: ['mesh'],
  8718. version: VERSION$4,
  8719. worker: true,
  8720. extensions: ['drc'],
  8721. mimeTypes: ['application/octet-stream'],
  8722. binary: true,
  8723. tests: ['DRACO'],
  8724. options: DEFAULT_DRACO_OPTIONS
  8725. };
  8726. function getMeshBoundingBox(attributes) {
  8727. let minX = Infinity;
  8728. let minY = Infinity;
  8729. let minZ = Infinity;
  8730. let maxX = -Infinity;
  8731. let maxY = -Infinity;
  8732. let maxZ = -Infinity;
  8733. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8734. const len = positions && positions.length;
  8735. for (let i = 0; i < len; i += 3) {
  8736. const x = positions[i];
  8737. const y = positions[i + 1];
  8738. const z = positions[i + 2];
  8739. minX = x < minX ? x : minX;
  8740. minY = y < minY ? y : minY;
  8741. minZ = z < minZ ? z : minZ;
  8742. maxX = x > maxX ? x : maxX;
  8743. maxY = y > maxY ? y : maxY;
  8744. maxZ = z > maxZ ? z : maxZ;
  8745. }
  8746. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8747. }
  8748. function assert$3(condition, message) {
  8749. if (!condition) {
  8750. throw new Error(message || 'loader assertion failed.');
  8751. }
  8752. }
  8753. class Schema {
  8754. constructor(fields, metadata) {
  8755. _defineProperty(this, "fields", void 0);
  8756. _defineProperty(this, "metadata", void 0);
  8757. assert$3(Array.isArray(fields));
  8758. checkNames(fields);
  8759. this.fields = fields;
  8760. this.metadata = metadata || new Map();
  8761. }
  8762. compareTo(other) {
  8763. if (this.metadata !== other.metadata) {
  8764. return false;
  8765. }
  8766. if (this.fields.length !== other.fields.length) {
  8767. return false;
  8768. }
  8769. for (let i = 0; i < this.fields.length; ++i) {
  8770. if (!this.fields[i].compareTo(other.fields[i])) {
  8771. return false;
  8772. }
  8773. }
  8774. return true;
  8775. }
  8776. select(...columnNames) {
  8777. const nameMap = Object.create(null);
  8778. for (const name of columnNames) {
  8779. nameMap[name] = true;
  8780. }
  8781. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8782. return new Schema(selectedFields, this.metadata);
  8783. }
  8784. selectAt(...columnIndices) {
  8785. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8786. return new Schema(selectedFields, this.metadata);
  8787. }
  8788. assign(schemaOrFields) {
  8789. let fields;
  8790. let metadata = this.metadata;
  8791. if (schemaOrFields instanceof Schema) {
  8792. const otherSchema = schemaOrFields;
  8793. fields = otherSchema.fields;
  8794. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8795. } else {
  8796. fields = schemaOrFields;
  8797. }
  8798. const fieldMap = Object.create(null);
  8799. for (const field of this.fields) {
  8800. fieldMap[field.name] = field;
  8801. }
  8802. for (const field of fields) {
  8803. fieldMap[field.name] = field;
  8804. }
  8805. const mergedFields = Object.values(fieldMap);
  8806. return new Schema(mergedFields, metadata);
  8807. }
  8808. }
  8809. function checkNames(fields) {
  8810. const usedNames = {};
  8811. for (const field of fields) {
  8812. if (usedNames[field.name]) {
  8813. console.warn('Schema: duplicated field name', field.name, field);
  8814. }
  8815. usedNames[field.name] = true;
  8816. }
  8817. }
  8818. function mergeMaps(m1, m2) {
  8819. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8820. }
  8821. class Field {
  8822. constructor(name, type, nullable = false, metadata = new Map()) {
  8823. _defineProperty(this, "name", void 0);
  8824. _defineProperty(this, "type", void 0);
  8825. _defineProperty(this, "nullable", void 0);
  8826. _defineProperty(this, "metadata", void 0);
  8827. this.name = name;
  8828. this.type = type;
  8829. this.nullable = nullable;
  8830. this.metadata = metadata;
  8831. }
  8832. get typeId() {
  8833. return this.type && this.type.typeId;
  8834. }
  8835. clone() {
  8836. return new Field(this.name, this.type, this.nullable, this.metadata);
  8837. }
  8838. compareTo(other) {
  8839. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8840. }
  8841. toString() {
  8842. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8843. }
  8844. }
  8845. let Type;
  8846. (function (Type) {
  8847. Type[Type["NONE"] = 0] = "NONE";
  8848. Type[Type["Null"] = 1] = "Null";
  8849. Type[Type["Int"] = 2] = "Int";
  8850. Type[Type["Float"] = 3] = "Float";
  8851. Type[Type["Binary"] = 4] = "Binary";
  8852. Type[Type["Utf8"] = 5] = "Utf8";
  8853. Type[Type["Bool"] = 6] = "Bool";
  8854. Type[Type["Decimal"] = 7] = "Decimal";
  8855. Type[Type["Date"] = 8] = "Date";
  8856. Type[Type["Time"] = 9] = "Time";
  8857. Type[Type["Timestamp"] = 10] = "Timestamp";
  8858. Type[Type["Interval"] = 11] = "Interval";
  8859. Type[Type["List"] = 12] = "List";
  8860. Type[Type["Struct"] = 13] = "Struct";
  8861. Type[Type["Union"] = 14] = "Union";
  8862. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8863. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8864. Type[Type["Map"] = 17] = "Map";
  8865. Type[Type["Dictionary"] = -1] = "Dictionary";
  8866. Type[Type["Int8"] = -2] = "Int8";
  8867. Type[Type["Int16"] = -3] = "Int16";
  8868. Type[Type["Int32"] = -4] = "Int32";
  8869. Type[Type["Int64"] = -5] = "Int64";
  8870. Type[Type["Uint8"] = -6] = "Uint8";
  8871. Type[Type["Uint16"] = -7] = "Uint16";
  8872. Type[Type["Uint32"] = -8] = "Uint32";
  8873. Type[Type["Uint64"] = -9] = "Uint64";
  8874. Type[Type["Float16"] = -10] = "Float16";
  8875. Type[Type["Float32"] = -11] = "Float32";
  8876. Type[Type["Float64"] = -12] = "Float64";
  8877. Type[Type["DateDay"] = -13] = "DateDay";
  8878. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8879. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8880. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8881. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8882. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8883. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8884. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8885. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8886. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8887. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8888. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8889. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  8890. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  8891. })(Type || (Type = {}));
  8892. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  8893. class DataType {
  8894. static isNull(x) {
  8895. return x && x.typeId === Type.Null;
  8896. }
  8897. static isInt(x) {
  8898. return x && x.typeId === Type.Int;
  8899. }
  8900. static isFloat(x) {
  8901. return x && x.typeId === Type.Float;
  8902. }
  8903. static isBinary(x) {
  8904. return x && x.typeId === Type.Binary;
  8905. }
  8906. static isUtf8(x) {
  8907. return x && x.typeId === Type.Utf8;
  8908. }
  8909. static isBool(x) {
  8910. return x && x.typeId === Type.Bool;
  8911. }
  8912. static isDecimal(x) {
  8913. return x && x.typeId === Type.Decimal;
  8914. }
  8915. static isDate(x) {
  8916. return x && x.typeId === Type.Date;
  8917. }
  8918. static isTime(x) {
  8919. return x && x.typeId === Type.Time;
  8920. }
  8921. static isTimestamp(x) {
  8922. return x && x.typeId === Type.Timestamp;
  8923. }
  8924. static isInterval(x) {
  8925. return x && x.typeId === Type.Interval;
  8926. }
  8927. static isList(x) {
  8928. return x && x.typeId === Type.List;
  8929. }
  8930. static isStruct(x) {
  8931. return x && x.typeId === Type.Struct;
  8932. }
  8933. static isUnion(x) {
  8934. return x && x.typeId === Type.Union;
  8935. }
  8936. static isFixedSizeBinary(x) {
  8937. return x && x.typeId === Type.FixedSizeBinary;
  8938. }
  8939. static isFixedSizeList(x) {
  8940. return x && x.typeId === Type.FixedSizeList;
  8941. }
  8942. static isMap(x) {
  8943. return x && x.typeId === Type.Map;
  8944. }
  8945. static isDictionary(x) {
  8946. return x && x.typeId === Type.Dictionary;
  8947. }
  8948. get typeId() {
  8949. return Type.NONE;
  8950. }
  8951. compareTo(other) {
  8952. return this === other;
  8953. }
  8954. }
  8955. _Symbol$toStringTag = Symbol.toStringTag;
  8956. class Int extends DataType {
  8957. constructor(isSigned, bitWidth) {
  8958. super();
  8959. _defineProperty(this, "isSigned", void 0);
  8960. _defineProperty(this, "bitWidth", void 0);
  8961. this.isSigned = isSigned;
  8962. this.bitWidth = bitWidth;
  8963. }
  8964. get typeId() {
  8965. return Type.Int;
  8966. }
  8967. get [_Symbol$toStringTag]() {
  8968. return 'Int';
  8969. }
  8970. toString() {
  8971. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  8972. }
  8973. }
  8974. class Int8 extends Int {
  8975. constructor() {
  8976. super(true, 8);
  8977. }
  8978. }
  8979. class Int16 extends Int {
  8980. constructor() {
  8981. super(true, 16);
  8982. }
  8983. }
  8984. class Int32 extends Int {
  8985. constructor() {
  8986. super(true, 32);
  8987. }
  8988. }
  8989. class Uint8 extends Int {
  8990. constructor() {
  8991. super(false, 8);
  8992. }
  8993. }
  8994. class Uint16 extends Int {
  8995. constructor() {
  8996. super(false, 16);
  8997. }
  8998. }
  8999. class Uint32 extends Int {
  9000. constructor() {
  9001. super(false, 32);
  9002. }
  9003. }
  9004. const Precision = {
  9005. HALF: 16,
  9006. SINGLE: 32,
  9007. DOUBLE: 64
  9008. };
  9009. _Symbol$toStringTag2 = Symbol.toStringTag;
  9010. class Float extends DataType {
  9011. constructor(precision) {
  9012. super();
  9013. _defineProperty(this, "precision", void 0);
  9014. this.precision = precision;
  9015. }
  9016. get typeId() {
  9017. return Type.Float;
  9018. }
  9019. get [_Symbol$toStringTag2]() {
  9020. return 'Float';
  9021. }
  9022. toString() {
  9023. return "Float".concat(this.precision);
  9024. }
  9025. }
  9026. class Float32 extends Float {
  9027. constructor() {
  9028. super(Precision.SINGLE);
  9029. }
  9030. }
  9031. class Float64 extends Float {
  9032. constructor() {
  9033. super(Precision.DOUBLE);
  9034. }
  9035. }
  9036. _Symbol$toStringTag7 = Symbol.toStringTag;
  9037. class FixedSizeList extends DataType {
  9038. constructor(listSize, child) {
  9039. super();
  9040. _defineProperty(this, "listSize", void 0);
  9041. _defineProperty(this, "children", void 0);
  9042. this.listSize = listSize;
  9043. this.children = [child];
  9044. }
  9045. get typeId() {
  9046. return Type.FixedSizeList;
  9047. }
  9048. get valueType() {
  9049. return this.children[0].type;
  9050. }
  9051. get valueField() {
  9052. return this.children[0];
  9053. }
  9054. get [_Symbol$toStringTag7]() {
  9055. return 'FixedSizeList';
  9056. }
  9057. toString() {
  9058. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9059. }
  9060. }
  9061. function getArrowTypeFromTypedArray(array) {
  9062. switch (array.constructor) {
  9063. case Int8Array:
  9064. return new Int8();
  9065. case Uint8Array:
  9066. return new Uint8();
  9067. case Int16Array:
  9068. return new Int16();
  9069. case Uint16Array:
  9070. return new Uint16();
  9071. case Int32Array:
  9072. return new Int32();
  9073. case Uint32Array:
  9074. return new Uint32();
  9075. case Float32Array:
  9076. return new Float32();
  9077. case Float64Array:
  9078. return new Float64();
  9079. default:
  9080. throw new Error('array type not supported');
  9081. }
  9082. }
  9083. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9084. const type = getArrowTypeFromTypedArray(attribute.value);
  9085. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9086. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9087. return field;
  9088. }
  9089. function makeMeshAttributeMetadata(attribute) {
  9090. const result = new Map();
  9091. if ('byteOffset' in attribute) {
  9092. result.set('byteOffset', attribute.byteOffset.toString(10));
  9093. }
  9094. if ('byteStride' in attribute) {
  9095. result.set('byteStride', attribute.byteStride.toString(10));
  9096. }
  9097. if ('normalized' in attribute) {
  9098. result.set('normalized', attribute.normalized.toString());
  9099. }
  9100. return result;
  9101. }
  9102. function getDracoSchema(attributes, loaderData, indices) {
  9103. const metadataMap = makeMetadata(loaderData.metadata);
  9104. const fields = [];
  9105. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9106. for (const attributeName in attributes) {
  9107. const attribute = attributes[attributeName];
  9108. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9109. fields.push(field);
  9110. }
  9111. if (indices) {
  9112. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9113. fields.push(indicesField);
  9114. }
  9115. return new Schema(fields, metadataMap);
  9116. }
  9117. function transformAttributesLoaderData(loaderData) {
  9118. const result = {};
  9119. for (const key in loaderData) {
  9120. const dracoAttribute = loaderData[key];
  9121. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9122. }
  9123. return result;
  9124. }
  9125. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9126. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9127. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9128. return field;
  9129. }
  9130. function makeMetadata(metadata) {
  9131. const metadataMap = new Map();
  9132. for (const key in metadata) {
  9133. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9134. }
  9135. return metadataMap;
  9136. }
  9137. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9138. POSITION: 'POSITION',
  9139. NORMAL: 'NORMAL',
  9140. COLOR: 'COLOR_0',
  9141. TEX_COORD: 'TEXCOORD_0'
  9142. };
  9143. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9144. 1: Int8Array,
  9145. 2: Uint8Array,
  9146. 3: Int16Array,
  9147. 4: Uint16Array,
  9148. 5: Int32Array,
  9149. 6: Uint32Array,
  9150. 9: Float32Array
  9151. };
  9152. const INDEX_ITEM_SIZE = 4;
  9153. class DracoParser {
  9154. constructor(draco) {
  9155. _defineProperty(this, "draco", void 0);
  9156. _defineProperty(this, "decoder", void 0);
  9157. _defineProperty(this, "metadataQuerier", void 0);
  9158. this.draco = draco;
  9159. this.decoder = new this.draco.Decoder();
  9160. this.metadataQuerier = new this.draco.MetadataQuerier();
  9161. }
  9162. destroy() {
  9163. this.draco.destroy(this.decoder);
  9164. this.draco.destroy(this.metadataQuerier);
  9165. }
  9166. parseSync(arrayBuffer, options = {}) {
  9167. const buffer = new this.draco.DecoderBuffer();
  9168. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9169. this._disableAttributeTransforms(options);
  9170. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9171. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9172. try {
  9173. let dracoStatus;
  9174. switch (geometry_type) {
  9175. case this.draco.TRIANGULAR_MESH:
  9176. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9177. break;
  9178. case this.draco.POINT_CLOUD:
  9179. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9180. break;
  9181. default:
  9182. throw new Error('DRACO: Unknown geometry type.');
  9183. }
  9184. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9185. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9186. throw new Error(message);
  9187. }
  9188. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9189. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9190. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9191. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9192. const data = {
  9193. loader: 'draco',
  9194. loaderData,
  9195. header: {
  9196. vertexCount: dracoGeometry.num_points(),
  9197. boundingBox
  9198. },
  9199. ...geometry,
  9200. schema
  9201. };
  9202. return data;
  9203. } finally {
  9204. this.draco.destroy(buffer);
  9205. if (dracoGeometry) {
  9206. this.draco.destroy(dracoGeometry);
  9207. }
  9208. }
  9209. }
  9210. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9211. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9212. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9213. return {
  9214. geometry_type,
  9215. num_attributes: dracoGeometry.num_attributes(),
  9216. num_points: dracoGeometry.num_points(),
  9217. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9218. metadata,
  9219. attributes
  9220. };
  9221. }
  9222. _getDracoAttributes(dracoGeometry, options) {
  9223. const dracoAttributes = {};
  9224. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9225. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9226. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9227. dracoAttributes[dracoAttribute.unique_id()] = {
  9228. unique_id: dracoAttribute.unique_id(),
  9229. attribute_type: dracoAttribute.attribute_type(),
  9230. data_type: dracoAttribute.data_type(),
  9231. num_components: dracoAttribute.num_components(),
  9232. byte_offset: dracoAttribute.byte_offset(),
  9233. byte_stride: dracoAttribute.byte_stride(),
  9234. normalized: dracoAttribute.normalized(),
  9235. attribute_index: attributeId,
  9236. metadata
  9237. };
  9238. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9239. if (quantization) {
  9240. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9241. }
  9242. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9243. if (octahedron) {
  9244. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9245. }
  9246. }
  9247. return dracoAttributes;
  9248. }
  9249. _getMeshData(dracoGeometry, loaderData, options) {
  9250. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9251. const positionAttribute = attributes.POSITION;
  9252. if (!positionAttribute) {
  9253. throw new Error('DRACO: No position attribute found.');
  9254. }
  9255. if (dracoGeometry instanceof this.draco.Mesh) {
  9256. switch (options.topology) {
  9257. case 'triangle-strip':
  9258. return {
  9259. topology: 'triangle-strip',
  9260. mode: 4,
  9261. attributes,
  9262. indices: {
  9263. value: this._getTriangleStripIndices(dracoGeometry),
  9264. size: 1
  9265. }
  9266. };
  9267. case 'triangle-list':
  9268. default:
  9269. return {
  9270. topology: 'triangle-list',
  9271. mode: 5,
  9272. attributes,
  9273. indices: {
  9274. value: this._getTriangleListIndices(dracoGeometry),
  9275. size: 1
  9276. }
  9277. };
  9278. }
  9279. }
  9280. return {
  9281. topology: 'point-list',
  9282. mode: 0,
  9283. attributes
  9284. };
  9285. }
  9286. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9287. const attributes = {};
  9288. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9289. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9290. loaderAttribute.name = attributeName;
  9291. const {
  9292. value,
  9293. size
  9294. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9295. attributes[attributeName] = {
  9296. value,
  9297. size,
  9298. byteOffset: loaderAttribute.byte_offset,
  9299. byteStride: loaderAttribute.byte_stride,
  9300. normalized: loaderAttribute.normalized
  9301. };
  9302. }
  9303. return attributes;
  9304. }
  9305. _getTriangleListIndices(dracoGeometry) {
  9306. const numFaces = dracoGeometry.num_faces();
  9307. const numIndices = numFaces * 3;
  9308. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9309. const ptr = this.draco._malloc(byteLength);
  9310. try {
  9311. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9312. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9313. } finally {
  9314. this.draco._free(ptr);
  9315. }
  9316. }
  9317. _getTriangleStripIndices(dracoGeometry) {
  9318. const dracoArray = new this.draco.DracoInt32Array();
  9319. try {
  9320. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9321. return getUint32Array(dracoArray);
  9322. } finally {
  9323. this.draco.destroy(dracoArray);
  9324. }
  9325. }
  9326. _getAttributeValues(dracoGeometry, attribute) {
  9327. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9328. const numComponents = attribute.num_components;
  9329. const numPoints = dracoGeometry.num_points();
  9330. const numValues = numPoints * numComponents;
  9331. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9332. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9333. let value;
  9334. const ptr = this.draco._malloc(byteLength);
  9335. try {
  9336. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9337. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9338. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9339. } finally {
  9340. this.draco._free(ptr);
  9341. }
  9342. return {
  9343. value,
  9344. size: numComponents
  9345. };
  9346. }
  9347. _deduceAttributeName(attribute, options) {
  9348. const uniqueId = attribute.unique_id;
  9349. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9350. if (attributeUniqueId === uniqueId) {
  9351. return attributeName;
  9352. }
  9353. }
  9354. const thisAttributeType = attribute.attribute_type;
  9355. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9356. const attributeType = this.draco[dracoAttributeConstant];
  9357. if (attributeType === thisAttributeType) {
  9358. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9359. }
  9360. }
  9361. const entryName = options.attributeNameEntry || 'name';
  9362. if (attribute.metadata[entryName]) {
  9363. return attribute.metadata[entryName].string;
  9364. }
  9365. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9366. }
  9367. _getTopLevelMetadata(dracoGeometry) {
  9368. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9369. return this._getDracoMetadata(dracoMetadata);
  9370. }
  9371. _getAttributeMetadata(dracoGeometry, attributeId) {
  9372. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9373. return this._getDracoMetadata(dracoMetadata);
  9374. }
  9375. _getDracoMetadata(dracoMetadata) {
  9376. if (!dracoMetadata || !dracoMetadata.ptr) {
  9377. return {};
  9378. }
  9379. const result = {};
  9380. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9381. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9382. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9383. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9384. }
  9385. return result;
  9386. }
  9387. _getDracoMetadataField(dracoMetadata, entryName) {
  9388. const dracoArray = new this.draco.DracoInt32Array();
  9389. try {
  9390. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9391. const intArray = getInt32Array(dracoArray);
  9392. return {
  9393. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9394. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9395. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9396. intArray
  9397. };
  9398. } finally {
  9399. this.draco.destroy(dracoArray);
  9400. }
  9401. }
  9402. _disableAttributeTransforms(options) {
  9403. const {
  9404. quantizedAttributes = [],
  9405. octahedronAttributes = []
  9406. } = options;
  9407. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9408. for (const dracoAttributeName of skipAttributes) {
  9409. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9410. }
  9411. }
  9412. _getQuantizationTransform(dracoAttribute, options) {
  9413. const {
  9414. quantizedAttributes = []
  9415. } = options;
  9416. const attribute_type = dracoAttribute.attribute_type();
  9417. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9418. if (skip) {
  9419. const transform = new this.draco.AttributeQuantizationTransform();
  9420. try {
  9421. if (transform.InitFromAttribute(dracoAttribute)) {
  9422. return {
  9423. quantization_bits: transform.quantization_bits(),
  9424. range: transform.range(),
  9425. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9426. };
  9427. }
  9428. } finally {
  9429. this.draco.destroy(transform);
  9430. }
  9431. }
  9432. return null;
  9433. }
  9434. _getOctahedronTransform(dracoAttribute, options) {
  9435. const {
  9436. octahedronAttributes = []
  9437. } = options;
  9438. const attribute_type = dracoAttribute.attribute_type();
  9439. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9440. if (octahedron) {
  9441. const transform = new this.draco.AttributeQuantizationTransform();
  9442. try {
  9443. if (transform.InitFromAttribute(dracoAttribute)) {
  9444. return {
  9445. quantization_bits: transform.quantization_bits()
  9446. };
  9447. }
  9448. } finally {
  9449. this.draco.destroy(transform);
  9450. }
  9451. }
  9452. return null;
  9453. }
  9454. }
  9455. function getDracoDataType(draco, attributeType) {
  9456. switch (attributeType) {
  9457. case Float32Array:
  9458. return draco.DT_FLOAT32;
  9459. case Int8Array:
  9460. return draco.DT_INT8;
  9461. case Int16Array:
  9462. return draco.DT_INT16;
  9463. case Int32Array:
  9464. return draco.DT_INT32;
  9465. case Uint8Array:
  9466. return draco.DT_UINT8;
  9467. case Uint16Array:
  9468. return draco.DT_UINT16;
  9469. case Uint32Array:
  9470. return draco.DT_UINT32;
  9471. default:
  9472. return draco.DT_INVALID;
  9473. }
  9474. }
  9475. function getInt32Array(dracoArray) {
  9476. const numValues = dracoArray.size();
  9477. const intArray = new Int32Array(numValues);
  9478. for (let i = 0; i < numValues; i++) {
  9479. intArray[i] = dracoArray.GetValue(i);
  9480. }
  9481. return intArray;
  9482. }
  9483. function getUint32Array(dracoArray) {
  9484. const numValues = dracoArray.size();
  9485. const intArray = new Int32Array(numValues);
  9486. for (let i = 0; i < numValues; i++) {
  9487. intArray[i] = dracoArray.GetValue(i);
  9488. }
  9489. return intArray;
  9490. }
  9491. const DRACO_VERSION = '1.4.1';
  9492. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9493. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9494. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9495. let loadDecoderPromise;
  9496. async function loadDracoDecoderModule(options) {
  9497. const modules = options.modules || {};
  9498. if (modules.draco3d) {
  9499. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9500. return {
  9501. draco
  9502. };
  9503. });
  9504. } else {
  9505. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9506. }
  9507. return await loadDecoderPromise;
  9508. }
  9509. async function loadDracoDecoder(options) {
  9510. let DracoDecoderModule;
  9511. let wasmBinary;
  9512. switch (options.draco && options.draco.decoderType) {
  9513. case 'js':
  9514. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9515. break;
  9516. case 'wasm':
  9517. default:
  9518. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9519. }
  9520. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9521. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9522. }
  9523. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9524. const options = {};
  9525. if (wasmBinary) {
  9526. options.wasmBinary = wasmBinary;
  9527. }
  9528. return new Promise(resolve => {
  9529. DracoDecoderModule({ ...options,
  9530. onModuleLoaded: draco => resolve({
  9531. draco
  9532. })
  9533. });
  9534. });
  9535. }
  9536. const DracoLoader = { ...DracoLoader$1,
  9537. parse: parse$2
  9538. };
  9539. async function parse$2(arrayBuffer, options) {
  9540. const {
  9541. draco
  9542. } = await loadDracoDecoderModule(options);
  9543. const dracoParser = new DracoParser(draco);
  9544. try {
  9545. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9546. } finally {
  9547. dracoParser.destroy();
  9548. }
  9549. }
  9550. const GL_PRIMITIVE_MODE = {
  9551. POINTS: 0x0000,
  9552. LINES: 0x0001,
  9553. LINE_LOOP: 0x0002,
  9554. LINE_STRIP: 0x0003,
  9555. TRIANGLES: 0x0004,
  9556. TRIANGLE_STRIP: 0x0005,
  9557. TRIANGLE_FAN: 0x0006
  9558. };
  9559. const GL_TYPE = {
  9560. BYTE: 5120,
  9561. UNSIGNED_BYTE: 5121,
  9562. SHORT: 5122,
  9563. UNSIGNED_SHORT: 5123,
  9564. INT: 5124,
  9565. UNSIGNED_INT: 5125,
  9566. FLOAT: 5126,
  9567. DOUBLE: 5130
  9568. };
  9569. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9570. ...GL_TYPE
  9571. };
  9572. const GL_TYPE_TO_ARRAY_TYPE = {
  9573. [GL_TYPE.DOUBLE]: Float64Array,
  9574. [GL_TYPE.FLOAT]: Float32Array,
  9575. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9576. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9577. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9578. [GL_TYPE.BYTE]: Int8Array,
  9579. [GL_TYPE.SHORT]: Int16Array,
  9580. [GL_TYPE.INT]: Int32Array
  9581. };
  9582. const NAME_TO_GL_TYPE = {
  9583. DOUBLE: GL_TYPE.DOUBLE,
  9584. FLOAT: GL_TYPE.FLOAT,
  9585. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9586. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9587. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9588. BYTE: GL_TYPE.BYTE,
  9589. SHORT: GL_TYPE.SHORT,
  9590. INT: GL_TYPE.INT
  9591. };
  9592. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9593. class GLType {
  9594. static fromTypedArray(arrayOrType) {
  9595. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9596. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9597. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9598. if (ArrayType === arrayOrType) {
  9599. return glType;
  9600. }
  9601. }
  9602. throw new Error(ERR_TYPE_CONVERSION);
  9603. }
  9604. static fromName(name) {
  9605. const glType = NAME_TO_GL_TYPE[name];
  9606. if (!glType) {
  9607. throw new Error(ERR_TYPE_CONVERSION);
  9608. }
  9609. return glType;
  9610. }
  9611. static getArrayType(glType) {
  9612. switch (glType) {
  9613. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9614. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9615. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9616. return Uint16Array;
  9617. default:
  9618. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9619. if (!ArrayType) {
  9620. throw new Error(ERR_TYPE_CONVERSION);
  9621. }
  9622. return ArrayType;
  9623. }
  9624. }
  9625. static getByteSize(glType) {
  9626. const ArrayType = GLType.getArrayType(glType);
  9627. return ArrayType.BYTES_PER_ELEMENT;
  9628. }
  9629. static validate(glType) {
  9630. return Boolean(GLType.getArrayType(glType));
  9631. }
  9632. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9633. if (length === undefined) {
  9634. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9635. }
  9636. const ArrayType = GLType.getArrayType(glType);
  9637. return new ArrayType(buffer, byteOffset, length);
  9638. }
  9639. }
  9640. function assert$2(condition, message) {
  9641. if (!condition) {
  9642. throw new Error("math.gl assertion failed. ".concat(message));
  9643. }
  9644. }
  9645. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9646. const r5 = rgb565 >> 11 & 31;
  9647. const g6 = rgb565 >> 5 & 63;
  9648. const b5 = rgb565 & 31;
  9649. target[0] = r5 << 3;
  9650. target[1] = g6 << 2;
  9651. target[2] = b5 << 3;
  9652. return target;
  9653. }
  9654. new Vector2();
  9655. new Vector3();
  9656. new Vector2();
  9657. new Vector2();
  9658. function fromSNorm(value, rangeMaximum = 255) {
  9659. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9660. }
  9661. function signNotZero(value) {
  9662. return value < 0.0 ? -1.0 : 1.0;
  9663. }
  9664. function octDecodeInRange(x, y, rangeMax, result) {
  9665. assert$2(result);
  9666. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9667. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9668. }
  9669. result.x = fromSNorm(x, rangeMax);
  9670. result.y = fromSNorm(y, rangeMax);
  9671. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9672. if (result.z < 0.0) {
  9673. const oldVX = result.x;
  9674. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9675. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9676. }
  9677. return result.normalize();
  9678. }
  9679. function octDecode(x, y, result) {
  9680. return octDecodeInRange(x, y, 255, result);
  9681. }
  9682. class Tile3DFeatureTable {
  9683. constructor(featureTableJson, featureTableBinary) {
  9684. _defineProperty(this, "json", void 0);
  9685. _defineProperty(this, "buffer", void 0);
  9686. _defineProperty(this, "featuresLength", 0);
  9687. _defineProperty(this, "_cachedTypedArrays", {});
  9688. this.json = featureTableJson;
  9689. this.buffer = featureTableBinary;
  9690. }
  9691. getExtension(extensionName) {
  9692. return this.json.extensions && this.json.extensions[extensionName];
  9693. }
  9694. hasProperty(propertyName) {
  9695. return Boolean(this.json[propertyName]);
  9696. }
  9697. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9698. const jsonValue = this.json[propertyName];
  9699. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9700. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9701. }
  9702. return jsonValue;
  9703. }
  9704. getPropertyArray(propertyName, componentType, componentLength) {
  9705. const jsonValue = this.json[propertyName];
  9706. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9707. if ('componentType' in jsonValue) {
  9708. componentType = GLType.fromName(jsonValue.componentType);
  9709. }
  9710. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9711. }
  9712. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9713. }
  9714. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9715. const jsonValue = this.json[propertyName];
  9716. if (!jsonValue) {
  9717. return jsonValue;
  9718. }
  9719. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9720. if (componentLength === 1) {
  9721. return typedArray[featureId];
  9722. }
  9723. for (let i = 0; i < componentLength; ++i) {
  9724. result[i] = typedArray[componentLength * featureId + i];
  9725. }
  9726. return result;
  9727. }
  9728. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9729. const cachedTypedArrays = this._cachedTypedArrays;
  9730. let typedArray = cachedTypedArrays[propertyName];
  9731. if (!typedArray) {
  9732. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9733. cachedTypedArrays[propertyName] = typedArray;
  9734. }
  9735. return typedArray;
  9736. }
  9737. _getTypedArrayFromArray(propertyName, componentType, array) {
  9738. const cachedTypedArrays = this._cachedTypedArrays;
  9739. let typedArray = cachedTypedArrays[propertyName];
  9740. if (!typedArray) {
  9741. typedArray = GLType.createTypedArray(componentType, array);
  9742. cachedTypedArrays[propertyName] = typedArray;
  9743. }
  9744. return typedArray;
  9745. }
  9746. }
  9747. const COMPONENTS_PER_ATTRIBUTE = {
  9748. SCALAR: 1,
  9749. VEC2: 2,
  9750. VEC3: 3,
  9751. VEC4: 4,
  9752. MAT2: 4,
  9753. MAT3: 9,
  9754. MAT4: 16
  9755. };
  9756. const UNPACKER = {
  9757. SCALAR: (values, i) => values[i],
  9758. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9759. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9760. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9761. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9762. 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]],
  9763. 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]]
  9764. };
  9765. const PACKER = {
  9766. SCALAR: (x, values, i) => {
  9767. values[i] = x;
  9768. },
  9769. VEC2: (x, values, i) => {
  9770. values[2 * i + 0] = x[0];
  9771. values[2 * i + 1] = x[1];
  9772. },
  9773. VEC3: (x, values, i) => {
  9774. values[3 * i + 0] = x[0];
  9775. values[3 * i + 1] = x[1];
  9776. values[3 * i + 2] = x[2];
  9777. },
  9778. VEC4: (x, values, i) => {
  9779. values[4 * i + 0] = x[0];
  9780. values[4 * i + 1] = x[1];
  9781. values[4 * i + 2] = x[2];
  9782. values[4 * i + 3] = x[3];
  9783. },
  9784. MAT2: (x, values, i) => {
  9785. values[4 * i + 0] = x[0];
  9786. values[4 * i + 1] = x[1];
  9787. values[4 * i + 2] = x[2];
  9788. values[4 * i + 3] = x[3];
  9789. },
  9790. MAT3: (x, values, i) => {
  9791. values[9 * i + 0] = x[0];
  9792. values[9 * i + 1] = x[1];
  9793. values[9 * i + 2] = x[2];
  9794. values[9 * i + 3] = x[3];
  9795. values[9 * i + 4] = x[4];
  9796. values[9 * i + 5] = x[5];
  9797. values[9 * i + 6] = x[6];
  9798. values[9 * i + 7] = x[7];
  9799. values[9 * i + 8] = x[8];
  9800. values[9 * i + 9] = x[9];
  9801. },
  9802. MAT4: (x, values, i) => {
  9803. values[16 * i + 0] = x[0];
  9804. values[16 * i + 1] = x[1];
  9805. values[16 * i + 2] = x[2];
  9806. values[16 * i + 3] = x[3];
  9807. values[16 * i + 4] = x[4];
  9808. values[16 * i + 5] = x[5];
  9809. values[16 * i + 6] = x[6];
  9810. values[16 * i + 7] = x[7];
  9811. values[16 * i + 8] = x[8];
  9812. values[16 * i + 9] = x[9];
  9813. values[16 * i + 10] = x[10];
  9814. values[16 * i + 11] = x[11];
  9815. values[16 * i + 12] = x[12];
  9816. values[16 * i + 13] = x[13];
  9817. values[16 * i + 14] = x[14];
  9818. values[16 * i + 15] = x[15];
  9819. }
  9820. };
  9821. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9822. const {
  9823. componentType
  9824. } = tile3DAccessor;
  9825. assert$7(tile3DAccessor.componentType);
  9826. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9827. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9828. const unpacker = UNPACKER[tile3DAccessor.type];
  9829. const packer = PACKER[tile3DAccessor.type];
  9830. byteOffset += tile3DAccessor.byteOffset;
  9831. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9832. return {
  9833. values,
  9834. type,
  9835. size,
  9836. unpacker,
  9837. packer
  9838. };
  9839. }
  9840. const defined$1 = x => x !== undefined;
  9841. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9842. if (!jsonHeader) {
  9843. return null;
  9844. }
  9845. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9846. const legacyHierarchy = jsonHeader.HIERARCHY;
  9847. if (legacyHierarchy) {
  9848. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9849. jsonHeader.extensions = jsonHeader.extensions || {};
  9850. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9851. hierarchy = legacyHierarchy;
  9852. }
  9853. if (!hierarchy) {
  9854. return null;
  9855. }
  9856. return initializeHierarchyValues(hierarchy, binaryBody);
  9857. }
  9858. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9859. let i;
  9860. let classId;
  9861. let binaryAccessor;
  9862. const instancesLength = hierarchyJson.instancesLength;
  9863. const classes = hierarchyJson.classes;
  9864. let classIds = hierarchyJson.classIds;
  9865. let parentCounts = hierarchyJson.parentCounts;
  9866. let parentIds = hierarchyJson.parentIds;
  9867. let parentIdsLength = instancesLength;
  9868. if (defined$1(classIds.byteOffset)) {
  9869. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9870. classIds.type = AttributeType.SCALAR;
  9871. binaryAccessor = getBinaryAccessor(classIds);
  9872. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9873. }
  9874. let parentIndexes;
  9875. if (defined$1(parentCounts)) {
  9876. if (defined$1(parentCounts.byteOffset)) {
  9877. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9878. parentCounts.type = AttributeType.SCALAR;
  9879. binaryAccessor = getBinaryAccessor(parentCounts);
  9880. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9881. }
  9882. parentIndexes = new Uint16Array(instancesLength);
  9883. parentIdsLength = 0;
  9884. for (i = 0; i < instancesLength; ++i) {
  9885. parentIndexes[i] = parentIdsLength;
  9886. parentIdsLength += parentCounts[i];
  9887. }
  9888. }
  9889. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  9890. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  9891. parentIds.type = AttributeType.SCALAR;
  9892. binaryAccessor = getBinaryAccessor(parentIds);
  9893. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  9894. }
  9895. const classesLength = classes.length;
  9896. for (i = 0; i < classesLength; ++i) {
  9897. const classInstancesLength = classes[i].length;
  9898. const properties = classes[i].instances;
  9899. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  9900. classes[i].instances = combine(binaryProperties, properties);
  9901. }
  9902. const classCounts = new Array(classesLength).fill(0);
  9903. const classIndexes = new Uint16Array(instancesLength);
  9904. for (i = 0; i < instancesLength; ++i) {
  9905. classId = classIds[i];
  9906. classIndexes[i] = classCounts[classId];
  9907. ++classCounts[classId];
  9908. }
  9909. const hierarchy = {
  9910. classes,
  9911. classIds,
  9912. classIndexes,
  9913. parentCounts,
  9914. parentIndexes,
  9915. parentIds
  9916. };
  9917. validateHierarchy(hierarchy);
  9918. return hierarchy;
  9919. }
  9920. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  9921. if (!hierarchy) {
  9922. return;
  9923. }
  9924. const parentCounts = hierarchy.parentCounts;
  9925. const parentIds = hierarchy.parentIds;
  9926. if (parentIds) {
  9927. return endConditionCallback(hierarchy, instanceIndex);
  9928. }
  9929. if (parentCounts > 0) {
  9930. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  9931. }
  9932. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  9933. }
  9934. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  9935. const classIds = hierarchy.classIds;
  9936. const parentCounts = hierarchy.parentCounts;
  9937. const parentIds = hierarchy.parentIds;
  9938. const parentIndexes = hierarchy.parentIndexes;
  9939. const instancesLength = classIds.length;
  9940. const visited = scratchVisited;
  9941. visited.length = Math.max(visited.length, instancesLength);
  9942. const visitedMarker = ++marker;
  9943. const stack = scratchStack;
  9944. stack.length = 0;
  9945. stack.push(instanceIndex);
  9946. while (stack.length > 0) {
  9947. instanceIndex = stack.pop();
  9948. if (visited[instanceIndex] === visitedMarker) {
  9949. continue;
  9950. }
  9951. visited[instanceIndex] = visitedMarker;
  9952. const result = endConditionCallback(hierarchy, instanceIndex);
  9953. if (defined$1(result)) {
  9954. return result;
  9955. }
  9956. const parentCount = parentCounts[instanceIndex];
  9957. const parentIndex = parentIndexes[instanceIndex];
  9958. for (let i = 0; i < parentCount; ++i) {
  9959. const parentId = parentIds[parentIndex + i];
  9960. if (parentId !== instanceIndex) {
  9961. stack.push(parentId);
  9962. }
  9963. }
  9964. }
  9965. return null;
  9966. }
  9967. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  9968. let hasParent = true;
  9969. while (hasParent) {
  9970. const result = endConditionCallback(hierarchy, instanceIndex);
  9971. if (defined$1(result)) {
  9972. return result;
  9973. }
  9974. const parentId = hierarchy.parentIds[instanceIndex];
  9975. hasParent = parentId !== instanceIndex;
  9976. instanceIndex = parentId;
  9977. }
  9978. throw new Error('traverseHierarchySingleParent');
  9979. }
  9980. function validateHierarchy(hierarchy) {
  9981. const classIds = hierarchy.classIds;
  9982. const instancesLength = classIds.length;
  9983. for (let i = 0; i < instancesLength; ++i) {
  9984. validateInstance(hierarchy, i, stack);
  9985. }
  9986. }
  9987. function validateInstance(hierarchy, instanceIndex, stack) {
  9988. const parentCounts = hierarchy.parentCounts;
  9989. const parentIds = hierarchy.parentIds;
  9990. const parentIndexes = hierarchy.parentIndexes;
  9991. const classIds = hierarchy.classIds;
  9992. const instancesLength = classIds.length;
  9993. if (!defined$1(parentIds)) {
  9994. return;
  9995. }
  9996. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  9997. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  9998. stack.push(instanceIndex);
  9999. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10000. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10001. for (let i = 0; i < parentCount; ++i) {
  10002. const parentId = parentIds[parentIndex + i];
  10003. if (parentId !== instanceIndex) {
  10004. validateInstance(hierarchy, parentId, stack);
  10005. }
  10006. }
  10007. stack.pop(instanceIndex);
  10008. }
  10009. function defined(x) {
  10010. return x !== undefined && x !== null;
  10011. }
  10012. const clone = (x, y) => x;
  10013. const IGNORED_PROPERTY_FIELDS = {
  10014. HIERARCHY: true,
  10015. extensions: true,
  10016. extras: true
  10017. };
  10018. class Tile3DBatchTableParser {
  10019. constructor(json, binary, featureCount, options = {}) {
  10020. var _this$json;
  10021. _defineProperty(this, "json", void 0);
  10022. _defineProperty(this, "binary", void 0);
  10023. _defineProperty(this, "featureCount", void 0);
  10024. _defineProperty(this, "_extensions", void 0);
  10025. _defineProperty(this, "_properties", void 0);
  10026. _defineProperty(this, "_binaryProperties", void 0);
  10027. _defineProperty(this, "_hierarchy", void 0);
  10028. assert$7(featureCount >= 0);
  10029. this.json = json || {};
  10030. this.binary = binary;
  10031. this.featureCount = featureCount;
  10032. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10033. this._properties = {};
  10034. for (const propertyName in this.json) {
  10035. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10036. this._properties[propertyName] = this.json[propertyName];
  10037. }
  10038. }
  10039. this._binaryProperties = this._initializeBinaryProperties();
  10040. if (options['3DTILES_batch_table_hierarchy']) {
  10041. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10042. }
  10043. }
  10044. getExtension(extensionName) {
  10045. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10046. }
  10047. memorySizeInBytes() {
  10048. return 0;
  10049. }
  10050. isClass(batchId, className) {
  10051. this._checkBatchId(batchId);
  10052. assert$7(typeof className === 'string', className);
  10053. if (this._hierarchy) {
  10054. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10055. const classId = hierarchy.classIds[instanceIndex];
  10056. const instanceClass = hierarchy.classes[classId];
  10057. return instanceClass.name === className;
  10058. });
  10059. return defined(result);
  10060. }
  10061. return false;
  10062. }
  10063. isExactClass(batchId, className) {
  10064. assert$7(typeof className === 'string', className);
  10065. return this.getExactClassName(batchId) === className;
  10066. }
  10067. getExactClassName(batchId) {
  10068. this._checkBatchId(batchId);
  10069. if (this._hierarchy) {
  10070. const classId = this._hierarchy.classIds[batchId];
  10071. const instanceClass = this._hierarchy.classes[classId];
  10072. return instanceClass.name;
  10073. }
  10074. return undefined;
  10075. }
  10076. hasProperty(batchId, name) {
  10077. this._checkBatchId(batchId);
  10078. assert$7(typeof name === 'string', name);
  10079. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10080. }
  10081. getPropertyNames(batchId, results) {
  10082. this._checkBatchId(batchId);
  10083. results = defined(results) ? results : [];
  10084. results.length = 0;
  10085. const propertyNames = Object.keys(this._properties);
  10086. results.push(...propertyNames);
  10087. if (this._hierarchy) {
  10088. this._getPropertyNamesInHierarchy(batchId, results);
  10089. }
  10090. return results;
  10091. }
  10092. getProperty(batchId, name) {
  10093. this._checkBatchId(batchId);
  10094. assert$7(typeof name === 'string', name);
  10095. if (this._binaryProperties) {
  10096. const binaryProperty = this._binaryProperties[name];
  10097. if (defined(binaryProperty)) {
  10098. return this._getBinaryProperty(binaryProperty, batchId);
  10099. }
  10100. }
  10101. const propertyValues = this._properties[name];
  10102. if (defined(propertyValues)) {
  10103. return clone(propertyValues[batchId]);
  10104. }
  10105. if (this._hierarchy) {
  10106. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10107. if (defined(hierarchyProperty)) {
  10108. return hierarchyProperty;
  10109. }
  10110. }
  10111. return undefined;
  10112. }
  10113. setProperty(batchId, name, value) {
  10114. const featureCount = this.featureCount;
  10115. this._checkBatchId(batchId);
  10116. assert$7(typeof name === 'string', name);
  10117. if (this._binaryProperties) {
  10118. const binaryProperty = this._binaryProperties[name];
  10119. if (binaryProperty) {
  10120. this._setBinaryProperty(binaryProperty, batchId, value);
  10121. return;
  10122. }
  10123. }
  10124. if (this._hierarchy) {
  10125. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10126. return;
  10127. }
  10128. }
  10129. let propertyValues = this._properties[name];
  10130. if (!defined(propertyValues)) {
  10131. this._properties[name] = new Array(featureCount);
  10132. propertyValues = this._properties[name];
  10133. }
  10134. propertyValues[batchId] = clone(value);
  10135. }
  10136. _checkBatchId(batchId) {
  10137. const valid = batchId >= 0 && batchId < this.featureCount;
  10138. if (!valid) {
  10139. throw new Error('batchId not in range [0, featureCount - 1].');
  10140. }
  10141. }
  10142. _getBinaryProperty(binaryProperty, index) {
  10143. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10144. }
  10145. _setBinaryProperty(binaryProperty, index, value) {
  10146. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10147. }
  10148. _initializeBinaryProperties() {
  10149. let binaryProperties = null;
  10150. for (const name in this._properties) {
  10151. const property = this._properties[name];
  10152. const binaryProperty = this._initializeBinaryProperty(name, property);
  10153. if (binaryProperty) {
  10154. binaryProperties = binaryProperties || {};
  10155. binaryProperties[name] = binaryProperty;
  10156. }
  10157. }
  10158. return binaryProperties;
  10159. }
  10160. _initializeBinaryProperty(name, property) {
  10161. if ('byteOffset' in property) {
  10162. const tile3DAccessor = property;
  10163. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10164. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10165. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10166. return {
  10167. typedArray: accessor.values,
  10168. componentCount: accessor.size,
  10169. unpack: accessor.unpacker,
  10170. pack: accessor.packer
  10171. };
  10172. }
  10173. return null;
  10174. }
  10175. _hasPropertyInHierarchy(batchId, name) {
  10176. if (!this._hierarchy) {
  10177. return false;
  10178. }
  10179. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10180. const classId = hierarchy.classIds[instanceIndex];
  10181. const instances = hierarchy.classes[classId].instances;
  10182. return defined(instances[name]);
  10183. });
  10184. return defined(result);
  10185. }
  10186. _getPropertyNamesInHierarchy(batchId, results) {
  10187. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10188. const classId = hierarchy.classIds[instanceIndex];
  10189. const instances = hierarchy.classes[classId].instances;
  10190. for (const name in instances) {
  10191. if (instances.hasOwnProperty(name)) {
  10192. if (results.indexOf(name) === -1) {
  10193. results.push(name);
  10194. }
  10195. }
  10196. }
  10197. });
  10198. }
  10199. _getHierarchyProperty(batchId, name) {
  10200. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10201. const classId = hierarchy.classIds[instanceIndex];
  10202. const instanceClass = hierarchy.classes[classId];
  10203. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10204. const propertyValues = instanceClass.instances[name];
  10205. if (defined(propertyValues)) {
  10206. if (defined(propertyValues.typedArray)) {
  10207. return this._getBinaryProperty(propertyValues, indexInClass);
  10208. }
  10209. return clone(propertyValues[indexInClass]);
  10210. }
  10211. return null;
  10212. });
  10213. }
  10214. _setHierarchyProperty(batchTable, batchId, name, value) {
  10215. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10216. const classId = hierarchy.classIds[instanceIndex];
  10217. const instanceClass = hierarchy.classes[classId];
  10218. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10219. const propertyValues = instanceClass.instances[name];
  10220. if (defined(propertyValues)) {
  10221. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10222. if (defined(propertyValues.typedArray)) {
  10223. this._setBinaryProperty(propertyValues, indexInClass, value);
  10224. } else {
  10225. propertyValues[indexInClass] = clone(value);
  10226. }
  10227. return true;
  10228. }
  10229. return false;
  10230. });
  10231. return defined(result);
  10232. }
  10233. }
  10234. const SIZEOF_UINT32$1 = 4;
  10235. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10236. const view = new DataView(arrayBuffer);
  10237. tile.magic = view.getUint32(byteOffset, true);
  10238. byteOffset += SIZEOF_UINT32$1;
  10239. tile.version = view.getUint32(byteOffset, true);
  10240. byteOffset += SIZEOF_UINT32$1;
  10241. tile.byteLength = view.getUint32(byteOffset, true);
  10242. byteOffset += SIZEOF_UINT32$1;
  10243. if (tile.version !== 1) {
  10244. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10245. }
  10246. return byteOffset;
  10247. }
  10248. const SIZEOF_UINT32 = 4;
  10249. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10250. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10251. const view = new DataView(arrayBuffer);
  10252. let batchLength;
  10253. tile.header = tile.header || {};
  10254. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10255. byteOffset += SIZEOF_UINT32;
  10256. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10257. byteOffset += SIZEOF_UINT32;
  10258. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10259. byteOffset += SIZEOF_UINT32;
  10260. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10261. byteOffset += SIZEOF_UINT32;
  10262. if (batchTableJsonByteLength >= 570425344) {
  10263. byteOffset -= SIZEOF_UINT32 * 2;
  10264. batchLength = featureTableJsonByteLength;
  10265. batchTableJsonByteLength = featureTableBinaryByteLength;
  10266. batchTableBinaryByteLength = 0;
  10267. featureTableJsonByteLength = 0;
  10268. featureTableBinaryByteLength = 0;
  10269. console.warn(DEPRECATION_WARNING);
  10270. } else if (batchTableBinaryByteLength >= 570425344) {
  10271. byteOffset -= SIZEOF_UINT32;
  10272. batchLength = batchTableJsonByteLength;
  10273. batchTableJsonByteLength = featureTableJsonByteLength;
  10274. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10275. featureTableJsonByteLength = 0;
  10276. featureTableBinaryByteLength = 0;
  10277. console.warn(DEPRECATION_WARNING);
  10278. }
  10279. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10280. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10281. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10282. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10283. tile.header.batchLength = batchLength;
  10284. return byteOffset;
  10285. }
  10286. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10287. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10288. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10289. return byteOffset;
  10290. }
  10291. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10292. const {
  10293. featureTableJsonByteLength,
  10294. featureTableBinaryByteLength,
  10295. batchLength
  10296. } = tile.header;
  10297. tile.featureTableJson = {
  10298. BATCH_LENGTH: batchLength || 0
  10299. };
  10300. if (featureTableJsonByteLength > 0) {
  10301. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10302. tile.featureTableJson = JSON.parse(featureTableString);
  10303. }
  10304. byteOffset += featureTableJsonByteLength;
  10305. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10306. byteOffset += featureTableBinaryByteLength;
  10307. return byteOffset;
  10308. }
  10309. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10310. const {
  10311. batchTableJsonByteLength,
  10312. batchTableBinaryByteLength
  10313. } = tile.header;
  10314. if (batchTableJsonByteLength > 0) {
  10315. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10316. tile.batchTableJson = JSON.parse(batchTableString);
  10317. byteOffset += batchTableJsonByteLength;
  10318. if (batchTableBinaryByteLength > 0) {
  10319. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10320. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10321. byteOffset += batchTableBinaryByteLength;
  10322. }
  10323. }
  10324. return byteOffset;
  10325. }
  10326. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10327. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10328. return null;
  10329. }
  10330. const {
  10331. batchIds,
  10332. isRGB565,
  10333. pointCount
  10334. } = tile;
  10335. if (batchIds && batchTable) {
  10336. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10337. for (let i = 0; i < pointCount; i++) {
  10338. const batchId = batchIds[i];
  10339. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10340. const color = dimensions.map(d => d * 255);
  10341. colorArray[i * 3] = color[0];
  10342. colorArray[i * 3 + 1] = color[1];
  10343. colorArray[i * 3 + 2] = color[2];
  10344. }
  10345. return {
  10346. type: GL$1.UNSIGNED_BYTE,
  10347. value: colorArray,
  10348. size: 3,
  10349. normalized: true
  10350. };
  10351. }
  10352. if (isRGB565) {
  10353. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10354. for (let i = 0; i < pointCount; i++) {
  10355. const color = decodeRGB565(colors[i]);
  10356. colorArray[i * 3] = color[0];
  10357. colorArray[i * 3 + 1] = color[1];
  10358. colorArray[i * 3 + 2] = color[2];
  10359. }
  10360. return {
  10361. type: GL$1.UNSIGNED_BYTE,
  10362. value: colorArray,
  10363. size: 3,
  10364. normalized: true
  10365. };
  10366. }
  10367. if (colors && colors.length === pointCount * 3) {
  10368. return {
  10369. type: GL$1.UNSIGNED_BYTE,
  10370. value: colors,
  10371. size: 3,
  10372. normalized: true
  10373. };
  10374. }
  10375. return {
  10376. type: GL$1.UNSIGNED_BYTE,
  10377. value: colors,
  10378. size: 4,
  10379. normalized: true
  10380. };
  10381. }
  10382. const scratchNormal = new Vector3();
  10383. function normalize3DTileNormalAttribute(tile, normals) {
  10384. if (!normals) {
  10385. return null;
  10386. }
  10387. if (tile.isOctEncoded16P) {
  10388. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10389. for (let i = 0; i < tile.pointsLength; i++) {
  10390. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10391. scratchNormal.toArray(decodedArray, i * 3);
  10392. }
  10393. return {
  10394. type: GL$1.FLOAT,
  10395. size: 2,
  10396. value: decodedArray
  10397. };
  10398. }
  10399. return {
  10400. type: GL$1.FLOAT,
  10401. size: 2,
  10402. value: normals
  10403. };
  10404. }
  10405. function normalize3DTilePositionAttribute(tile, positions, options) {
  10406. if (!tile.isQuantized) {
  10407. return positions;
  10408. }
  10409. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10410. tile.isQuantized = false;
  10411. return decodeQuantizedPositions(tile, positions);
  10412. }
  10413. return {
  10414. type: GL$1.UNSIGNED_SHORT,
  10415. value: positions,
  10416. size: 3,
  10417. normalized: true
  10418. };
  10419. }
  10420. function decodeQuantizedPositions(tile, positions) {
  10421. const scratchPosition = new Vector3();
  10422. const decodedArray = new Float32Array(tile.pointCount * 3);
  10423. for (let i = 0; i < tile.pointCount; i++) {
  10424. 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);
  10425. }
  10426. return decodedArray;
  10427. }
  10428. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10429. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10430. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10431. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10432. initializeTile(tile);
  10433. const {
  10434. featureTable,
  10435. batchTable
  10436. } = parsePointCloudTables(tile);
  10437. await parseDraco(tile, featureTable, batchTable, options, context);
  10438. parsePositions(tile, featureTable, options);
  10439. parseColors(tile, featureTable, batchTable);
  10440. parseNormals(tile, featureTable);
  10441. return byteOffset;
  10442. }
  10443. function initializeTile(tile) {
  10444. tile.attributes = {
  10445. positions: null,
  10446. colors: null,
  10447. normals: null,
  10448. batchIds: null
  10449. };
  10450. tile.isQuantized = false;
  10451. tile.isTranslucent = false;
  10452. tile.isRGB565 = false;
  10453. tile.isOctEncoded16P = false;
  10454. }
  10455. function parsePointCloudTables(tile) {
  10456. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10457. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10458. if (!Number.isFinite(pointsLength)) {
  10459. throw new Error('POINTS_LENGTH must be defined');
  10460. }
  10461. featureTable.featuresLength = pointsLength;
  10462. tile.featuresLength = pointsLength;
  10463. tile.pointsLength = pointsLength;
  10464. tile.pointCount = pointsLength;
  10465. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10466. const batchTable = parseBatchIds(tile, featureTable);
  10467. return {
  10468. featureTable,
  10469. batchTable
  10470. };
  10471. }
  10472. function parsePositions(tile, featureTable, options) {
  10473. if (!tile.attributes.positions) {
  10474. if (featureTable.hasProperty('POSITION')) {
  10475. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10476. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10477. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10478. tile.isQuantized = true;
  10479. tile.quantizedRange = (1 << 16) - 1;
  10480. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10481. if (!tile.quantizedVolumeScale) {
  10482. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10483. }
  10484. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10485. if (!tile.quantizedVolumeOffset) {
  10486. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10487. }
  10488. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10489. }
  10490. }
  10491. if (!tile.attributes.positions) {
  10492. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10493. }
  10494. }
  10495. function parseColors(tile, featureTable, batchTable) {
  10496. if (!tile.attributes.colors) {
  10497. let colors = null;
  10498. if (featureTable.hasProperty('RGBA')) {
  10499. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10500. tile.isTranslucent = true;
  10501. } else if (featureTable.hasProperty('RGB')) {
  10502. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10503. } else if (featureTable.hasProperty('RGB565')) {
  10504. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10505. tile.isRGB565 = true;
  10506. }
  10507. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10508. }
  10509. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10510. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10511. }
  10512. }
  10513. function parseNormals(tile, featureTable) {
  10514. if (!tile.attributes.normals) {
  10515. let normals = null;
  10516. if (featureTable.hasProperty('NORMAL')) {
  10517. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10518. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10519. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10520. tile.isOctEncoded16P = true;
  10521. }
  10522. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10523. }
  10524. }
  10525. function parseBatchIds(tile, featureTable) {
  10526. let batchTable = null;
  10527. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10528. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10529. if (tile.batchIds) {
  10530. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10531. if (!batchFeatureLength) {
  10532. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10533. }
  10534. const {
  10535. batchTableJson,
  10536. batchTableBinary
  10537. } = tile;
  10538. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10539. }
  10540. }
  10541. return batchTable;
  10542. }
  10543. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10544. let dracoBuffer;
  10545. let dracoFeatureTableProperties;
  10546. let dracoBatchTableProperties;
  10547. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10548. if (batchTableDraco) {
  10549. dracoBatchTableProperties = batchTableDraco.properties;
  10550. }
  10551. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10552. if (featureTableDraco) {
  10553. dracoFeatureTableProperties = featureTableDraco.properties;
  10554. const dracoByteOffset = featureTableDraco.byteOffset;
  10555. const dracoByteLength = featureTableDraco.byteLength;
  10556. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10557. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10558. }
  10559. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10560. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10561. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10562. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10563. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10564. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10565. }
  10566. if (!dracoBuffer) {
  10567. return true;
  10568. }
  10569. const dracoData = {
  10570. buffer: dracoBuffer,
  10571. properties: { ...dracoFeatureTableProperties,
  10572. ...dracoBatchTableProperties
  10573. },
  10574. featureTableProperties: dracoFeatureTableProperties,
  10575. batchTableProperties: dracoBatchTableProperties,
  10576. dequantizeInShader: false
  10577. };
  10578. return await loadDraco(tile, dracoData, options, context);
  10579. }
  10580. async function loadDraco(tile, dracoData, options, context) {
  10581. const {
  10582. parse
  10583. } = context;
  10584. const dracoOptions = { ...options,
  10585. draco: { ...options.draco,
  10586. extraAttributes: dracoData.batchTableProperties || {}
  10587. }
  10588. };
  10589. delete dracoOptions['3d-tiles'];
  10590. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10591. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10592. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10593. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10594. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10595. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10596. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10597. if (isQuantizedDraco) {
  10598. const quantization = data.POSITION.data.quantization;
  10599. const range = quantization.range;
  10600. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10601. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10602. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10603. tile.isQuantizedDraco = true;
  10604. }
  10605. if (isOctEncodedDraco) {
  10606. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10607. tile.isOctEncodedDraco = true;
  10608. }
  10609. const batchTableAttributes = {};
  10610. if (dracoData.batchTableProperties) {
  10611. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10612. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10613. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10614. }
  10615. }
  10616. }
  10617. tile.attributes = {
  10618. positions: decodedPositions,
  10619. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10620. normals: decodedNormals,
  10621. batchIds: decodedBatchIds,
  10622. ...batchTableAttributes
  10623. };
  10624. }
  10625. const VERSION$3 = "3.1.4" ;
  10626. const VERSION$2 = "3.1.4" ;
  10627. const VERSION$1 = "3.1.4" ;
  10628. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10629. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10630. let loadBasisTranscoderPromise;
  10631. async function loadBasisTrascoderModule(options) {
  10632. const modules = options.modules || {};
  10633. if (modules.basis) {
  10634. return modules.basis;
  10635. }
  10636. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10637. return await loadBasisTranscoderPromise;
  10638. }
  10639. async function loadBasisTrascoder(options) {
  10640. let BASIS = null;
  10641. let wasmBinary = null;
  10642. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10643. BASIS = BASIS || globalThis.BASIS;
  10644. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10645. }
  10646. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10647. const options = {};
  10648. if (wasmBinary) {
  10649. options.wasmBinary = wasmBinary;
  10650. }
  10651. return new Promise(resolve => {
  10652. BasisModule(options).then(module => {
  10653. const {
  10654. BasisFile,
  10655. initializeBasis
  10656. } = module;
  10657. initializeBasis();
  10658. resolve({
  10659. BasisFile
  10660. });
  10661. });
  10662. });
  10663. }
  10664. let loadBasisEncoderPromise;
  10665. async function loadBasisEncoderModule(options) {
  10666. const modules = options.modules || {};
  10667. if (modules.basisEncoder) {
  10668. return modules.basisEncoder;
  10669. }
  10670. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10671. return await loadBasisEncoderPromise;
  10672. }
  10673. async function loadBasisEncoder(options) {
  10674. let BASIS_ENCODER = null;
  10675. let wasmBinary = null;
  10676. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10677. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10678. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10679. }
  10680. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10681. const options = {};
  10682. if (wasmBinary) {
  10683. options.wasmBinary = wasmBinary;
  10684. }
  10685. return new Promise(resolve => {
  10686. BasisEncoderModule(options).then(module => {
  10687. const {
  10688. BasisFile,
  10689. KTX2File,
  10690. initializeBasis,
  10691. BasisEncoder
  10692. } = module;
  10693. initializeBasis();
  10694. resolve({
  10695. BasisFile,
  10696. KTX2File,
  10697. BasisEncoder
  10698. });
  10699. });
  10700. });
  10701. }
  10702. const GL_EXTENSIONS_CONSTANTS = {
  10703. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10704. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10705. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10706. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10707. COMPRESSED_R11_EAC: 0x9270,
  10708. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10709. COMPRESSED_RG11_EAC: 0x9272,
  10710. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10711. COMPRESSED_RGB8_ETC2: 0x9274,
  10712. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10713. COMPRESSED_SRGB8_ETC2: 0x9276,
  10714. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10715. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10716. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10717. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10718. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10719. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10720. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10721. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10722. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10723. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10724. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10725. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10726. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10727. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10728. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10729. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10730. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10731. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10732. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10733. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10734. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10735. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10736. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10737. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10738. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10739. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10740. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10741. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10742. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10743. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10744. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10745. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10746. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10747. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10748. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10749. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10750. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10751. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10752. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10753. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10754. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10755. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10756. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10757. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10758. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10759. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10760. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10761. };
  10762. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10763. const WEBGL_EXTENSIONS = {
  10764. WEBGL_compressed_texture_s3tc: 'dxt',
  10765. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10766. WEBGL_compressed_texture_etc1: 'etc1',
  10767. WEBGL_compressed_texture_etc: 'etc2',
  10768. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10769. WEBGL_compressed_texture_atc: 'atc',
  10770. WEBGL_compressed_texture_astc: 'astc',
  10771. EXT_texture_compression_rgtc: 'rgtc'
  10772. };
  10773. let formats = null;
  10774. function getSupportedGPUTextureFormats(gl) {
  10775. if (!formats) {
  10776. gl = gl || getWebGLContext() || undefined;
  10777. formats = new Set();
  10778. for (const prefix of BROWSER_PREFIXES) {
  10779. for (const extension in WEBGL_EXTENSIONS) {
  10780. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10781. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10782. formats.add(gpuTextureFormat);
  10783. }
  10784. }
  10785. }
  10786. }
  10787. return formats;
  10788. }
  10789. function getWebGLContext() {
  10790. try {
  10791. const canvas = document.createElement('canvas');
  10792. return canvas.getContext('webgl');
  10793. } catch (error) {
  10794. return null;
  10795. }
  10796. }
  10797. 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={}));
  10798. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10799. function isKTX(data) {
  10800. const id = new Uint8Array(data);
  10801. 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];
  10802. return !notKTX;
  10803. }
  10804. const OutputFormat = {
  10805. etc1: {
  10806. basisFormat: 0,
  10807. compressed: true,
  10808. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10809. },
  10810. etc2: {
  10811. basisFormat: 1,
  10812. compressed: true
  10813. },
  10814. bc1: {
  10815. basisFormat: 2,
  10816. compressed: true,
  10817. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10818. },
  10819. bc3: {
  10820. basisFormat: 3,
  10821. compressed: true,
  10822. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10823. },
  10824. bc4: {
  10825. basisFormat: 4,
  10826. compressed: true
  10827. },
  10828. bc5: {
  10829. basisFormat: 5,
  10830. compressed: true
  10831. },
  10832. 'bc7-m6-opaque-only': {
  10833. basisFormat: 6,
  10834. compressed: true
  10835. },
  10836. 'bc7-m5': {
  10837. basisFormat: 7,
  10838. compressed: true
  10839. },
  10840. 'pvrtc1-4-rgb': {
  10841. basisFormat: 8,
  10842. compressed: true,
  10843. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10844. },
  10845. 'pvrtc1-4-rgba': {
  10846. basisFormat: 9,
  10847. compressed: true,
  10848. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10849. },
  10850. 'astc-4x4': {
  10851. basisFormat: 10,
  10852. compressed: true,
  10853. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10854. },
  10855. 'atc-rgb': {
  10856. basisFormat: 11,
  10857. compressed: true
  10858. },
  10859. 'atc-rgba-interpolated-alpha': {
  10860. basisFormat: 12,
  10861. compressed: true
  10862. },
  10863. rgba32: {
  10864. basisFormat: 13,
  10865. compressed: false
  10866. },
  10867. rgb565: {
  10868. basisFormat: 14,
  10869. compressed: false
  10870. },
  10871. bgr565: {
  10872. basisFormat: 15,
  10873. compressed: false
  10874. },
  10875. rgba4444: {
  10876. basisFormat: 16,
  10877. compressed: false
  10878. }
  10879. };
  10880. async function parseBasis(data, options) {
  10881. if (options.basis.containerFormat === 'auto') {
  10882. if (isKTX(data)) {
  10883. const fileConstructors = await loadBasisEncoderModule(options);
  10884. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10885. }
  10886. const {
  10887. BasisFile
  10888. } = await loadBasisTrascoderModule(options);
  10889. return parseBasisFile(BasisFile, data, options);
  10890. }
  10891. switch (options.basis.module) {
  10892. case 'encoder':
  10893. const fileConstructors = await loadBasisEncoderModule(options);
  10894. switch (options.basis.containerFormat) {
  10895. case 'ktx2':
  10896. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10897. case 'basis':
  10898. default:
  10899. return parseBasisFile(fileConstructors.BasisFile, data, options);
  10900. }
  10901. case 'transcoder':
  10902. default:
  10903. const {
  10904. BasisFile
  10905. } = await loadBasisTrascoderModule(options);
  10906. return parseBasisFile(BasisFile, data, options);
  10907. }
  10908. }
  10909. function parseBasisFile(BasisFile, data, options) {
  10910. const basisFile = new BasisFile(new Uint8Array(data));
  10911. try {
  10912. if (!basisFile.startTranscoding()) {
  10913. return null;
  10914. }
  10915. const imageCount = basisFile.getNumImages();
  10916. const images = [];
  10917. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  10918. const levelsCount = basisFile.getNumLevels(imageIndex);
  10919. const levels = [];
  10920. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10921. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  10922. }
  10923. images.push(levels);
  10924. }
  10925. return images;
  10926. } finally {
  10927. basisFile.close();
  10928. basisFile.delete();
  10929. }
  10930. }
  10931. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  10932. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  10933. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  10934. const hasAlpha = basisFile.getHasAlpha();
  10935. const {
  10936. compressed,
  10937. format,
  10938. basisFormat
  10939. } = getBasisOptions(options, hasAlpha);
  10940. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  10941. const decodedData = new Uint8Array(decodedSize);
  10942. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  10943. return null;
  10944. }
  10945. return {
  10946. width,
  10947. height,
  10948. data: decodedData,
  10949. compressed,
  10950. hasAlpha,
  10951. format
  10952. };
  10953. }
  10954. function parseKTX2File(KTX2File, data, options) {
  10955. const ktx2File = new KTX2File(new Uint8Array(data));
  10956. try {
  10957. if (!ktx2File.startTranscoding()) {
  10958. return null;
  10959. }
  10960. const levelsCount = ktx2File.getLevels();
  10961. const levels = [];
  10962. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10963. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  10964. break;
  10965. }
  10966. return levels;
  10967. } finally {
  10968. ktx2File.close();
  10969. ktx2File.delete();
  10970. }
  10971. }
  10972. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  10973. const {
  10974. alphaFlag,
  10975. height,
  10976. width
  10977. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  10978. const {
  10979. compressed,
  10980. format,
  10981. basisFormat
  10982. } = getBasisOptions(options, alphaFlag);
  10983. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  10984. const decodedData = new Uint8Array(decodedSize);
  10985. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  10986. return null;
  10987. }
  10988. return {
  10989. width,
  10990. height,
  10991. data: decodedData,
  10992. compressed,
  10993. alphaFlag,
  10994. format
  10995. };
  10996. }
  10997. function getBasisOptions(options, hasAlpha) {
  10998. let format = options && options.basis && options.basis.format;
  10999. if (format === 'auto') {
  11000. format = selectSupportedBasisFormat();
  11001. }
  11002. if (typeof format === 'object') {
  11003. format = hasAlpha ? format.alpha : format.noAlpha;
  11004. }
  11005. format = format.toLowerCase();
  11006. return OutputFormat[format];
  11007. }
  11008. function selectSupportedBasisFormat() {
  11009. const supportedFormats = getSupportedGPUTextureFormats();
  11010. if (supportedFormats.has('astc')) {
  11011. return 'astc-4x4';
  11012. } else if (supportedFormats.has('dxt')) {
  11013. return {
  11014. alpha: 'bc3',
  11015. noAlpha: 'bc1'
  11016. };
  11017. } else if (supportedFormats.has('pvrtc')) {
  11018. return {
  11019. alpha: 'pvrtc1-4-rgba',
  11020. noAlpha: 'pvrtc1-4-rgb'
  11021. };
  11022. } else if (supportedFormats.has('etc1')) {
  11023. return 'etc1';
  11024. } else if (supportedFormats.has('etc2')) {
  11025. return 'etc2';
  11026. }
  11027. return 'rgb565';
  11028. }
  11029. const BasisWorkerLoader = {
  11030. name: 'Basis',
  11031. id: 'basis',
  11032. module: 'textures',
  11033. version: VERSION$2,
  11034. worker: true,
  11035. extensions: ['basis', 'ktx2'],
  11036. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11037. tests: ['sB'],
  11038. binary: true,
  11039. options: {
  11040. basis: {
  11041. format: 'auto',
  11042. libraryPath: 'libs/',
  11043. containerFormat: 'auto',
  11044. module: 'transcoder'
  11045. }
  11046. }
  11047. };
  11048. const BasisLoader = { ...BasisWorkerLoader,
  11049. parse: parseBasis
  11050. };
  11051. const VERSION = "3.1.4" ;
  11052. const {
  11053. _parseImageNode
  11054. } = globalThis;
  11055. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11056. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11057. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11058. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11059. function isImageTypeSupported(type) {
  11060. switch (type) {
  11061. case 'auto':
  11062. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11063. case 'imagebitmap':
  11064. return IMAGE_BITMAP_SUPPORTED;
  11065. case 'image':
  11066. return IMAGE_SUPPORTED;
  11067. case 'data':
  11068. return DATA_SUPPORTED;
  11069. default:
  11070. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11071. }
  11072. }
  11073. function getDefaultImageType() {
  11074. if (IMAGE_BITMAP_SUPPORTED) {
  11075. return 'imagebitmap';
  11076. }
  11077. if (IMAGE_SUPPORTED) {
  11078. return 'image';
  11079. }
  11080. if (DATA_SUPPORTED) {
  11081. return 'data';
  11082. }
  11083. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11084. }
  11085. function getImageType(image) {
  11086. const format = getImageTypeOrNull(image);
  11087. if (!format) {
  11088. throw new Error('Not an image');
  11089. }
  11090. return format;
  11091. }
  11092. function getImageData(image) {
  11093. switch (getImageType(image)) {
  11094. case 'data':
  11095. return image;
  11096. case 'image':
  11097. case 'imagebitmap':
  11098. const canvas = document.createElement('canvas');
  11099. const context = canvas.getContext('2d');
  11100. if (!context) {
  11101. throw new Error('getImageData');
  11102. }
  11103. canvas.width = image.width;
  11104. canvas.height = image.height;
  11105. context.drawImage(image, 0, 0);
  11106. return context.getImageData(0, 0, image.width, image.height);
  11107. default:
  11108. throw new Error('getImageData');
  11109. }
  11110. }
  11111. function getImageTypeOrNull(image) {
  11112. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11113. return 'imagebitmap';
  11114. }
  11115. if (typeof Image !== 'undefined' && image instanceof Image) {
  11116. return 'image';
  11117. }
  11118. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11119. return 'data';
  11120. }
  11121. return null;
  11122. }
  11123. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11124. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11125. function isSVG(url) {
  11126. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11127. }
  11128. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11129. if (isSVG(url)) {
  11130. const textDecoder = new TextDecoder();
  11131. let xmlText = textDecoder.decode(arrayBuffer);
  11132. try {
  11133. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11134. xmlText = unescape(encodeURIComponent(xmlText));
  11135. }
  11136. } catch (error) {
  11137. throw new Error(error.message);
  11138. }
  11139. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11140. return src;
  11141. }
  11142. return getBlob(arrayBuffer, url);
  11143. }
  11144. function getBlob(arrayBuffer, url) {
  11145. if (isSVG(url)) {
  11146. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11147. }
  11148. return new Blob([new Uint8Array(arrayBuffer)]);
  11149. }
  11150. async function parseToImage(arrayBuffer, options, url) {
  11151. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11152. const URL = self.URL || self.webkitURL;
  11153. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11154. try {
  11155. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11156. } finally {
  11157. if (objectUrl) {
  11158. URL.revokeObjectURL(objectUrl);
  11159. }
  11160. }
  11161. }
  11162. async function loadToImage(url, options) {
  11163. const image = new Image();
  11164. image.src = url;
  11165. if (options.image && options.image.decode && image.decode) {
  11166. await image.decode();
  11167. return image;
  11168. }
  11169. return await new Promise((resolve, reject) => {
  11170. try {
  11171. image.onload = () => resolve(image);
  11172. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11173. } catch (error) {
  11174. reject(error);
  11175. }
  11176. });
  11177. }
  11178. const EMPTY_OBJECT = {};
  11179. let imagebitmapOptionsSupported = true;
  11180. async function parseToImageBitmap(arrayBuffer, options, url) {
  11181. let blob;
  11182. if (isSVG(url)) {
  11183. const image = await parseToImage(arrayBuffer, options, url);
  11184. blob = image;
  11185. } else {
  11186. blob = getBlob(arrayBuffer, url);
  11187. }
  11188. const imagebitmapOptions = options && options.imagebitmap;
  11189. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11190. }
  11191. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11192. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11193. imagebitmapOptions = null;
  11194. }
  11195. if (imagebitmapOptions) {
  11196. try {
  11197. return await createImageBitmap(blob, imagebitmapOptions);
  11198. } catch (error) {
  11199. console.warn(error);
  11200. imagebitmapOptionsSupported = false;
  11201. }
  11202. }
  11203. return await createImageBitmap(blob);
  11204. }
  11205. function isEmptyObject(object) {
  11206. for (const key in object || EMPTY_OBJECT) {
  11207. return false;
  11208. }
  11209. return true;
  11210. }
  11211. const BIG_ENDIAN = false;
  11212. const LITTLE_ENDIAN = true;
  11213. function getBinaryImageMetadata(binaryData) {
  11214. const dataView = toDataView(binaryData);
  11215. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11216. }
  11217. function getPngMetadata(binaryData) {
  11218. const dataView = toDataView(binaryData);
  11219. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11220. if (!isPng) {
  11221. return null;
  11222. }
  11223. return {
  11224. mimeType: 'image/png',
  11225. width: dataView.getUint32(16, BIG_ENDIAN),
  11226. height: dataView.getUint32(20, BIG_ENDIAN)
  11227. };
  11228. }
  11229. function getGifMetadata(binaryData) {
  11230. const dataView = toDataView(binaryData);
  11231. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11232. if (!isGif) {
  11233. return null;
  11234. }
  11235. return {
  11236. mimeType: 'image/gif',
  11237. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11238. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11239. };
  11240. }
  11241. function getBmpMetadata(binaryData) {
  11242. const dataView = toDataView(binaryData);
  11243. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11244. if (!isBmp) {
  11245. return null;
  11246. }
  11247. return {
  11248. mimeType: 'image/bmp',
  11249. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11250. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11251. };
  11252. }
  11253. function getJpegMetadata(binaryData) {
  11254. const dataView = toDataView(binaryData);
  11255. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11256. if (!isJpeg) {
  11257. return null;
  11258. }
  11259. const {
  11260. tableMarkers,
  11261. sofMarkers
  11262. } = getJpegMarkers();
  11263. let i = 2;
  11264. while (i + 9 < dataView.byteLength) {
  11265. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11266. if (sofMarkers.has(marker)) {
  11267. return {
  11268. mimeType: 'image/jpeg',
  11269. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11270. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11271. };
  11272. }
  11273. if (!tableMarkers.has(marker)) {
  11274. return null;
  11275. }
  11276. i += 2;
  11277. i += dataView.getUint16(i, BIG_ENDIAN);
  11278. }
  11279. return null;
  11280. }
  11281. function getJpegMarkers() {
  11282. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11283. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11284. tableMarkers.add(i);
  11285. }
  11286. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11287. return {
  11288. tableMarkers,
  11289. sofMarkers
  11290. };
  11291. }
  11292. function toDataView(data) {
  11293. if (data instanceof DataView) {
  11294. return data;
  11295. }
  11296. if (ArrayBuffer.isView(data)) {
  11297. return new DataView(data.buffer);
  11298. }
  11299. if (data instanceof ArrayBuffer) {
  11300. return new DataView(data);
  11301. }
  11302. throw new Error('toDataView');
  11303. }
  11304. async function parseToNodeImage(arrayBuffer, options) {
  11305. const {
  11306. mimeType
  11307. } = getBinaryImageMetadata(arrayBuffer) || {};
  11308. const _parseImageNode = globalThis._parseImageNode;
  11309. assert$7(_parseImageNode);
  11310. return await _parseImageNode(arrayBuffer, mimeType);
  11311. }
  11312. async function parseImage(arrayBuffer, options, context) {
  11313. options = options || {};
  11314. const imageOptions = options.image || {};
  11315. const imageType = imageOptions.type || 'auto';
  11316. const {
  11317. url
  11318. } = context || {};
  11319. const loadType = getLoadableImageType(imageType);
  11320. let image;
  11321. switch (loadType) {
  11322. case 'imagebitmap':
  11323. image = await parseToImageBitmap(arrayBuffer, options, url);
  11324. break;
  11325. case 'image':
  11326. image = await parseToImage(arrayBuffer, options, url);
  11327. break;
  11328. case 'data':
  11329. image = await parseToNodeImage(arrayBuffer);
  11330. break;
  11331. default:
  11332. assert$7(false);
  11333. }
  11334. if (imageType === 'data') {
  11335. image = getImageData(image);
  11336. }
  11337. return image;
  11338. }
  11339. function getLoadableImageType(type) {
  11340. switch (type) {
  11341. case 'auto':
  11342. case 'data':
  11343. return getDefaultImageType();
  11344. default:
  11345. isImageTypeSupported(type);
  11346. return type;
  11347. }
  11348. }
  11349. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11350. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11351. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11352. image: {
  11353. type: 'auto',
  11354. decode: true
  11355. }
  11356. };
  11357. const ImageLoader = {
  11358. id: 'image',
  11359. module: 'images',
  11360. name: 'Images',
  11361. version: VERSION,
  11362. mimeTypes: MIME_TYPES,
  11363. extensions: EXTENSIONS$1,
  11364. parse: parseImage,
  11365. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11366. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11367. };
  11368. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11369. const mimeTypeSupported = {};
  11370. function _isImageFormatSupported(mimeType) {
  11371. if (mimeTypeSupported[mimeType] === undefined) {
  11372. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11373. }
  11374. return mimeTypeSupported[mimeType];
  11375. }
  11376. function checkFormatSupport(mimeType) {
  11377. switch (mimeType) {
  11378. case 'image/webp':
  11379. return checkWebPSupport();
  11380. case 'image/svg':
  11381. return isBrowser$2;
  11382. default:
  11383. if (!isBrowser$2) {
  11384. const {
  11385. _parseImageNode
  11386. } = globalThis;
  11387. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11388. }
  11389. return true;
  11390. }
  11391. }
  11392. function checkWebPSupport() {
  11393. if (!isBrowser$2) {
  11394. return false;
  11395. }
  11396. try {
  11397. const element = document.createElement('canvas');
  11398. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11399. } catch {
  11400. return false;
  11401. }
  11402. }
  11403. function assert$1(condition, message) {
  11404. if (!condition) {
  11405. throw new Error(message || 'assert failed: gltf');
  11406. }
  11407. }
  11408. function resolveUrl(url, options) {
  11409. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11410. if (absolute) {
  11411. return url;
  11412. }
  11413. const baseUrl = options.baseUri || options.uri;
  11414. if (!baseUrl) {
  11415. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11416. }
  11417. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11418. }
  11419. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11420. const bufferView = json.bufferViews[bufferViewIndex];
  11421. assert$1(bufferView);
  11422. const bufferIndex = bufferView.buffer;
  11423. const binChunk = buffers[bufferIndex];
  11424. assert$1(binChunk);
  11425. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11426. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11427. }
  11428. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11429. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11430. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11431. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11432. SCALAR: 1,
  11433. VEC2: 2,
  11434. VEC3: 3,
  11435. VEC4: 4,
  11436. MAT2: 4,
  11437. MAT3: 9,
  11438. MAT4: 16
  11439. };
  11440. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11441. 5120: 1,
  11442. 5121: 1,
  11443. 5122: 2,
  11444. 5123: 2,
  11445. 5125: 4,
  11446. 5126: 4
  11447. };
  11448. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11449. 5120: Int8Array,
  11450. 5121: Uint8Array,
  11451. 5122: Int16Array,
  11452. 5123: Uint16Array,
  11453. 5125: Uint32Array,
  11454. 5126: Float32Array
  11455. };
  11456. function getAccessorTypeFromSize(size) {
  11457. const type = TYPES[size - 1];
  11458. return type || TYPES[0];
  11459. }
  11460. function getComponentTypeFromArray(typedArray) {
  11461. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11462. if (!componentType) {
  11463. throw new Error('Illegal typed array');
  11464. }
  11465. return componentType;
  11466. }
  11467. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11468. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11469. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11470. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11471. const length = accessor.count * components;
  11472. const byteLength = accessor.count * components * bytesPerComponent;
  11473. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11474. return {
  11475. ArrayType,
  11476. length,
  11477. byteLength
  11478. };
  11479. }
  11480. const DEFAULT_GLTF_JSON = {
  11481. asset: {
  11482. version: '2.0',
  11483. generator: 'loaders.gl'
  11484. },
  11485. buffers: []
  11486. };
  11487. class GLTFScenegraph {
  11488. constructor(gltf) {
  11489. _defineProperty(this, "gltf", void 0);
  11490. _defineProperty(this, "sourceBuffers", void 0);
  11491. _defineProperty(this, "byteLength", void 0);
  11492. this.gltf = gltf || {
  11493. json: { ...DEFAULT_GLTF_JSON
  11494. },
  11495. buffers: []
  11496. };
  11497. this.sourceBuffers = [];
  11498. this.byteLength = 0;
  11499. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11500. this.byteLength = this.gltf.buffers[0].byteLength;
  11501. this.sourceBuffers = [this.gltf.buffers[0]];
  11502. }
  11503. }
  11504. get json() {
  11505. return this.gltf.json;
  11506. }
  11507. getApplicationData(key) {
  11508. const data = this.json[key];
  11509. return data;
  11510. }
  11511. getExtraData(key) {
  11512. const extras = this.json.extras || {};
  11513. return extras[key];
  11514. }
  11515. getExtension(extensionName) {
  11516. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11517. const extensions = this.json.extensions || {};
  11518. return isExtension ? extensions[extensionName] || true : null;
  11519. }
  11520. getRequiredExtension(extensionName) {
  11521. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11522. return isRequired ? this.getExtension(extensionName) : null;
  11523. }
  11524. getRequiredExtensions() {
  11525. return this.json.extensionsRequired || [];
  11526. }
  11527. getUsedExtensions() {
  11528. return this.json.extensionsUsed || [];
  11529. }
  11530. getObjectExtension(object, extensionName) {
  11531. const extensions = object.extensions || {};
  11532. return extensions[extensionName];
  11533. }
  11534. getScene(index) {
  11535. return this.getObject('scenes', index);
  11536. }
  11537. getNode(index) {
  11538. return this.getObject('nodes', index);
  11539. }
  11540. getSkin(index) {
  11541. return this.getObject('skins', index);
  11542. }
  11543. getMesh(index) {
  11544. return this.getObject('meshes', index);
  11545. }
  11546. getMaterial(index) {
  11547. return this.getObject('materials', index);
  11548. }
  11549. getAccessor(index) {
  11550. return this.getObject('accessors', index);
  11551. }
  11552. getTexture(index) {
  11553. return this.getObject('textures', index);
  11554. }
  11555. getSampler(index) {
  11556. return this.getObject('samplers', index);
  11557. }
  11558. getImage(index) {
  11559. return this.getObject('images', index);
  11560. }
  11561. getBufferView(index) {
  11562. return this.getObject('bufferViews', index);
  11563. }
  11564. getBuffer(index) {
  11565. return this.getObject('buffers', index);
  11566. }
  11567. getObject(array, index) {
  11568. if (typeof index === 'object') {
  11569. return index;
  11570. }
  11571. const object = this.json[array] && this.json[array][index];
  11572. if (!object) {
  11573. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11574. }
  11575. return object;
  11576. }
  11577. getTypedArrayForBufferView(bufferView) {
  11578. bufferView = this.getBufferView(bufferView);
  11579. const bufferIndex = bufferView.buffer;
  11580. const binChunk = this.gltf.buffers[bufferIndex];
  11581. assert$1(binChunk);
  11582. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11583. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11584. }
  11585. getTypedArrayForAccessor(accessor) {
  11586. accessor = this.getAccessor(accessor);
  11587. const bufferView = this.getBufferView(accessor.bufferView);
  11588. const buffer = this.getBuffer(bufferView.buffer);
  11589. const arrayBuffer = buffer.data;
  11590. const {
  11591. ArrayType,
  11592. length
  11593. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11594. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11595. return new ArrayType(arrayBuffer, byteOffset, length);
  11596. }
  11597. getTypedArrayForImageData(image) {
  11598. image = this.getAccessor(image);
  11599. const bufferView = this.getBufferView(image.bufferView);
  11600. const buffer = this.getBuffer(bufferView.buffer);
  11601. const arrayBuffer = buffer.data;
  11602. const byteOffset = bufferView.byteOffset || 0;
  11603. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11604. }
  11605. addApplicationData(key, data) {
  11606. this.json[key] = data;
  11607. return this;
  11608. }
  11609. addExtraData(key, data) {
  11610. this.json.extras = this.json.extras || {};
  11611. this.json.extras[key] = data;
  11612. return this;
  11613. }
  11614. addObjectExtension(object, extensionName, data) {
  11615. object.extensions = object.extensions || {};
  11616. object.extensions[extensionName] = data;
  11617. this.registerUsedExtension(extensionName);
  11618. return this;
  11619. }
  11620. setObjectExtension(object, extensionName, data) {
  11621. const extensions = object.extensions || {};
  11622. extensions[extensionName] = data;
  11623. }
  11624. removeObjectExtension(object, extensionName) {
  11625. const extensions = object.extensions || {};
  11626. const extension = extensions[extensionName];
  11627. delete extensions[extensionName];
  11628. return extension;
  11629. }
  11630. addExtension(extensionName, extensionData = {}) {
  11631. assert$1(extensionData);
  11632. this.json.extensions = this.json.extensions || {};
  11633. this.json.extensions[extensionName] = extensionData;
  11634. this.registerUsedExtension(extensionName);
  11635. return extensionData;
  11636. }
  11637. addRequiredExtension(extensionName, extensionData = {}) {
  11638. assert$1(extensionData);
  11639. this.addExtension(extensionName, extensionData);
  11640. this.registerRequiredExtension(extensionName);
  11641. return extensionData;
  11642. }
  11643. registerUsedExtension(extensionName) {
  11644. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11645. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11646. this.json.extensionsUsed.push(extensionName);
  11647. }
  11648. }
  11649. registerRequiredExtension(extensionName) {
  11650. this.registerUsedExtension(extensionName);
  11651. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11652. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11653. this.json.extensionsRequired.push(extensionName);
  11654. }
  11655. }
  11656. removeExtension(extensionName) {
  11657. if (this.json.extensionsRequired) {
  11658. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11659. }
  11660. if (this.json.extensionsUsed) {
  11661. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11662. }
  11663. if (this.json.extensions) {
  11664. delete this.json.extensions[extensionName];
  11665. }
  11666. }
  11667. setDefaultScene(sceneIndex) {
  11668. this.json.scene = sceneIndex;
  11669. }
  11670. addScene(scene) {
  11671. const {
  11672. nodeIndices
  11673. } = scene;
  11674. this.json.scenes = this.json.scenes || [];
  11675. this.json.scenes.push({
  11676. nodes: nodeIndices
  11677. });
  11678. return this.json.scenes.length - 1;
  11679. }
  11680. addNode(node) {
  11681. const {
  11682. meshIndex,
  11683. matrix
  11684. } = node;
  11685. this.json.nodes = this.json.nodes || [];
  11686. const nodeData = {
  11687. mesh: meshIndex
  11688. };
  11689. if (matrix) {
  11690. nodeData.matrix = matrix;
  11691. }
  11692. this.json.nodes.push(nodeData);
  11693. return this.json.nodes.length - 1;
  11694. }
  11695. addMesh(mesh) {
  11696. const {
  11697. attributes,
  11698. indices,
  11699. material,
  11700. mode = 4
  11701. } = mesh;
  11702. const accessors = this._addAttributes(attributes);
  11703. const glTFMesh = {
  11704. primitives: [{
  11705. attributes: accessors,
  11706. mode
  11707. }]
  11708. };
  11709. if (indices) {
  11710. const indicesAccessor = this._addIndices(indices);
  11711. glTFMesh.primitives[0].indices = indicesAccessor;
  11712. }
  11713. if (Number.isFinite(material)) {
  11714. glTFMesh.primitives[0].material = material;
  11715. }
  11716. this.json.meshes = this.json.meshes || [];
  11717. this.json.meshes.push(glTFMesh);
  11718. return this.json.meshes.length - 1;
  11719. }
  11720. addPointCloud(attributes) {
  11721. const accessorIndices = this._addAttributes(attributes);
  11722. const glTFMesh = {
  11723. primitives: [{
  11724. attributes: accessorIndices,
  11725. mode: 0
  11726. }]
  11727. };
  11728. this.json.meshes = this.json.meshes || [];
  11729. this.json.meshes.push(glTFMesh);
  11730. return this.json.meshes.length - 1;
  11731. }
  11732. addImage(imageData, mimeTypeOpt) {
  11733. const metadata = getBinaryImageMetadata(imageData);
  11734. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11735. const bufferViewIndex = this.addBufferView(imageData);
  11736. const glTFImage = {
  11737. bufferView: bufferViewIndex,
  11738. mimeType
  11739. };
  11740. this.json.images = this.json.images || [];
  11741. this.json.images.push(glTFImage);
  11742. return this.json.images.length - 1;
  11743. }
  11744. addBufferView(buffer) {
  11745. const byteLength = buffer.byteLength;
  11746. assert$1(Number.isFinite(byteLength));
  11747. this.sourceBuffers = this.sourceBuffers || [];
  11748. this.sourceBuffers.push(buffer);
  11749. const glTFBufferView = {
  11750. buffer: 0,
  11751. byteOffset: this.byteLength,
  11752. byteLength
  11753. };
  11754. this.byteLength += padToNBytes(byteLength, 4);
  11755. this.json.bufferViews = this.json.bufferViews || [];
  11756. this.json.bufferViews.push(glTFBufferView);
  11757. return this.json.bufferViews.length - 1;
  11758. }
  11759. addAccessor(bufferViewIndex, accessor) {
  11760. const glTFAccessor = {
  11761. bufferView: bufferViewIndex,
  11762. type: getAccessorTypeFromSize(accessor.size),
  11763. componentType: accessor.componentType,
  11764. count: accessor.count,
  11765. max: accessor.max,
  11766. min: accessor.min
  11767. };
  11768. this.json.accessors = this.json.accessors || [];
  11769. this.json.accessors.push(glTFAccessor);
  11770. return this.json.accessors.length - 1;
  11771. }
  11772. addBinaryBuffer(sourceBuffer, accessor = {
  11773. size: 3
  11774. }) {
  11775. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11776. let minMax = {
  11777. min: accessor.min,
  11778. max: accessor.max
  11779. };
  11780. if (!minMax.min || !minMax.max) {
  11781. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11782. }
  11783. const accessorDefaults = {
  11784. size: accessor.size,
  11785. componentType: getComponentTypeFromArray(sourceBuffer),
  11786. count: Math.round(sourceBuffer.length / accessor.size),
  11787. min: minMax.min,
  11788. max: minMax.max
  11789. };
  11790. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11791. }
  11792. addTexture(texture) {
  11793. const {
  11794. imageIndex
  11795. } = texture;
  11796. const glTFTexture = {
  11797. source: imageIndex
  11798. };
  11799. this.json.textures = this.json.textures || [];
  11800. this.json.textures.push(glTFTexture);
  11801. return this.json.textures.length - 1;
  11802. }
  11803. addMaterial(pbrMaterialInfo) {
  11804. this.json.materials = this.json.materials || [];
  11805. this.json.materials.push(pbrMaterialInfo);
  11806. return this.json.materials.length - 1;
  11807. }
  11808. createBinaryChunk() {
  11809. var _this$json, _this$json$buffers;
  11810. this.gltf.buffers = [];
  11811. const totalByteLength = this.byteLength;
  11812. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11813. const targetArray = new Uint8Array(arrayBuffer);
  11814. let dstByteOffset = 0;
  11815. for (const sourceBuffer of this.sourceBuffers || []) {
  11816. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11817. }
  11818. 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]) {
  11819. this.json.buffers[0].byteLength = totalByteLength;
  11820. } else {
  11821. this.json.buffers = [{
  11822. byteLength: totalByteLength
  11823. }];
  11824. }
  11825. this.gltf.binary = arrayBuffer;
  11826. this.sourceBuffers = [arrayBuffer];
  11827. }
  11828. _removeStringFromArray(array, string) {
  11829. let found = true;
  11830. while (found) {
  11831. const index = array.indexOf(string);
  11832. if (index > -1) {
  11833. array.splice(index, 1);
  11834. } else {
  11835. found = false;
  11836. }
  11837. }
  11838. }
  11839. _addAttributes(attributes = {}) {
  11840. const result = {};
  11841. for (const attributeKey in attributes) {
  11842. const attributeData = attributes[attributeKey];
  11843. const attrName = this._getGltfAttributeName(attributeKey);
  11844. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11845. result[attrName] = accessor;
  11846. }
  11847. return result;
  11848. }
  11849. _addIndices(indices) {
  11850. return this.addBinaryBuffer(indices, {
  11851. size: 1
  11852. });
  11853. }
  11854. _getGltfAttributeName(attributeName) {
  11855. switch (attributeName.toLowerCase()) {
  11856. case 'position':
  11857. case 'positions':
  11858. case 'vertices':
  11859. return 'POSITION';
  11860. case 'normal':
  11861. case 'normals':
  11862. return 'NORMAL';
  11863. case 'color':
  11864. case 'colors':
  11865. return 'COLOR_0';
  11866. case 'texcoord':
  11867. case 'texcoords':
  11868. return 'TEXCOORD_0';
  11869. default:
  11870. return attributeName;
  11871. }
  11872. }
  11873. _getAccessorMinMax(buffer, size) {
  11874. const result = {
  11875. min: null,
  11876. max: null
  11877. };
  11878. if (buffer.length < size) {
  11879. return result;
  11880. }
  11881. result.min = [];
  11882. result.max = [];
  11883. const initValues = buffer.subarray(0, size);
  11884. for (const value of initValues) {
  11885. result.min.push(value);
  11886. result.max.push(value);
  11887. }
  11888. for (let index = size; index < buffer.length; index += size) {
  11889. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  11890. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  11891. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  11892. }
  11893. }
  11894. return result;
  11895. }
  11896. }
  11897. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  11898. 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';
  11899. 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';
  11900. 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]);
  11901. 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]);
  11902. const FILTERS = {
  11903. 0: '',
  11904. 1: 'meshopt_decodeFilterOct',
  11905. 2: 'meshopt_decodeFilterQuat',
  11906. 3: 'meshopt_decodeFilterExp',
  11907. NONE: '',
  11908. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  11909. QUATERNION: 'meshopt_decodeFilterQuat',
  11910. EXPONENTIAL: 'meshopt_decodeFilterExp'
  11911. };
  11912. const DECODERS = {
  11913. 0: 'meshopt_decodeVertexBuffer',
  11914. 1: 'meshopt_decodeIndexBuffer',
  11915. 2: 'meshopt_decodeIndexSequence',
  11916. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  11917. TRIANGLES: 'meshopt_decodeIndexBuffer',
  11918. INDICES: 'meshopt_decodeIndexSequence'
  11919. };
  11920. function isMeshoptSupported() {
  11921. return isWebAssemblySupported;
  11922. }
  11923. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  11924. const instance = await loadWasmInstance();
  11925. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  11926. }
  11927. let wasmPromise;
  11928. async function loadWasmInstance() {
  11929. if (!wasmPromise) {
  11930. wasmPromise = loadWasmModule();
  11931. }
  11932. return wasmPromise;
  11933. }
  11934. async function loadWasmModule() {
  11935. let wasm = wasm_base;
  11936. if (WebAssembly.validate(detector)) {
  11937. wasm = wasm_simd;
  11938. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  11939. }
  11940. const result = await WebAssembly.instantiate(unpack(wasm), {});
  11941. await result.instance.exports.__wasm_call_ctors();
  11942. return result.instance;
  11943. }
  11944. function unpack(data) {
  11945. const result = new Uint8Array(data.length);
  11946. for (let i = 0; i < data.length; ++i) {
  11947. const ch = data.charCodeAt(i);
  11948. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  11949. }
  11950. let write = 0;
  11951. for (let i = 0; i < data.length; ++i) {
  11952. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  11953. }
  11954. return result.buffer.slice(0, write);
  11955. }
  11956. function decode$5(instance, fun, target, count, size, source, filter) {
  11957. const sbrk = instance.exports.sbrk;
  11958. const count4 = count + 3 & ~3;
  11959. const tp = sbrk(count4 * size);
  11960. const sp = sbrk(source.length);
  11961. const heap = new Uint8Array(instance.exports.memory.buffer);
  11962. heap.set(source, sp);
  11963. const res = fun(tp, count, size, sp, source.length);
  11964. if (res === 0 && filter) {
  11965. filter(tp, count4, size);
  11966. }
  11967. target.set(heap.subarray(tp, tp + count * size));
  11968. sbrk(tp - sbrk(0));
  11969. if (res !== 0) {
  11970. throw new Error("Malformed buffer data: ".concat(res));
  11971. }
  11972. }
  11973. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  11974. const name$6 = EXT_MESHOPT_COMPRESSION;
  11975. function preprocess$4(gltfData) {
  11976. const scenegraph = new GLTFScenegraph(gltfData);
  11977. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  11978. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  11979. }
  11980. }
  11981. async function decode$4(gltfData, options) {
  11982. var _options$gltf;
  11983. const scenegraph = new GLTFScenegraph(gltfData);
  11984. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  11985. return;
  11986. }
  11987. const promises = [];
  11988. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  11989. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  11990. }
  11991. await Promise.all(promises);
  11992. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  11993. }
  11994. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  11995. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  11996. if (meshoptExtension) {
  11997. const buffer = bufferView.buffer;
  11998. const {
  11999. byteOffset = 0,
  12000. byteLength = 0,
  12001. byteStride,
  12002. count,
  12003. mode,
  12004. filter = 'NONE'
  12005. } = meshoptExtension;
  12006. const source = new Uint8Array(buffer, byteOffset, byteLength);
  12007. const result = new ArrayBuffer(count * byteStride);
  12008. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  12009. return result;
  12010. }
  12011. return null;
  12012. }
  12013. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12014. __proto__: null,
  12015. name: name$6,
  12016. preprocess: preprocess$4,
  12017. decode: decode$4
  12018. });
  12019. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12020. const name$5 = EXT_TEXTURE_WEBP;
  12021. function preprocess$3(gltfData, options) {
  12022. const scenegraph = new GLTFScenegraph(gltfData);
  12023. if (!_isImageFormatSupported('image/webp')) {
  12024. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12025. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12026. }
  12027. return;
  12028. }
  12029. const {
  12030. json
  12031. } = scenegraph;
  12032. for (const texture of json.textures || []) {
  12033. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12034. if (extension) {
  12035. texture.source = extension.source;
  12036. }
  12037. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12038. }
  12039. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12040. }
  12041. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12042. __proto__: null,
  12043. name: name$5,
  12044. preprocess: preprocess$3
  12045. });
  12046. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12047. const name$4 = KHR_TEXTURE_BASISU;
  12048. function preprocess$2(gltfData, options) {
  12049. const scene = new GLTFScenegraph(gltfData);
  12050. const {
  12051. json
  12052. } = scene;
  12053. for (const texture of json.textures || []) {
  12054. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12055. if (extension) {
  12056. texture.source = extension.source;
  12057. }
  12058. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12059. }
  12060. scene.removeExtension(KHR_TEXTURE_BASISU);
  12061. }
  12062. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12063. __proto__: null,
  12064. name: name$4,
  12065. preprocess: preprocess$2
  12066. });
  12067. function getGLTFAccessors(attributes) {
  12068. const accessors = {};
  12069. for (const name in attributes) {
  12070. const attribute = attributes[name];
  12071. if (name !== 'indices') {
  12072. const glTFAccessor = getGLTFAccessor(attribute);
  12073. accessors[name] = glTFAccessor;
  12074. }
  12075. }
  12076. return accessors;
  12077. }
  12078. function getGLTFAccessor(attribute) {
  12079. const {
  12080. buffer,
  12081. size,
  12082. count
  12083. } = getAccessorData(attribute);
  12084. const glTFAccessor = {
  12085. value: buffer,
  12086. size,
  12087. byteOffset: 0,
  12088. count,
  12089. type: getAccessorTypeFromSize(size),
  12090. componentType: getComponentTypeFromArray(buffer)
  12091. };
  12092. return glTFAccessor;
  12093. }
  12094. function getAccessorData(attribute) {
  12095. let buffer = attribute;
  12096. let size = 1;
  12097. let count = 0;
  12098. if (attribute && attribute.value) {
  12099. buffer = attribute.value;
  12100. size = attribute.size || 1;
  12101. }
  12102. if (buffer) {
  12103. if (!ArrayBuffer.isView(buffer)) {
  12104. buffer = toTypedArray(buffer, Float32Array);
  12105. }
  12106. count = buffer.length / size;
  12107. }
  12108. return {
  12109. buffer,
  12110. size,
  12111. count
  12112. };
  12113. }
  12114. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12115. if (!array) {
  12116. return null;
  12117. }
  12118. if (Array.isArray(array)) {
  12119. return new ArrayType(array);
  12120. }
  12121. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12122. return new ArrayType(array);
  12123. }
  12124. return array;
  12125. }
  12126. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12127. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12128. function preprocess$1(gltfData, options, context) {
  12129. const scenegraph = new GLTFScenegraph(gltfData);
  12130. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12131. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12132. }
  12133. }
  12134. async function decode$3(gltfData, options, context) {
  12135. var _options$gltf;
  12136. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12137. return;
  12138. }
  12139. const scenegraph = new GLTFScenegraph(gltfData);
  12140. const promises = [];
  12141. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12142. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12143. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12144. }
  12145. }
  12146. await Promise.all(promises);
  12147. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12148. }
  12149. function encode$3(gltfData, options = {}) {
  12150. const scenegraph = new GLTFScenegraph(gltfData);
  12151. for (const mesh of scenegraph.json.meshes || []) {
  12152. compressMesh(mesh);
  12153. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12154. }
  12155. }
  12156. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12157. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12158. if (!dracoExtension) {
  12159. return;
  12160. }
  12161. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12162. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12163. const {
  12164. parse
  12165. } = context;
  12166. const dracoOptions = { ...options
  12167. };
  12168. delete dracoOptions['3d-tiles'];
  12169. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12170. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12171. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12172. if (attributeName in primitive.attributes) {
  12173. const accessorIndex = primitive.attributes[attributeName];
  12174. const accessor = scenegraph.getAccessor(accessorIndex);
  12175. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12176. decodedAttribute.min = accessor.min;
  12177. decodedAttribute.max = accessor.max;
  12178. }
  12179. }
  12180. }
  12181. primitive.attributes = decodedAttributes;
  12182. if (decodedData.indices) {
  12183. primitive.indices = getGLTFAccessor(decodedData.indices);
  12184. }
  12185. checkPrimitive(primitive);
  12186. }
  12187. function compressMesh(attributes, indices, mode = 4, options, context) {
  12188. var _context$parseSync;
  12189. if (!options.DracoWriter) {
  12190. throw new Error('options.gltf.DracoWriter not provided');
  12191. }
  12192. const compressedData = options.DracoWriter.encodeSync({
  12193. attributes
  12194. });
  12195. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12196. attributes
  12197. });
  12198. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12199. const bufferViewIndex = options.addBufferView(compressedData);
  12200. const glTFMesh = {
  12201. primitives: [{
  12202. attributes: fauxAccessors,
  12203. mode,
  12204. extensions: {
  12205. [KHR_DRACO_MESH_COMPRESSION]: {
  12206. bufferView: bufferViewIndex,
  12207. attributes: fauxAccessors
  12208. }
  12209. }
  12210. }]
  12211. };
  12212. return glTFMesh;
  12213. }
  12214. function checkPrimitive(primitive) {
  12215. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12216. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12217. }
  12218. }
  12219. function* makeMeshPrimitiveIterator(scenegraph) {
  12220. for (const mesh of scenegraph.json.meshes || []) {
  12221. for (const primitive of mesh.primitives) {
  12222. yield primitive;
  12223. }
  12224. }
  12225. }
  12226. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12227. __proto__: null,
  12228. name: name$3,
  12229. preprocess: preprocess$1,
  12230. decode: decode$3,
  12231. encode: encode$3
  12232. });
  12233. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12234. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12235. async function decode$2(gltfData) {
  12236. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12237. const {
  12238. json
  12239. } = gltfScenegraph;
  12240. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12241. if (extension) {
  12242. gltfScenegraph.json.lights = extension.lights;
  12243. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12244. }
  12245. for (const node of json.nodes || []) {
  12246. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12247. if (nodeExtension) {
  12248. node.light = nodeExtension.light;
  12249. }
  12250. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12251. }
  12252. }
  12253. async function encode$2(gltfData) {
  12254. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12255. const {
  12256. json
  12257. } = gltfScenegraph;
  12258. if (json.lights) {
  12259. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12260. assert$1(!extension.lights);
  12261. extension.lights = json.lights;
  12262. delete json.lights;
  12263. }
  12264. if (gltfScenegraph.json.lights) {
  12265. for (const light of gltfScenegraph.json.lights) {
  12266. const node = light.node;
  12267. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12268. }
  12269. delete gltfScenegraph.json.lights;
  12270. }
  12271. }
  12272. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12273. __proto__: null,
  12274. name: name$2,
  12275. decode: decode$2,
  12276. encode: encode$2
  12277. });
  12278. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12279. const name$1 = KHR_MATERIALS_UNLIT;
  12280. async function decode$1(gltfData) {
  12281. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12282. const {
  12283. json
  12284. } = gltfScenegraph;
  12285. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12286. for (const material of json.materials || []) {
  12287. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12288. if (extension) {
  12289. material.unlit = true;
  12290. }
  12291. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12292. }
  12293. }
  12294. function encode$1(gltfData) {
  12295. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12296. const {
  12297. json
  12298. } = gltfScenegraph;
  12299. if (gltfScenegraph.materials) {
  12300. for (const material of json.materials || []) {
  12301. if (material.unlit) {
  12302. delete material.unlit;
  12303. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12304. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12305. }
  12306. }
  12307. }
  12308. }
  12309. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12310. __proto__: null,
  12311. name: name$1,
  12312. decode: decode$1,
  12313. encode: encode$1
  12314. });
  12315. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12316. const name = KHR_TECHNIQUES_WEBGL;
  12317. async function decode(gltfData) {
  12318. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12319. const {
  12320. json
  12321. } = gltfScenegraph;
  12322. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12323. if (extension) {
  12324. const techniques = resolveTechniques(extension, gltfScenegraph);
  12325. for (const material of json.materials || []) {
  12326. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12327. if (materialExtension) {
  12328. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12329. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12330. }
  12331. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12332. }
  12333. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12334. }
  12335. }
  12336. async function encode(gltfData, options) {}
  12337. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12338. const {
  12339. programs = [],
  12340. shaders = [],
  12341. techniques = []
  12342. } = techniquesExtension;
  12343. const textDecoder = new TextDecoder();
  12344. shaders.forEach(shader => {
  12345. if (Number.isFinite(shader.bufferView)) {
  12346. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12347. } else {
  12348. throw new Error('KHR_techniques_webgl: no shader code');
  12349. }
  12350. });
  12351. programs.forEach(program => {
  12352. program.fragmentShader = shaders[program.fragmentShader];
  12353. program.vertexShader = shaders[program.vertexShader];
  12354. });
  12355. techniques.forEach(technique => {
  12356. technique.program = programs[technique.program];
  12357. });
  12358. return techniques;
  12359. }
  12360. function resolveValues(technique, gltfScenegraph) {
  12361. const values = Object.assign({}, technique.values);
  12362. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12363. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12364. values[uniform] = technique.uniforms[uniform].value;
  12365. }
  12366. });
  12367. Object.keys(values).forEach(uniform => {
  12368. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12369. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12370. }
  12371. });
  12372. return values;
  12373. }
  12374. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12375. __proto__: null,
  12376. name: name,
  12377. decode: decode,
  12378. encode: encode
  12379. });
  12380. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12381. function preprocessExtensions(gltf, options = {}, context) {
  12382. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12383. for (const extension of extensions) {
  12384. var _extension$preprocess;
  12385. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12386. }
  12387. }
  12388. async function decodeExtensions(gltf, options = {}, context) {
  12389. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12390. for (const extension of extensions) {
  12391. var _extension$decode;
  12392. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12393. }
  12394. }
  12395. function useExtension(extensionName, options) {
  12396. var _options$gltf;
  12397. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12398. const exclude = extensionName in excludes && !excludes[extensionName];
  12399. return !exclude;
  12400. }
  12401. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12402. function preprocess(gltfData) {
  12403. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12404. const {
  12405. json
  12406. } = gltfScenegraph;
  12407. for (const image of json.images || []) {
  12408. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12409. if (extension) {
  12410. Object.assign(image, extension);
  12411. }
  12412. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12413. }
  12414. if (json.buffers && json.buffers[0]) {
  12415. delete json.buffers[0].uri;
  12416. }
  12417. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12418. }
  12419. const GLTF_ARRAYS = {
  12420. accessors: 'accessor',
  12421. animations: 'animation',
  12422. buffers: 'buffer',
  12423. bufferViews: 'bufferView',
  12424. images: 'image',
  12425. materials: 'material',
  12426. meshes: 'mesh',
  12427. nodes: 'node',
  12428. samplers: 'sampler',
  12429. scenes: 'scene',
  12430. skins: 'skin',
  12431. textures: 'texture'
  12432. };
  12433. const GLTF_KEYS = {
  12434. accessor: 'accessors',
  12435. animations: 'animation',
  12436. buffer: 'buffers',
  12437. bufferView: 'bufferViews',
  12438. image: 'images',
  12439. material: 'materials',
  12440. mesh: 'meshes',
  12441. node: 'nodes',
  12442. sampler: 'samplers',
  12443. scene: 'scenes',
  12444. skin: 'skins',
  12445. texture: 'textures'
  12446. };
  12447. class GLTFV1Normalizer {
  12448. constructor() {
  12449. _defineProperty(this, "idToIndexMap", {
  12450. animations: {},
  12451. accessors: {},
  12452. buffers: {},
  12453. bufferViews: {},
  12454. images: {},
  12455. materials: {},
  12456. meshes: {},
  12457. nodes: {},
  12458. samplers: {},
  12459. scenes: {},
  12460. skins: {},
  12461. textures: {}
  12462. });
  12463. _defineProperty(this, "json", void 0);
  12464. }
  12465. normalize(gltf, options) {
  12466. this.json = gltf.json;
  12467. const json = gltf.json;
  12468. switch (json.asset && json.asset.version) {
  12469. case '2.0':
  12470. return;
  12471. case undefined:
  12472. case '1.0':
  12473. break;
  12474. default:
  12475. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12476. return;
  12477. }
  12478. if (!options.normalize) {
  12479. throw new Error('glTF v1 is not supported.');
  12480. }
  12481. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12482. this._addAsset(json);
  12483. this._convertTopLevelObjectsToArrays(json);
  12484. preprocess(gltf);
  12485. this._convertObjectIdsToArrayIndices(json);
  12486. this._updateObjects(json);
  12487. this._updateMaterial(json);
  12488. }
  12489. _addAsset(json) {
  12490. json.asset = json.asset || {};
  12491. json.asset.version = '2.0';
  12492. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12493. }
  12494. _convertTopLevelObjectsToArrays(json) {
  12495. for (const arrayName in GLTF_ARRAYS) {
  12496. this._convertTopLevelObjectToArray(json, arrayName);
  12497. }
  12498. }
  12499. _convertTopLevelObjectToArray(json, mapName) {
  12500. const objectMap = json[mapName];
  12501. if (!objectMap || Array.isArray(objectMap)) {
  12502. return;
  12503. }
  12504. json[mapName] = [];
  12505. for (const id in objectMap) {
  12506. const object = objectMap[id];
  12507. object.id = object.id || id;
  12508. const index = json[mapName].length;
  12509. json[mapName].push(object);
  12510. this.idToIndexMap[mapName][id] = index;
  12511. }
  12512. }
  12513. _convertObjectIdsToArrayIndices(json) {
  12514. for (const arrayName in GLTF_ARRAYS) {
  12515. this._convertIdsToIndices(json, arrayName);
  12516. }
  12517. if ('scene' in json) {
  12518. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12519. }
  12520. for (const texture of json.textures) {
  12521. this._convertTextureIds(texture);
  12522. }
  12523. for (const mesh of json.meshes) {
  12524. this._convertMeshIds(mesh);
  12525. }
  12526. for (const node of json.nodes) {
  12527. this._convertNodeIds(node);
  12528. }
  12529. for (const node of json.scenes) {
  12530. this._convertSceneIds(node);
  12531. }
  12532. }
  12533. _convertTextureIds(texture) {
  12534. if (texture.source) {
  12535. texture.source = this._convertIdToIndex(texture.source, 'image');
  12536. }
  12537. }
  12538. _convertMeshIds(mesh) {
  12539. for (const primitive of mesh.primitives) {
  12540. const {
  12541. attributes,
  12542. indices,
  12543. material
  12544. } = primitive;
  12545. for (const attributeName in attributes) {
  12546. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12547. }
  12548. if (indices) {
  12549. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12550. }
  12551. if (material) {
  12552. primitive.material = this._convertIdToIndex(material, 'material');
  12553. }
  12554. }
  12555. }
  12556. _convertNodeIds(node) {
  12557. if (node.children) {
  12558. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12559. }
  12560. if (node.meshes) {
  12561. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12562. }
  12563. }
  12564. _convertSceneIds(scene) {
  12565. if (scene.nodes) {
  12566. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12567. }
  12568. }
  12569. _convertIdsToIndices(json, topLevelArrayName) {
  12570. if (!json[topLevelArrayName]) {
  12571. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12572. json[topLevelArrayName] = [];
  12573. }
  12574. for (const object of json[topLevelArrayName]) {
  12575. for (const key in object) {
  12576. const id = object[key];
  12577. const index = this._convertIdToIndex(id, key);
  12578. object[key] = index;
  12579. }
  12580. }
  12581. }
  12582. _convertIdToIndex(id, key) {
  12583. const arrayName = GLTF_KEYS[key];
  12584. if (arrayName in this.idToIndexMap) {
  12585. const index = this.idToIndexMap[arrayName][id];
  12586. if (!Number.isFinite(index)) {
  12587. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12588. }
  12589. return index;
  12590. }
  12591. return id;
  12592. }
  12593. _updateObjects(json) {
  12594. for (const buffer of this.json.buffers) {
  12595. delete buffer.type;
  12596. }
  12597. }
  12598. _updateMaterial(json) {
  12599. for (const material of json.materials) {
  12600. material.pbrMetallicRoughness = {
  12601. baseColorFactor: [1, 1, 1, 1],
  12602. metallicFactor: 1,
  12603. roughnessFactor: 1
  12604. };
  12605. const textureId = material.values && material.values.tex;
  12606. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12607. if (textureIndex !== -1) {
  12608. material.pbrMetallicRoughness.baseColorTexture = {
  12609. index: textureIndex
  12610. };
  12611. }
  12612. }
  12613. }
  12614. }
  12615. function normalizeGLTFV1(gltf, options = {}) {
  12616. return new GLTFV1Normalizer().normalize(gltf, options);
  12617. }
  12618. const COMPONENTS = {
  12619. SCALAR: 1,
  12620. VEC2: 2,
  12621. VEC3: 3,
  12622. VEC4: 4,
  12623. MAT2: 4,
  12624. MAT3: 9,
  12625. MAT4: 16
  12626. };
  12627. const BYTES = {
  12628. 5120: 1,
  12629. 5121: 1,
  12630. 5122: 2,
  12631. 5123: 2,
  12632. 5125: 4,
  12633. 5126: 4
  12634. };
  12635. const GL_SAMPLER = {
  12636. TEXTURE_MAG_FILTER: 0x2800,
  12637. TEXTURE_MIN_FILTER: 0x2801,
  12638. TEXTURE_WRAP_S: 0x2802,
  12639. TEXTURE_WRAP_T: 0x2803,
  12640. REPEAT: 0x2901,
  12641. LINEAR: 0x2601,
  12642. NEAREST_MIPMAP_LINEAR: 0x2702
  12643. };
  12644. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12645. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12646. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12647. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12648. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12649. };
  12650. const DEFAULT_SAMPLER = {
  12651. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12652. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12653. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12654. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12655. };
  12656. function getBytesFromComponentType(componentType) {
  12657. return BYTES[componentType];
  12658. }
  12659. function getSizeFromAccessorType(type) {
  12660. return COMPONENTS[type];
  12661. }
  12662. class GLTFPostProcessor {
  12663. constructor() {
  12664. _defineProperty(this, "baseUri", '');
  12665. _defineProperty(this, "json", {});
  12666. _defineProperty(this, "buffers", []);
  12667. _defineProperty(this, "images", []);
  12668. }
  12669. postProcess(gltf, options = {}) {
  12670. const {
  12671. json,
  12672. buffers = [],
  12673. images = [],
  12674. baseUri = ''
  12675. } = gltf;
  12676. assert$1(json);
  12677. this.baseUri = baseUri;
  12678. this.json = json;
  12679. this.buffers = buffers;
  12680. this.images = images;
  12681. this._resolveTree(this.json, options);
  12682. return this.json;
  12683. }
  12684. _resolveTree(json, options = {}) {
  12685. if (json.bufferViews) {
  12686. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12687. }
  12688. if (json.images) {
  12689. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12690. }
  12691. if (json.samplers) {
  12692. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12693. }
  12694. if (json.textures) {
  12695. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12696. }
  12697. if (json.accessors) {
  12698. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12699. }
  12700. if (json.materials) {
  12701. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12702. }
  12703. if (json.meshes) {
  12704. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12705. }
  12706. if (json.nodes) {
  12707. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12708. }
  12709. if (json.skins) {
  12710. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12711. }
  12712. if (json.scenes) {
  12713. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12714. }
  12715. if (json.scene !== undefined) {
  12716. json.scene = json.scenes[this.json.scene];
  12717. }
  12718. }
  12719. getScene(index) {
  12720. return this._get('scenes', index);
  12721. }
  12722. getNode(index) {
  12723. return this._get('nodes', index);
  12724. }
  12725. getSkin(index) {
  12726. return this._get('skins', index);
  12727. }
  12728. getMesh(index) {
  12729. return this._get('meshes', index);
  12730. }
  12731. getMaterial(index) {
  12732. return this._get('materials', index);
  12733. }
  12734. getAccessor(index) {
  12735. return this._get('accessors', index);
  12736. }
  12737. getCamera(index) {
  12738. return null;
  12739. }
  12740. getTexture(index) {
  12741. return this._get('textures', index);
  12742. }
  12743. getSampler(index) {
  12744. return this._get('samplers', index);
  12745. }
  12746. getImage(index) {
  12747. return this._get('images', index);
  12748. }
  12749. getBufferView(index) {
  12750. return this._get('bufferViews', index);
  12751. }
  12752. getBuffer(index) {
  12753. return this._get('buffers', index);
  12754. }
  12755. _get(array, index) {
  12756. if (typeof index === 'object') {
  12757. return index;
  12758. }
  12759. const object = this.json[array] && this.json[array][index];
  12760. if (!object) {
  12761. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12762. }
  12763. return object;
  12764. }
  12765. _resolveScene(scene, index) {
  12766. scene.id = scene.id || "scene-".concat(index);
  12767. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12768. return scene;
  12769. }
  12770. _resolveNode(node, index) {
  12771. node.id = node.id || "node-".concat(index);
  12772. if (node.children) {
  12773. node.children = node.children.map(child => this.getNode(child));
  12774. }
  12775. if (node.mesh !== undefined) {
  12776. node.mesh = this.getMesh(node.mesh);
  12777. } else if (node.meshes !== undefined && node.meshes.length) {
  12778. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12779. const mesh = this.getMesh(meshIndex);
  12780. accum.id = mesh.id;
  12781. accum.primitives = accum.primitives.concat(mesh.primitives);
  12782. return accum;
  12783. }, {
  12784. primitives: []
  12785. });
  12786. }
  12787. if (node.camera !== undefined) {
  12788. node.camera = this.getCamera(node.camera);
  12789. }
  12790. if (node.skin !== undefined) {
  12791. node.skin = this.getSkin(node.skin);
  12792. }
  12793. return node;
  12794. }
  12795. _resolveSkin(skin, index) {
  12796. skin.id = skin.id || "skin-".concat(index);
  12797. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12798. return skin;
  12799. }
  12800. _resolveMesh(mesh, index) {
  12801. mesh.id = mesh.id || "mesh-".concat(index);
  12802. if (mesh.primitives) {
  12803. mesh.primitives = mesh.primitives.map(primitive => {
  12804. primitive = { ...primitive
  12805. };
  12806. const attributes = primitive.attributes;
  12807. primitive.attributes = {};
  12808. for (const attribute in attributes) {
  12809. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12810. }
  12811. if (primitive.indices !== undefined) {
  12812. primitive.indices = this.getAccessor(primitive.indices);
  12813. }
  12814. if (primitive.material !== undefined) {
  12815. primitive.material = this.getMaterial(primitive.material);
  12816. }
  12817. return primitive;
  12818. });
  12819. }
  12820. return mesh;
  12821. }
  12822. _resolveMaterial(material, index) {
  12823. material.id = material.id || "material-".concat(index);
  12824. if (material.normalTexture) {
  12825. material.normalTexture = { ...material.normalTexture
  12826. };
  12827. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12828. }
  12829. if (material.occlusionTexture) {
  12830. material.occlustionTexture = { ...material.occlustionTexture
  12831. };
  12832. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12833. }
  12834. if (material.emissiveTexture) {
  12835. material.emmisiveTexture = { ...material.emmisiveTexture
  12836. };
  12837. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12838. }
  12839. if (!material.emissiveFactor) {
  12840. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12841. }
  12842. if (material.pbrMetallicRoughness) {
  12843. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12844. };
  12845. const mr = material.pbrMetallicRoughness;
  12846. if (mr.baseColorTexture) {
  12847. mr.baseColorTexture = { ...mr.baseColorTexture
  12848. };
  12849. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12850. }
  12851. if (mr.metallicRoughnessTexture) {
  12852. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12853. };
  12854. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12855. }
  12856. }
  12857. return material;
  12858. }
  12859. _resolveAccessor(accessor, index) {
  12860. accessor.id = accessor.id || "accessor-".concat(index);
  12861. if (accessor.bufferView !== undefined) {
  12862. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12863. }
  12864. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12865. accessor.components = getSizeFromAccessorType(accessor.type);
  12866. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12867. if (accessor.bufferView) {
  12868. const buffer = accessor.bufferView.buffer;
  12869. const {
  12870. ArrayType,
  12871. byteLength
  12872. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12873. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12874. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12875. if (accessor.bufferView.byteStride) {
  12876. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12877. }
  12878. accessor.value = new ArrayType(cutBuffer);
  12879. }
  12880. return accessor;
  12881. }
  12882. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12883. const result = new Uint8Array(count * bytesPerElement);
  12884. for (let i = 0; i < count; i++) {
  12885. const elementOffset = byteOffset + i * byteStride;
  12886. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12887. }
  12888. return result.buffer;
  12889. }
  12890. _resolveTexture(texture, index) {
  12891. texture.id = texture.id || "texture-".concat(index);
  12892. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  12893. texture.source = this.getImage(texture.source);
  12894. return texture;
  12895. }
  12896. _resolveSampler(sampler, index) {
  12897. sampler.id = sampler.id || "sampler-".concat(index);
  12898. sampler.parameters = {};
  12899. for (const key in sampler) {
  12900. const glEnum = this._enumSamplerParameter(key);
  12901. if (glEnum !== undefined) {
  12902. sampler.parameters[glEnum] = sampler[key];
  12903. }
  12904. }
  12905. return sampler;
  12906. }
  12907. _enumSamplerParameter(key) {
  12908. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  12909. }
  12910. _resolveImage(image, index) {
  12911. image.id = image.id || "image-".concat(index);
  12912. if (image.bufferView !== undefined) {
  12913. image.bufferView = this.getBufferView(image.bufferView);
  12914. }
  12915. const preloadedImage = this.images[index];
  12916. if (preloadedImage) {
  12917. image.image = preloadedImage;
  12918. }
  12919. return image;
  12920. }
  12921. _resolveBufferView(bufferView, index) {
  12922. const bufferIndex = bufferView.buffer;
  12923. const result = {
  12924. id: "bufferView-".concat(index),
  12925. ...bufferView,
  12926. buffer: this.buffers[bufferIndex]
  12927. };
  12928. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  12929. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  12930. if ('byteOffset' in bufferView) {
  12931. byteOffset += bufferView.byteOffset;
  12932. }
  12933. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  12934. return result;
  12935. }
  12936. _resolveCamera(camera, index) {
  12937. camera.id = camera.id || "camera-".concat(index);
  12938. if (camera.perspective) ;
  12939. if (camera.orthographic) ;
  12940. return camera;
  12941. }
  12942. }
  12943. function postProcessGLTF(gltf, options) {
  12944. return new GLTFPostProcessor().postProcess(gltf, options);
  12945. }
  12946. const MAGIC_glTF = 0x676c5446;
  12947. const GLB_FILE_HEADER_SIZE = 12;
  12948. const GLB_CHUNK_HEADER_SIZE = 8;
  12949. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  12950. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  12951. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  12952. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  12953. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  12954. const LE = true;
  12955. function getMagicString(dataView, byteOffset = 0) {
  12956. 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)));
  12957. }
  12958. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  12959. const dataView = new DataView(arrayBuffer);
  12960. const {
  12961. magic = MAGIC_glTF
  12962. } = options;
  12963. const magic1 = dataView.getUint32(byteOffset, false);
  12964. return magic1 === magic || magic1 === MAGIC_glTF;
  12965. }
  12966. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  12967. const dataView = new DataView(arrayBuffer);
  12968. const type = getMagicString(dataView, byteOffset + 0);
  12969. const version = dataView.getUint32(byteOffset + 4, LE);
  12970. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  12971. Object.assign(glb, {
  12972. header: {
  12973. byteOffset,
  12974. byteLength,
  12975. hasBinChunk: false
  12976. },
  12977. type,
  12978. version,
  12979. json: {},
  12980. binChunks: []
  12981. });
  12982. byteOffset += GLB_FILE_HEADER_SIZE;
  12983. switch (glb.version) {
  12984. case 1:
  12985. return parseGLBV1(glb, dataView, byteOffset);
  12986. case 2:
  12987. return parseGLBV2(glb, dataView, byteOffset, options = {});
  12988. default:
  12989. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  12990. }
  12991. }
  12992. function parseGLBV1(glb, dataView, byteOffset) {
  12993. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  12994. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  12995. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  12996. byteOffset += GLB_CHUNK_HEADER_SIZE;
  12997. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  12998. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  12999. byteOffset += contentLength;
  13000. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13001. return byteOffset;
  13002. }
  13003. function parseGLBV2(glb, dataView, byteOffset, options) {
  13004. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13005. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13006. return byteOffset + glb.header.byteLength;
  13007. }
  13008. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13009. while (byteOffset + 8 <= glb.header.byteLength) {
  13010. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13011. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13012. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13013. switch (chunkFormat) {
  13014. case GLB_CHUNK_TYPE_JSON:
  13015. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13016. break;
  13017. case GLB_CHUNK_TYPE_BIN:
  13018. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13019. break;
  13020. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13021. if (!options.strict) {
  13022. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13023. }
  13024. break;
  13025. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13026. if (!options.strict) {
  13027. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13028. }
  13029. break;
  13030. }
  13031. byteOffset += padToNBytes(chunkLength, 4);
  13032. }
  13033. return byteOffset;
  13034. }
  13035. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13036. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13037. const textDecoder = new TextDecoder('utf8');
  13038. const jsonText = textDecoder.decode(jsonChunk);
  13039. glb.json = JSON.parse(jsonText);
  13040. return padToNBytes(chunkLength, 4);
  13041. }
  13042. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13043. glb.header.hasBinChunk = true;
  13044. glb.binChunks.push({
  13045. byteOffset,
  13046. byteLength: chunkLength,
  13047. arrayBuffer: dataView.buffer
  13048. });
  13049. return padToNBytes(chunkLength, 4);
  13050. }
  13051. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13052. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13053. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13054. normalizeGLTFV1(gltf, {
  13055. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13056. });
  13057. preprocessExtensions(gltf, options, context);
  13058. const promises = [];
  13059. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13060. await loadBuffers(gltf, options, context);
  13061. }
  13062. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13063. const promise = loadImages(gltf, options, context);
  13064. promises.push(promise);
  13065. }
  13066. const promise = decodeExtensions(gltf, options, context);
  13067. promises.push(promise);
  13068. await Promise.all(promises);
  13069. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13070. }
  13071. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13072. if (options.uri) {
  13073. gltf.baseUri = options.uri;
  13074. }
  13075. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13076. const textDecoder = new TextDecoder();
  13077. data = textDecoder.decode(data);
  13078. }
  13079. if (typeof data === 'string') {
  13080. gltf.json = parseJSON(data);
  13081. } else if (data instanceof ArrayBuffer) {
  13082. const glb = {};
  13083. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13084. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13085. gltf._glb = glb;
  13086. gltf.json = glb.json;
  13087. } else {
  13088. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13089. }
  13090. const buffers = gltf.json.buffers || [];
  13091. gltf.buffers = new Array(buffers.length).fill(null);
  13092. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13093. const {
  13094. binChunks
  13095. } = gltf._glb;
  13096. gltf.buffers[0] = {
  13097. arrayBuffer: binChunks[0].arrayBuffer,
  13098. byteOffset: binChunks[0].byteOffset,
  13099. byteLength: binChunks[0].byteLength
  13100. };
  13101. }
  13102. const images = gltf.json.images || [];
  13103. gltf.images = new Array(images.length).fill({});
  13104. }
  13105. async function loadBuffers(gltf, options, context) {
  13106. const buffers = gltf.json.buffers || [];
  13107. for (let i = 0; i < buffers.length; ++i) {
  13108. const buffer = buffers[i];
  13109. if (buffer.uri) {
  13110. var _context$fetch, _response$arrayBuffer;
  13111. const {
  13112. fetch
  13113. } = context;
  13114. assert$1(fetch);
  13115. const uri = resolveUrl(buffer.uri, options);
  13116. 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));
  13117. 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));
  13118. gltf.buffers[i] = {
  13119. arrayBuffer,
  13120. byteOffset: 0,
  13121. byteLength: arrayBuffer.byteLength
  13122. };
  13123. delete buffer.uri;
  13124. }
  13125. }
  13126. }
  13127. async function loadImages(gltf, options, context) {
  13128. const imageIndices = getReferencesImageIndices(gltf);
  13129. const images = gltf.json.images || [];
  13130. const promises = [];
  13131. for (const imageIndex of imageIndices) {
  13132. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13133. }
  13134. return await Promise.all(promises);
  13135. }
  13136. function getReferencesImageIndices(gltf) {
  13137. const imageIndices = new Set();
  13138. const textures = gltf.json.textures || [];
  13139. for (const texture of textures) {
  13140. if (texture.source !== undefined) {
  13141. imageIndices.add(texture.source);
  13142. }
  13143. }
  13144. return Array.from(imageIndices).sort();
  13145. }
  13146. async function loadImage(gltf, image, index, options, context) {
  13147. const {
  13148. fetch,
  13149. parse
  13150. } = context;
  13151. let arrayBuffer;
  13152. if (image.uri) {
  13153. const uri = resolveUrl(image.uri, options);
  13154. const response = await fetch(uri);
  13155. arrayBuffer = await response.arrayBuffer();
  13156. }
  13157. if (Number.isFinite(image.bufferView)) {
  13158. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13159. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13160. }
  13161. assert$1(arrayBuffer, 'glTF image has no data');
  13162. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13163. mimeType: image.mimeType,
  13164. basis: options.basis || {
  13165. format: selectSupportedBasisFormat()
  13166. }
  13167. }, context);
  13168. if (parsedImage && parsedImage[0]) {
  13169. parsedImage = {
  13170. compressed: true,
  13171. mipmaps: false,
  13172. width: parsedImage[0].width,
  13173. height: parsedImage[0].height,
  13174. data: parsedImage
  13175. };
  13176. }
  13177. gltf.images = gltf.images || [];
  13178. gltf.images[index] = parsedImage;
  13179. }
  13180. const GLTFLoader = {
  13181. name: 'glTF',
  13182. id: 'gltf',
  13183. module: 'gltf',
  13184. version: VERSION$3,
  13185. extensions: ['gltf', 'glb'],
  13186. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13187. text: true,
  13188. binary: true,
  13189. tests: ['glTF'],
  13190. parse: parse$1,
  13191. options: {
  13192. gltf: {
  13193. normalize: true,
  13194. loadBuffers: true,
  13195. loadImages: true,
  13196. decompressMeshes: true,
  13197. postProcess: true
  13198. },
  13199. log: console
  13200. },
  13201. deprecatedOptions: {
  13202. fetchImages: 'gltf.loadImages',
  13203. createImages: 'gltf.loadImages',
  13204. decompress: 'gltf.decompressMeshes',
  13205. postProcess: 'gltf.postProcess',
  13206. gltf: {
  13207. decompress: 'gltf.decompressMeshes'
  13208. }
  13209. }
  13210. };
  13211. async function parse$1(arrayBuffer, options = {}, context) {
  13212. options = { ...GLTFLoader.options,
  13213. ...options
  13214. };
  13215. options.gltf = { ...GLTFLoader.options.gltf,
  13216. ...options.gltf
  13217. };
  13218. const {
  13219. byteOffset = 0
  13220. } = options;
  13221. const gltf = {};
  13222. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13223. }
  13224. const GLTF_FORMAT = {
  13225. URI: 0,
  13226. EMBEDDED: 1
  13227. };
  13228. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13229. tile.rotateYtoZ = true;
  13230. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13231. if (gltfByteLength === 0) {
  13232. throw new Error('glTF byte length must be greater than 0.');
  13233. }
  13234. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13235. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13236. tile.gltfByteOffset = 0;
  13237. tile.gltfByteLength = gltfByteLength;
  13238. if (byteOffset % 4 === 0) ; else {
  13239. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13240. }
  13241. return tile.byteOffset + tile.byteLength;
  13242. }
  13243. async function extractGLTF(tile, gltfFormat, options, context) {
  13244. const tile3DOptions = options['3d-tiles'] || {};
  13245. extractGLTFBufferOrURL(tile, gltfFormat);
  13246. if (tile3DOptions.loadGLTF) {
  13247. const {
  13248. parse,
  13249. fetch
  13250. } = context;
  13251. if (tile.gltfUrl) {
  13252. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13253. tile.gltfByteOffset = 0;
  13254. }
  13255. if (tile.gltfArrayBuffer) {
  13256. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13257. delete tile.gltfArrayBuffer;
  13258. delete tile.gltfByteOffset;
  13259. delete tile.gltfByteLength;
  13260. }
  13261. }
  13262. }
  13263. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13264. switch (gltfFormat) {
  13265. case GLTF_FORMAT.URI:
  13266. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13267. const textDecoder = new TextDecoder();
  13268. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13269. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13270. delete tile.gltfArrayBuffer;
  13271. delete tile.gltfByteOffset;
  13272. delete tile.gltfByteLength;
  13273. break;
  13274. case GLTF_FORMAT.EMBEDDED:
  13275. break;
  13276. default:
  13277. throw new Error('b3dm: Illegal glTF format field');
  13278. }
  13279. }
  13280. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13281. var _tile$gltf;
  13282. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13283. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13284. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13285. if (extensions && extensions.CESIUM_RTC) {
  13286. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13287. }
  13288. return byteOffset;
  13289. }
  13290. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13291. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13292. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13293. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13294. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13295. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13296. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13297. return byteOffset;
  13298. }
  13299. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13300. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13301. await extractGLTF(tile, tile.gltfFormat, options, context);
  13302. return byteOffset;
  13303. }
  13304. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13305. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13306. if (tile.version !== 1) {
  13307. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13308. }
  13309. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13310. const view = new DataView(arrayBuffer);
  13311. tile.gltfFormat = view.getUint32(byteOffset, true);
  13312. byteOffset += 4;
  13313. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13314. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13315. if (tile.featureTableJsonByteLength === 0) {
  13316. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13317. }
  13318. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13319. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13320. featureTable.featuresLength = instancesLength;
  13321. if (!Number.isFinite(instancesLength)) {
  13322. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13323. }
  13324. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13325. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13326. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13327. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13328. return byteOffset;
  13329. }
  13330. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13331. const collectionOptions = {
  13332. instances: new Array(instancesLength),
  13333. batchTable: tile._batchTable,
  13334. cull: false,
  13335. url: undefined,
  13336. gltf: undefined,
  13337. basePath: undefined,
  13338. incrementallyLoadTextures: false,
  13339. forwardAxis: [1, 0, 0]
  13340. };
  13341. const instances = collectionOptions.instances;
  13342. const instancePosition = new Vector3();
  13343. new Vector3();
  13344. new Vector3();
  13345. new Vector3();
  13346. const instanceRotation = new Matrix3();
  13347. const instanceQuaternion = new Quaternion();
  13348. const instanceScale = new Vector3();
  13349. const instanceTranslationRotationScale = {};
  13350. const instanceTransform = new Matrix4();
  13351. const scratch1 = [];
  13352. const scratch2 = [];
  13353. const scratchVector1 = new Vector3();
  13354. const scratchVector2 = new Vector3();
  13355. for (let i = 0; i < instancesLength; i++) {
  13356. let position;
  13357. if (featureTable.hasProperty('POSITION')) {
  13358. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13359. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13360. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13361. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13362. if (!quantizedVolumeOffset) {
  13363. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13364. }
  13365. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13366. if (!quantizedVolumeScale) {
  13367. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13368. }
  13369. const MAX_UNSIGNED_SHORT = 65535.0;
  13370. for (let j = 0; j < 3; j++) {
  13371. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13372. }
  13373. }
  13374. if (!position) {
  13375. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13376. }
  13377. instancePosition.copy(position);
  13378. instanceTranslationRotationScale.translation = instancePosition;
  13379. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13380. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13381. if (tile.normalUp) {
  13382. if (!tile.normalRight) {
  13383. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13384. }
  13385. tile.hasCustomOrientation = true;
  13386. } else {
  13387. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13388. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13389. if (tile.octNormalUp) {
  13390. if (!tile.octNormalRight) {
  13391. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13392. }
  13393. throw new Error('i3dm: oct-encoded orientation not implemented');
  13394. } else if (tile.eastNorthUp) {
  13395. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13396. instanceTransform.getRotationMatrix3(instanceRotation);
  13397. } else {
  13398. instanceRotation.identity();
  13399. }
  13400. }
  13401. instanceQuaternion.fromMatrix3(instanceRotation);
  13402. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13403. instanceScale.set(1.0, 1.0, 1.0);
  13404. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13405. if (Number.isFinite(scale)) {
  13406. instanceScale.multiplyByScalar(scale);
  13407. }
  13408. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13409. if (nonUniformScale) {
  13410. instanceScale.scale(nonUniformScale);
  13411. }
  13412. instanceTranslationRotationScale.scale = instanceScale;
  13413. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13414. if (batchId === undefined) {
  13415. batchId = i;
  13416. }
  13417. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13418. instanceTransform.identity();
  13419. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13420. instanceTransform.multiplyRight(rotationMatrix);
  13421. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13422. const modelMatrix = instanceTransform.clone();
  13423. instances[i] = {
  13424. modelMatrix,
  13425. batchId
  13426. };
  13427. }
  13428. tile.instances = instances;
  13429. }
  13430. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13431. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13432. const view = new DataView(arrayBuffer);
  13433. tile.tilesLength = view.getUint32(byteOffset, true);
  13434. byteOffset += 4;
  13435. tile.tiles = [];
  13436. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13437. const subtile = {};
  13438. tile.tiles.push(subtile);
  13439. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13440. }
  13441. return byteOffset;
  13442. }
  13443. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13444. tile.rotateYtoZ = true;
  13445. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13446. const {
  13447. parse
  13448. } = context;
  13449. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13450. }
  13451. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13452. tile.byteOffset = byteOffset;
  13453. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13454. switch (tile.type) {
  13455. case TILE3D_TYPE.COMPOSITE:
  13456. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13457. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13458. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13459. case TILE3D_TYPE.GLTF:
  13460. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13461. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13462. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13463. case TILE3D_TYPE.POINT_CLOUD:
  13464. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13465. default:
  13466. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13467. }
  13468. }
  13469. const SUBTREE_FILE_MAGIC = 0x74627573;
  13470. const SUBTREE_FILE_VERSION = 1;
  13471. async function parse3DTilesSubtree(data) {
  13472. const magic = new Uint32Array(data.slice(0, 4));
  13473. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13474. throw new Error('Wrong subtree file magic number');
  13475. }
  13476. const version = new Uint32Array(data.slice(4, 8));
  13477. if (version[0] !== SUBTREE_FILE_VERSION) {
  13478. throw new Error('Wrong subtree file verson, must be 1');
  13479. }
  13480. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13481. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13482. const textDecoder = new TextDecoder('utf8');
  13483. const string = textDecoder.decode(stringAttribute);
  13484. const subtree = JSON.parse(string);
  13485. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13486. let internalBinaryBuffer = new ArrayBuffer(0);
  13487. if (binaryByteLength) {
  13488. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13489. }
  13490. if ('bufferView' in subtree.tileAvailability) {
  13491. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13492. }
  13493. if ('bufferView' in subtree.contentAvailability) {
  13494. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13495. }
  13496. if ('bufferView' in subtree.childSubtreeAvailability) {
  13497. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13498. }
  13499. return subtree;
  13500. }
  13501. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13502. const bufferViewIndex = subtree[name].bufferView;
  13503. const bufferView = subtree.bufferViews[bufferViewIndex];
  13504. const buffer = subtree.buffers[bufferView.buffer];
  13505. if (buffer.uri) {
  13506. const response = await fetchFile(buffer.uri);
  13507. const data = await response.arrayBuffer();
  13508. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13509. }
  13510. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13511. }
  13512. function parseUint64Value(buffer) {
  13513. const dataView = new DataView(buffer);
  13514. const left = dataView.getUint32(0, true);
  13515. const right = dataView.getUint32(4, true);
  13516. return left + 2 ** 32 * right;
  13517. }
  13518. const Tile3DSubtreeLoader = {
  13519. id: '3d-tiles-subtree',
  13520. name: '3D Tiles Subtree',
  13521. module: '3d-tiles',
  13522. version: VERSION$5,
  13523. extensions: ['subtree'],
  13524. mimeTypes: ['application/octet-stream'],
  13525. tests: ['subtree'],
  13526. parse: parse3DTilesSubtree,
  13527. options: {}
  13528. };
  13529. const QUADTREE_DEVISION_COUNT = 4;
  13530. const OCTREE_DEVISION_COUNT = 8;
  13531. const SUBDIVISION_COUNT_MAP = {
  13532. QUADTREE: QUADTREE_DEVISION_COUNT,
  13533. OCTREE: OCTREE_DEVISION_COUNT
  13534. };
  13535. async function parseImplicitTiles(subtree, options, parentData = {
  13536. mortonIndex: 0,
  13537. x: 0,
  13538. y: 0,
  13539. z: 0
  13540. }, childIndex = 0, level = 0, globalData = {
  13541. level: 0,
  13542. mortonIndex: 0,
  13543. x: 0,
  13544. y: 0,
  13545. z: 0
  13546. }) {
  13547. const {
  13548. subdivisionScheme,
  13549. subtreeLevels,
  13550. maximumLevel,
  13551. contentUrlTemplate,
  13552. subtreesUriTemplate,
  13553. basePath
  13554. } = options;
  13555. const tile = {
  13556. children: [],
  13557. lodMetricValue: 0,
  13558. contentUrl: ''
  13559. };
  13560. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13561. const childX = childIndex & 0b01;
  13562. const childY = childIndex >> 1 & 0b01;
  13563. const childZ = childIndex >> 2 & 0b01;
  13564. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13565. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13566. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13567. let childTileX = concatBits(parentData.x, childX);
  13568. let childTileY = concatBits(parentData.y, childY);
  13569. let childTileZ = concatBits(parentData.z, childZ);
  13570. let isChildSubtreeAvailable = false;
  13571. if (level + 1 > subtreeLevels) {
  13572. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13573. }
  13574. const x = concatBits(globalData.x, childTileX);
  13575. const y = concatBits(globalData.y, childTileY);
  13576. const z = concatBits(globalData.z, childTileZ);
  13577. const lev = level + globalData.level;
  13578. if (isChildSubtreeAvailable) {
  13579. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13580. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13581. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13582. subtree = childSubtree;
  13583. globalData.mortonIndex = childTileMortonIndex;
  13584. globalData.x = childTileX;
  13585. globalData.y = childTileY;
  13586. globalData.z = childTileZ;
  13587. globalData.level = level;
  13588. childTileMortonIndex = 0;
  13589. tileAvailabilityIndex = 0;
  13590. childTileX = 0;
  13591. childTileY = 0;
  13592. childTileZ = 0;
  13593. level = 0;
  13594. }
  13595. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13596. if (!isTileAvailable || level > maximumLevel) {
  13597. return tile;
  13598. }
  13599. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13600. if (isContentAvailable) {
  13601. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13602. }
  13603. const childTileLevel = level + 1;
  13604. const pData = {
  13605. mortonIndex: childTileMortonIndex,
  13606. x: childTileX,
  13607. y: childTileY,
  13608. z: childTileZ
  13609. };
  13610. for (let index = 0; index < childrenPerTile; index++) {
  13611. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13612. if (currentTile.contentUrl || currentTile.children.length) {
  13613. const globalLevel = lev + 1;
  13614. const childCoordinates = {
  13615. childTileX,
  13616. childTileY,
  13617. childTileZ
  13618. };
  13619. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13620. tile.children.push(formattedTile);
  13621. }
  13622. }
  13623. return tile;
  13624. }
  13625. function getAvailabilityResult(availabilityData, index) {
  13626. if ('constant' in availabilityData) {
  13627. return Boolean(availabilityData.constant);
  13628. }
  13629. if (availabilityData.explicitBitstream) {
  13630. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13631. }
  13632. return false;
  13633. }
  13634. function formatTileData(tile, level, childCoordinates, options) {
  13635. const {
  13636. basePath,
  13637. refine,
  13638. getRefine,
  13639. lodMetricType,
  13640. getTileType,
  13641. rootLodMetricValue,
  13642. rootBoundingVolume
  13643. } = options;
  13644. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13645. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13646. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13647. return {
  13648. children: tile.children,
  13649. contentUrl: tile.contentUrl,
  13650. content: {
  13651. uri
  13652. },
  13653. id: tile.contentUrl,
  13654. refine: getRefine(refine),
  13655. type: getTileType(tile),
  13656. lodMetricType,
  13657. lodMetricValue,
  13658. boundingVolume
  13659. };
  13660. }
  13661. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13662. if (rootBoundingVolume.region) {
  13663. const {
  13664. childTileX,
  13665. childTileY,
  13666. childTileZ
  13667. } = childCoordinates;
  13668. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13669. const boundingVolumesCount = 2 ** level;
  13670. const sizeX = (east - west) / boundingVolumesCount;
  13671. const sizeY = (north - south) / boundingVolumesCount;
  13672. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13673. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13674. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13675. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13676. return {
  13677. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13678. };
  13679. }
  13680. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13681. return null;
  13682. }
  13683. function concatBits(first, second) {
  13684. return parseInt(first.toString(2) + second.toString(2), 2);
  13685. }
  13686. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13687. const mapUrl = generateMapUrl({
  13688. level,
  13689. x,
  13690. y,
  13691. z
  13692. });
  13693. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13694. }
  13695. function generateMapUrl(items) {
  13696. const mapUrl = {};
  13697. for (const key in items) {
  13698. mapUrl["{".concat(key, "}")] = items[key];
  13699. }
  13700. return mapUrl;
  13701. }
  13702. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13703. const byteIndex = Math.floor(availabilityIndex / 8);
  13704. const bitIndex = availabilityIndex % 8;
  13705. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13706. return bitValue === 1;
  13707. }
  13708. function getTileType(tile) {
  13709. if (!tile.contentUrl) {
  13710. return TILE_TYPE.EMPTY;
  13711. }
  13712. const contentUrl = tile.contentUrl;
  13713. const fileExtension = contentUrl.split('.').pop();
  13714. switch (fileExtension) {
  13715. case 'pnts':
  13716. return TILE_TYPE.POINTCLOUD;
  13717. case 'i3dm':
  13718. case 'b3dm':
  13719. case 'glb':
  13720. case 'gltf':
  13721. return TILE_TYPE.SCENEGRAPH;
  13722. default:
  13723. return fileExtension;
  13724. }
  13725. }
  13726. function getRefine(refine) {
  13727. switch (refine) {
  13728. case 'REPLACE':
  13729. case 'replace':
  13730. return TILE_REFINEMENT.REPLACE;
  13731. case 'ADD':
  13732. case 'add':
  13733. return TILE_REFINEMENT.ADD;
  13734. default:
  13735. return refine;
  13736. }
  13737. }
  13738. function normalizeTileData(tile, options) {
  13739. if (!tile) {
  13740. return null;
  13741. }
  13742. if (tile.content) {
  13743. const contentUri = tile.content.uri || tile.content.url;
  13744. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13745. }
  13746. tile.id = tile.contentUrl;
  13747. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13748. tile.lodMetricValue = tile.geometricError;
  13749. tile.transformMatrix = tile.transform;
  13750. tile.type = getTileType(tile);
  13751. tile.refine = getRefine(tile.refine);
  13752. return tile;
  13753. }
  13754. function normalizeTileHeaders(tileset) {
  13755. const basePath = tileset.basePath;
  13756. const root = normalizeTileData(tileset.root, tileset);
  13757. const stack = [];
  13758. stack.push(root);
  13759. while (stack.length > 0) {
  13760. const tile = stack.pop() || {};
  13761. const children = tile.children || [];
  13762. for (const childHeader of children) {
  13763. normalizeTileData(childHeader, {
  13764. basePath
  13765. });
  13766. stack.push(childHeader);
  13767. }
  13768. }
  13769. return root;
  13770. }
  13771. async function normalizeImplicitTileHeaders(tileset) {
  13772. if (!tileset.root) {
  13773. return null;
  13774. }
  13775. const basePath = tileset.basePath;
  13776. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13777. const {
  13778. subdivisionScheme,
  13779. maximumLevel,
  13780. subtreeLevels,
  13781. subtrees: {
  13782. uri: subtreesUriTemplate
  13783. }
  13784. } = implicitTilingExtension;
  13785. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13786. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13787. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13788. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13789. const refine = tileset.root.refine;
  13790. const rootLodMetricValue = tileset.root.geometricError;
  13791. const rootBoundingVolume = tileset.root.boundingVolume;
  13792. const options = {
  13793. contentUrlTemplate,
  13794. subtreesUriTemplate,
  13795. subdivisionScheme,
  13796. subtreeLevels,
  13797. maximumLevel,
  13798. refine,
  13799. basePath,
  13800. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13801. rootLodMetricValue,
  13802. rootBoundingVolume,
  13803. getTileType,
  13804. getRefine
  13805. };
  13806. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13807. }
  13808. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13809. if (!tile) {
  13810. return null;
  13811. }
  13812. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13813. tile.lodMetricValue = tile.geometricError;
  13814. tile.transformMatrix = tile.transform;
  13815. const {
  13816. children,
  13817. contentUrl
  13818. } = await parseImplicitTiles(rootSubtree, options);
  13819. if (contentUrl) {
  13820. tile.contentUrl = contentUrl;
  13821. tile.content = {
  13822. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13823. };
  13824. }
  13825. tile.refine = getRefine(tile.refine);
  13826. tile.type = getTileType(tile);
  13827. tile.children = children;
  13828. tile.id = tile.contentUrl;
  13829. return tile;
  13830. }
  13831. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13832. const Tiles3DLoader = {
  13833. id: '3d-tiles',
  13834. name: '3D Tiles',
  13835. module: '3d-tiles',
  13836. version: VERSION$5,
  13837. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13838. mimeTypes: ['application/octet-stream'],
  13839. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13840. parse,
  13841. options: {
  13842. '3d-tiles': {
  13843. loadGLTF: true,
  13844. decodeQuantizedPositions: false,
  13845. isTileset: 'auto',
  13846. assetGltfUpAxis: null
  13847. }
  13848. }
  13849. };
  13850. function getBaseUri(tileset) {
  13851. return dirname(tileset.url);
  13852. }
  13853. async function parseTile(arrayBuffer, options, context) {
  13854. const tile = {
  13855. content: {
  13856. featureIds: null
  13857. }
  13858. };
  13859. const byteOffset = 0;
  13860. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13861. return tile.content;
  13862. }
  13863. async function parseTileset(data, options, context) {
  13864. var _tilesetJson$root;
  13865. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13866. tilesetJson.loader = options.loader || Tiles3DLoader;
  13867. tilesetJson.url = context.url;
  13868. tilesetJson.basePath = getBaseUri(tilesetJson);
  13869. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13870. tilesetJson.type = TILESET_TYPE.TILES3D;
  13871. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13872. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13873. return tilesetJson;
  13874. }
  13875. async function parse(data, options, context) {
  13876. const loaderOptions = options['3d-tiles'] || {};
  13877. let isTileset;
  13878. if (loaderOptions.isTileset === 'auto') {
  13879. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13880. } else {
  13881. isTileset = loaderOptions.isTileset;
  13882. }
  13883. if (isTileset) {
  13884. data = await parseTileset(data, options, context);
  13885. } else {
  13886. data = await parseTile(data, options, context);
  13887. }
  13888. return data;
  13889. }
  13890. function hasImplicitTilingExtension(tilesetJson) {
  13891. var _tilesetJson$extensio, _tilesetJson$extensio2;
  13892. 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));
  13893. }
  13894. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  13895. async function getIonTilesetMetadata(accessToken, assetId) {
  13896. if (!assetId) {
  13897. const assets = await getIonAssets(accessToken);
  13898. for (const item of assets.items) {
  13899. if (item.type === '3DTILES') {
  13900. assetId = item.id;
  13901. }
  13902. }
  13903. }
  13904. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  13905. const {
  13906. type,
  13907. url
  13908. } = ionAssetMetadata;
  13909. assert$7(type === '3DTILES' && url);
  13910. ionAssetMetadata.headers = {
  13911. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  13912. };
  13913. return ionAssetMetadata;
  13914. }
  13915. async function getIonAssets(accessToken) {
  13916. assert$7(accessToken);
  13917. const url = CESIUM_ION_URL;
  13918. const headers = {
  13919. Authorization: "Bearer ".concat(accessToken)
  13920. };
  13921. const response = await fetchFile(url, {
  13922. fetch: {
  13923. headers
  13924. }
  13925. });
  13926. if (!response.ok) {
  13927. throw new Error(response.statusText);
  13928. }
  13929. return await response.json();
  13930. }
  13931. async function getIonAssetMetadata(accessToken, assetId) {
  13932. assert$7(accessToken, assetId);
  13933. const headers = {
  13934. Authorization: "Bearer ".concat(accessToken)
  13935. };
  13936. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  13937. let response = await fetchFile("".concat(url), {
  13938. fetch: {
  13939. headers
  13940. }
  13941. });
  13942. if (!response.ok) {
  13943. throw new Error(response.statusText);
  13944. }
  13945. let metadata = await response.json();
  13946. response = await fetchFile("".concat(url, "/endpoint"), {
  13947. fetch: {
  13948. headers
  13949. }
  13950. });
  13951. if (!response.ok) {
  13952. throw new Error(response.statusText);
  13953. }
  13954. const tilesetInfo = await response.json();
  13955. metadata = { ...metadata,
  13956. ...tilesetInfo
  13957. };
  13958. return metadata;
  13959. }
  13960. async function preload(url, options = {}) {
  13961. options = options['cesium-ion'] || {};
  13962. const {
  13963. accessToken
  13964. } = options;
  13965. let assetId = options.assetId;
  13966. if (!Number.isFinite(assetId)) {
  13967. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  13968. assetId = matched && matched[1];
  13969. }
  13970. return getIonTilesetMetadata(accessToken, assetId);
  13971. }
  13972. const CesiumIonLoader = { ...Tiles3DLoader,
  13973. id: 'cesium-ion',
  13974. name: 'Cesium Ion',
  13975. preload,
  13976. parse: async (data, options, context) => {
  13977. options = { ...options
  13978. };
  13979. options['3d-tiles'] = options['cesium-ion'];
  13980. options.loader = CesiumIonLoader;
  13981. return Tiles3DLoader.parse(data, options, context);
  13982. },
  13983. options: {
  13984. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  13985. accessToken: null
  13986. }
  13987. }
  13988. };
  13989. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  13990. function generateGradientTexture(gradient) {
  13991. const size = 64;
  13992. // create canvas
  13993. const canvas = document.createElement('canvas');
  13994. canvas.width = size;
  13995. canvas.height = size;
  13996. // get context
  13997. const context = canvas.getContext('2d');
  13998. // draw gradient
  13999. context.rect(0, 0, size, size);
  14000. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14001. for (let i = 0; i < gradient.length; i++) {
  14002. const step = gradient[i];
  14003. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14004. }
  14005. context.fillStyle = ctxGradient;
  14006. context.fill();
  14007. //let texture = new THREE.Texture(canvas);
  14008. const texture = new CanvasTexture(canvas);
  14009. texture.needsUpdate = true;
  14010. texture.minFilter = LinearFilter;
  14011. texture.wrapS = RepeatWrapping;
  14012. texture.wrapT = RepeatWrapping;
  14013. texture.repeat.set(2, 2);
  14014. // textureImage = texture.image;
  14015. return texture;
  14016. }
  14017. function getCameraFrustum(camera) {
  14018. camera.updateMatrix(); // make sure camera's local matrix is updated
  14019. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14020. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14021. const frustum = new Frustum();
  14022. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14023. return frustum;
  14024. }
  14025. function loadersPlaneToMesh(plane) {
  14026. const group = new Group();
  14027. // Create a basic rectangle geometry from math.gl plane
  14028. const planeGeometry = new PlaneGeometry(10, 5);
  14029. // Align the geometry to the plane
  14030. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14031. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14032. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14033. planeGeometry.lookAt(focalPoint);
  14034. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14035. // Edges
  14036. /*
  14037. const edges = new EdgesGeometry(planeGeometry)
  14038. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14039. //plane
  14040. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14041. const mesh = new Mesh(planeGeometry, material);
  14042. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14043. group.add(arrowHelper);
  14044. group.add(mesh);
  14045. return group;
  14046. }
  14047. function loadersBoundingBoxToMesh(tile) {
  14048. // Create a basic rectangle geometry from math.gl half-axes
  14049. const { boundingVolume } = tile;
  14050. let redColor = 0;
  14051. if (tile.content) {
  14052. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14053. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14054. }
  14055. const boxColor = new Color(redColor, 1.0, 0.0);
  14056. const boxGeometry = new BoxGeometry(1, 1, 1);
  14057. const boxTransform = new Matrix4$1();
  14058. if (boundingVolume.halfAxes) {
  14059. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  14060. }
  14061. else if (boundingVolume.radius) {
  14062. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  14063. }
  14064. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundingVolume.center)) //add
  14065. boxGeometry.applyMatrix4(boxTransform);
  14066. const edges = new EdgesGeometry(boxGeometry);
  14067. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14068. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14069. dispPlane.matrixAutoUpdate = false //add
  14070. /* if(tile.content.byteLength == void 0){
  14071. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14072. dispPlane.updateMatrixWorld = (a,b)=>{
  14073. oldUpdate(a,b)
  14074. }
  14075. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14076. dispPlane.updateMatrix = (a,b)=>{
  14077. oldU(a,b)
  14078. }
  14079. } */
  14080. return dispPlane;
  14081. }
  14082. function getMatrix4FromHalfAxes(halfAxes) {
  14083. const m = halfAxes;
  14084. const rotateMatrix = new Matrix4$1().fromArray([
  14085. m[0] * 2,
  14086. m[1] * 2,
  14087. m[2] * 2,
  14088. 0,
  14089. m[3] * 2,
  14090. m[4] * 2,
  14091. m[5] * 2,
  14092. 0,
  14093. m[6] * 2,
  14094. m[7] * 2,
  14095. m[8] * 2,
  14096. 0,
  14097. 0,
  14098. 0,
  14099. 0,
  14100. 1,
  14101. ]);
  14102. return rotateMatrix;
  14103. }
  14104. /*
  14105. * from https://github.com/tentone/geo-three
  14106. * Tree-shaking did not work, probably due to static class methods
  14107. */
  14108. function datumsToSpherical(latitude, longitude) {
  14109. const EARTH_RADIUS = 6378137;
  14110. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14111. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14112. const x = longitude * EARTH_ORIGIN / 180.0;
  14113. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14114. y = y * EARTH_ORIGIN / 180.0;
  14115. return new Vector2$1(x, y);
  14116. }
  14117. const Gradients = {
  14118. // From chroma spectral http://gka.github.io/chroma.js/
  14119. SPECTRAL: [
  14120. [0, new Color(0.3686, 0.3098, 0.6353)],
  14121. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14122. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14123. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14124. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14125. [0.5, new Color(1.0, 1.0, 0.749)],
  14126. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14127. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14128. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14129. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14130. [1, new Color(0.6196, 0.0039, 0.2588)],
  14131. ],
  14132. PLASMA: [
  14133. [0.0, new Color(0.241, 0.015, 0.61)],
  14134. [0.1, new Color(0.387, 0.001, 0.654)],
  14135. [0.2, new Color(0.524, 0.025, 0.653)],
  14136. [0.3, new Color(0.651, 0.125, 0.596)],
  14137. [0.4, new Color(0.752, 0.227, 0.513)],
  14138. [0.5, new Color(0.837, 0.329, 0.431)],
  14139. [0.6, new Color(0.907, 0.435, 0.353)],
  14140. [0.7, new Color(0.963, 0.554, 0.272)],
  14141. [0.8, new Color(0.992, 0.681, 0.195)],
  14142. [0.9, new Color(0.987, 0.822, 0.144)],
  14143. [1.0, new Color(0.94, 0.975, 0.131)],
  14144. ],
  14145. YELLOW_GREEN: [
  14146. [0, new Color(0.1647, 0.2824, 0.3451)],
  14147. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14148. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14149. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14150. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14151. [0.5, new Color(0.137, 0.665, 0.5614)],
  14152. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14153. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14154. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14155. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14156. [1, new Color(0.9804, 0.9804, 0.4314)],
  14157. ],
  14158. VIRIDIS: [
  14159. [0.0, new Color(0.267, 0.005, 0.329)],
  14160. [0.1, new Color(0.283, 0.141, 0.458)],
  14161. [0.2, new Color(0.254, 0.265, 0.53)],
  14162. [0.3, new Color(0.207, 0.372, 0.553)],
  14163. [0.4, new Color(0.164, 0.471, 0.558)],
  14164. [0.5, new Color(0.128, 0.567, 0.551)],
  14165. [0.6, new Color(0.135, 0.659, 0.518)],
  14166. [0.7, new Color(0.267, 0.749, 0.441)],
  14167. [0.8, new Color(0.478, 0.821, 0.318)],
  14168. [0.9, new Color(0.741, 0.873, 0.15)],
  14169. [1.0, new Color(0.993, 0.906, 0.144)],
  14170. ],
  14171. INFERNO: [
  14172. [0.0, new Color(0.077, 0.042, 0.206)],
  14173. [0.1, new Color(0.225, 0.036, 0.388)],
  14174. [0.2, new Color(0.373, 0.074, 0.432)],
  14175. [0.3, new Color(0.522, 0.128, 0.42)],
  14176. [0.4, new Color(0.665, 0.182, 0.37)],
  14177. [0.5, new Color(0.797, 0.255, 0.287)],
  14178. [0.6, new Color(0.902, 0.364, 0.184)],
  14179. [0.7, new Color(0.969, 0.516, 0.063)],
  14180. [0.8, new Color(0.988, 0.683, 0.072)],
  14181. [0.9, new Color(0.961, 0.859, 0.298)],
  14182. [1.0, new Color(0.988, 0.998, 0.645)],
  14183. ],
  14184. GRAYSCALE: [
  14185. [0, new Color(0, 0, 0)],
  14186. [1, new Color(1, 1, 1)],
  14187. ],
  14188. // 16 samples of the TURBU color scheme
  14189. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14190. // original file licensed under Apache-2.0
  14191. TURBO: [
  14192. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14193. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14194. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14195. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14196. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14197. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14198. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14199. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14200. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14201. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14202. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14203. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14204. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14205. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14206. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14207. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14208. ],
  14209. RAINBOW: [
  14210. [0, new Color(0.278, 0, 0.714)],
  14211. [1 / 6, new Color(0, 0, 1)],
  14212. [2 / 6, new Color(0, 1, 1)],
  14213. [3 / 6, new Color(0, 1, 0)],
  14214. [4 / 6, new Color(1, 1, 0)],
  14215. [5 / 6, new Color(1, 0.64, 0)],
  14216. [1, new Color(1, 0, 0)],
  14217. ],
  14218. CONTOUR: [
  14219. [0.0, new Color(0, 0, 0)],
  14220. [0.03, new Color(0, 0, 0)],
  14221. [0.04, new Color(1, 1, 1)],
  14222. [1.0, new Color(1, 1, 1)],
  14223. ],
  14224. };
  14225. const PointCloudFS = `
  14226. varying vec3 vColor;
  14227. uniform float alpha;
  14228. void main() {
  14229. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14230. discard;
  14231. } else {
  14232. gl_FragColor = vec4( vColor, alpha);
  14233. }
  14234. }
  14235. `;
  14236. const PointCloudVS = `
  14237. varying vec3 vColor;
  14238. uniform sampler2D gradient;
  14239. uniform sampler2D grayscale;
  14240. attribute float intensity;
  14241. attribute float classification;
  14242. uniform vec3 rootCenter;
  14243. uniform vec3 rootNormal;
  14244. uniform vec2 elevationRange;
  14245. uniform int coloring;
  14246. uniform bool hideGround;
  14247. uniform float maxIntensity;
  14248. uniform float intensityContrast;
  14249. uniform float pointSize;
  14250. #ifdef USE_COLOR
  14251. vec3 getRGB() {
  14252. vec3 rgb = color;
  14253. return rgb;
  14254. }
  14255. #endif
  14256. vec3 getElevation(){
  14257. vec4 world = modelMatrix * vec4( position, 1.0 );
  14258. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14259. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14260. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14261. return cElevation;
  14262. }
  14263. vec3 getIntensity(){
  14264. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14265. float intmod = pow(intensity, intensityContrast);
  14266. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14267. return cIntensity;
  14268. }
  14269. vec3 getClassification(){
  14270. float classNormalized = classification / 255.0;
  14271. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14272. return cClassification;
  14273. }
  14274. vec3 getColor(){
  14275. vec3 color;
  14276. if (hideGround && classification == 2.0) {
  14277. return vec3(0.0, 0.0, 0.0);
  14278. }
  14279. if (coloring == 1) {
  14280. color = getIntensity();
  14281. }
  14282. else if (coloring == 2) {
  14283. color = getClassification();
  14284. } else if (coloring == 3) {
  14285. color = getElevation();
  14286. }
  14287. #ifdef USE_COLOR
  14288. else if (coloring == 4) {
  14289. color = getRGB();
  14290. }
  14291. #endif
  14292. else {
  14293. color = vec3(1.0, 1.0, 1.0);
  14294. }
  14295. return color;
  14296. }
  14297. void main() {
  14298. vColor = getColor();
  14299. gl_PointSize = pointSize;
  14300. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14301. }
  14302. `;
  14303. /** Types of coloring used when viewing point cloud tiles */
  14304. var PointCloudColoring;
  14305. (function (PointCloudColoring) {
  14306. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14307. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14308. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14309. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14310. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14311. })(PointCloudColoring || (PointCloudColoring = {}));
  14312. /** Types of shading used when viewing b3dm (mesh) tiles */
  14313. var Shading;
  14314. (function (Shading) {
  14315. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14316. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14317. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14318. })(Shading || (Shading = {}));
  14319. var GeoTransform;
  14320. (function (GeoTransform) {
  14321. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14322. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14323. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14324. })(GeoTransform || (GeoTransform = {}));
  14325. const gradient = Gradients.RAINBOW;
  14326. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14327. const grayscale = Gradients.GRAYSCALE;
  14328. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14329. const defaultOptions = {
  14330. throttleRequests: true,
  14331. maxRequests: 64,
  14332. updateInterval: 0.1,
  14333. maxConcurrency: 1,
  14334. maximumScreenSpaceError: 16,
  14335. maximumMemoryUsage: 32,
  14336. viewDistanceScale: 1.0,
  14337. skipLevelOfDetail: false,
  14338. updateTransforms: true,
  14339. shading: Shading.FlatTexture,
  14340. transparent: false,
  14341. pointCloudColoring: PointCloudColoring.White,
  14342. pointSize: 1.0,
  14343. worker: true,
  14344. wireframe: false,
  14345. debug: false,
  14346. basisTranscoderPath: null,
  14347. dracoDecoderPath: null,
  14348. material: null,
  14349. computeNormals: false,
  14350. shaderCallback: null,
  14351. geoTransform: GeoTransform.Reset,
  14352. preloadTilesCount: null
  14353. };
  14354. /** 3D Tiles Loader */
  14355. class Loader3DTiles {
  14356. /**
  14357. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14358. * @public
  14359. *
  14360. * @param props - Properties for this load call {@link LoaderProps}.
  14361. * @returns An object containing the 3D Model to be added to the scene
  14362. * and a runtime engine to be updated every frame.
  14363. */
  14364. static load(props) {
  14365. return __awaiter(this, void 0, void 0, function* () {
  14366. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14367. const { url } = props;
  14368. const UPDATE_INTERVAL = options.updateInterval;
  14369. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14370. const loadersGLOptions = {};
  14371. if (options.cesiumIONToken) {
  14372. loadersGLOptions['cesium-ion'] = {
  14373. accessToken: options.cesiumIONToken,
  14374. };
  14375. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14376. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14377. }
  14378. if (props.loadingManager) {
  14379. props.loadingManager.itemStart(url);
  14380. }
  14381. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14382. const renderMap = {};
  14383. const boxMap = {};
  14384. const unloadQueue = [];
  14385. const root = new Group();
  14386. const tileBoxes = new Group();
  14387. tileBoxes.matrixAutoUpdate = false//add
  14388. if (!options.debug) {
  14389. tileBoxes.visible = false;
  14390. }else{
  14391. options.parent.add(tileBoxes) //add
  14392. }
  14393. const pointcloudUniforms = {
  14394. pointSize: { type: 'f', value: options.pointSize },
  14395. gradient: { type: 't', value: gradientTexture },
  14396. grayscale: { type: 't', value: grayscaleTexture },
  14397. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14398. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14399. coloring: { type: 'i', value: options.pointCloudColoring },
  14400. hideGround: { type: 'b', value: true },
  14401. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14402. maxIntensity: { type: 'f', value: 1.0 },
  14403. intensityContrast: { type: 'f', value: 1.0 },
  14404. alpha: { type: 'f', value: 1.0 },
  14405. };
  14406. const pointcloudMaterial = new ShaderMaterial({
  14407. uniforms: pointcloudUniforms,
  14408. vertexShader: PointCloudVS,
  14409. fragmentShader: PointCloudFS,
  14410. transparent: options.transparent,
  14411. vertexColors: true
  14412. });
  14413. let cameraReference = null;
  14414. let rendererReference = null;
  14415. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14416. let ktx2Loader = undefined;
  14417. let dracoLoader = undefined;
  14418. if (options.basisTranscoderPath) {
  14419. ktx2Loader = new KTX2Loader();
  14420. ktx2Loader.detectSupport(props.renderer);
  14421. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14422. ktx2Loader.setWorkerLimit(1);
  14423. gltfLoader.setKTX2Loader(ktx2Loader);
  14424. }
  14425. if (options.dracoDecoderPath) {
  14426. dracoLoader = new DRACOLoader();
  14427. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14428. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14429. gltfLoader.setDRACOLoader(dracoLoader);
  14430. }
  14431. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14432. const tileOptions = {
  14433. maximumMemoryUsage: options.maximumMemoryUsage,
  14434. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14435. viewDistanceScale: options.viewDistanceScale,
  14436. skipLevelOfDetail: options.skipLevelOfDetail,
  14437. updateTransforms: options.updateTransforms,
  14438. throttleRequests: options.throttleRequests,
  14439. maxRequests: options.maxRequests,
  14440. maxDepth: options.maxDepth || 50, // !zeg改
  14441. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14442. let tileContent = null;
  14443. switch (tile.type) {
  14444. case TILE_TYPE.POINTCLOUD: {
  14445. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14446. break;
  14447. }
  14448. case TILE_TYPE.SCENEGRAPH:
  14449. case TILE_TYPE.MESH: {
  14450. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14451. break;
  14452. }
  14453. }
  14454. if (tileContent) {
  14455. tileContent.visible = false;
  14456. renderMap[tile.id] = tileContent;
  14457. root.add(renderMap[tile.id]);
  14458. if (options.debug) {
  14459. const box = loadersBoundingBoxToMesh(tile);
  14460. tileBoxes.add(box);
  14461. boxMap[tile.id] = box;
  14462. }
  14463. //xzw :
  14464. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14465. }
  14466. }),
  14467. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14468. if (tileset) {
  14469. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14470. detectOrientation(tile);
  14471. }
  14472. tileset._frameNumber++;
  14473. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14474. }
  14475. }),
  14476. onTileUnload: (tile) => {
  14477. unloadQueue.push(tile);
  14478. },
  14479. onTileError: (tile, message) => {
  14480. console.error('Tile error', tile.id, message);
  14481. },
  14482. };
  14483. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14484. loadImages: false,
  14485. }, '3d-tiles': {
  14486. loadGLTF: false
  14487. } }) }));
  14488. //
  14489. // transformations
  14490. const threeMat = new Matrix4$1();
  14491. const tileTrasnform = new Matrix4$1();
  14492. const rootCenter = new Vector3$1();
  14493. let orientationDetected = false;
  14494. if (tileset.root.boundingVolume) {
  14495. if (tileset.root.header.boundingVolume.region) {
  14496. // TODO: Handle region type bounding volumes
  14497. // https://github.com/visgl/loaders.gl/issues/1994
  14498. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14499. options.geoTransform = GeoTransform.WGS84Cartesian;
  14500. }
  14501. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14502. }
  14503. else {
  14504. console.warn("Bounding volume not found, no transformations applied");
  14505. }
  14506. if (options.debug) {
  14507. const box = loadersBoundingBoxToMesh(tileset.root);
  14508. tileBoxes.add(box);
  14509. boxMap[tileset.root.id] = box;
  14510. }
  14511. let disposeFlag = false;
  14512. let loadingEnded = false;
  14513. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14514. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14515. // Extra stats
  14516. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14517. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14518. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14519. let timer = 0;
  14520. let lastCameraTransform = null;
  14521. let lastCameraAspect = null;
  14522. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14523. let sseDenominator = null;
  14524. root.updateMatrixWorld(true);
  14525. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14526. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14527. detectOrientation(tileset.root);
  14528. updateResetTransform();
  14529. if (options.debug) {
  14530. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14531. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14532. }
  14533. if (options.geoTransform == GeoTransform.Mercator) {
  14534. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14535. rootCenter.set(coords.x, 0, -coords.y);
  14536. root.position.copy(rootCenter);
  14537. root.rotation.set(-Math.PI / 2, 0, 0);
  14538. root.updateMatrixWorld(true);
  14539. }
  14540. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14541. root.applyMatrix4(tileTrasnform);
  14542. root.updateMatrixWorld(true);
  14543. rootCenter.copy(root.position);
  14544. }
  14545. function detectOrientation(tile) {
  14546. if (!tile.boundingVolume.halfAxes) {
  14547. return;
  14548. }
  14549. const halfAxes = tile.boundingVolume.halfAxes;
  14550. const orientationMatrix = new Matrix4$1()
  14551. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14552. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14553. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14554. if (!rotation.equals(new Euler())) {
  14555. orientationDetected = true;
  14556. const pos = new Vector3$1(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  14557. tileTrasnform.extractRotation(orientationMatrix);
  14558. tileTrasnform.setPosition(pos);
  14559. updateResetTransform();
  14560. }
  14561. }
  14562. function updateResetTransform() {
  14563. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14564. // Reset the current model matrix and apply our own transformation
  14565. threeMat.copy(tileTrasnform).invert();
  14566. threeMat.premultiply(lastRootTransform);
  14567. threeMat.copy(lastRootTransform).multiply(new Matrix4$1().copy(tileTrasnform).invert());
  14568. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14569. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  14570. }
  14571. }
  14572. // 更新瓦片显隐和瓦片迭代更新
  14573. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14574. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14575. return
  14576. }
  14577. // Assumes camera fov, near and far are not changing
  14578. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14579. const loadersFrustum = new PerspectiveFrustum({
  14580. fov: (camera.fov / 180) * Math.PI,
  14581. aspectRatio: camera.aspect,
  14582. near: camera.near,
  14583. far: camera.far,
  14584. });
  14585. sseDenominator = loadersFrustum.sseDenominator;
  14586. lastCameraAspect = camera.aspect;
  14587. if(camera.aspect == 0)return//add
  14588. if (options.debug) {
  14589. console.log('Updated sse denonimator:', sseDenominator);
  14590. }
  14591. }
  14592. const frustum = getCameraFrustum(camera);
  14593. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14594. const cullingVolume = new CullingVolume(planes);
  14595. const rendererSize = new Vector2$1();
  14596. renderer.getSize(rendererSize);
  14597. const frameState = {
  14598. camera: {
  14599. position: lastCameraPosition.toArray(),
  14600. },
  14601. height: rendererSize.y,
  14602. frameNumber: tileset._frameNumber,
  14603. sseDenominator: sseDenominator,
  14604. cullingVolume: cullingVolume,
  14605. viewport: {
  14606. id: 0,
  14607. },
  14608. };
  14609. tileset._cache.reset();
  14610. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14611. for (const tile of tileset.tiles) {
  14612. if (tile.selected) {
  14613. if (!renderMap[tile.id]) {
  14614. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14615. }
  14616. else {
  14617. // Make sure it's visible
  14618. if(!renderMap[tile.id].visible){
  14619. if(visiVertexCount<maxVertexVisi){
  14620. renderMap[tile.id].visible = true;
  14621. visiVertexCount += renderMap[tile.id].vertexCount //xzw add
  14622. options.debug && (boxMap[tile.id].material.opacity = 1)
  14623. }else{
  14624. //console.log('超出', visiVertexCount)
  14625. }
  14626. }
  14627. /* if(!renderMap[tile.id].realVisible()){
  14628. console.error('!realVisible')
  14629. } */
  14630. }
  14631. }
  14632. else {
  14633. if (renderMap[tile.id]) {
  14634. if(renderMap[tile.id].visible){
  14635. renderMap[tile.id].visible = false;
  14636. options.debug && (boxMap[tile.id].material.opacity = 0.1)
  14637. visiVertexCount -= renderMap[tile.id].vertexCount //xzw add
  14638. }
  14639. }
  14640. }
  14641. }
  14642. while (unloadQueue.length > 0) {
  14643. const tile = unloadQueue.pop();
  14644. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14645. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14646. root.remove(renderMap[tile.id]);
  14647. disposeNode(renderMap[tile.id]);
  14648. delete renderMap[tile.id];
  14649. }
  14650. if (boxMap[tile.id]) {
  14651. disposeNode(boxMap[tile.id]);
  14652. tileBoxes.remove(boxMap[tile.id]);
  14653. delete boxMap[tile.id];
  14654. }
  14655. }
  14656. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14657. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14658. if (props.onProgress) {
  14659. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14660. }
  14661. if (props.loadingManager && !loadingEnded) {
  14662. if (tilesLoading == 0 &&
  14663. (options.preloadTilesCount == null ||
  14664. tilesLoaded >= options.preloadTilesCount)) {
  14665. loadingEnded = true;
  14666. props.loadingManager.itemEnd(props.url);
  14667. }
  14668. }
  14669. return frameState;
  14670. }
  14671. return {
  14672. model: root,
  14673. runtime: {
  14674. getTileset: () => {
  14675. return tileset;
  14676. },
  14677. getStats: () => {
  14678. return tileset.stats;
  14679. },
  14680. showTiles: (visible) => {
  14681. tileBoxes.visible = visible;
  14682. },
  14683. setWireframe: (wireframe) => {
  14684. options.wireframe = wireframe;
  14685. root.traverse((object) => {
  14686. if (object instanceof Mesh) {
  14687. object.material.wireframe = wireframe;
  14688. }
  14689. });
  14690. },
  14691. setDebug: (debug) => {
  14692. options.debug = debug;
  14693. tileBoxes.visible = debug;
  14694. },
  14695. setShading: (shading) => {
  14696. options.shading = shading;
  14697. },
  14698. getTileBoxes: () => {
  14699. return tileBoxes;
  14700. },
  14701. setViewDistanceScale: (scale) => {
  14702. tileset.options.viewDistanceScale = scale;
  14703. tileset._frameNumber++;
  14704. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14705. },
  14706. setHideGround: (enabled) => {
  14707. pointcloudUniforms.hideGround.value = enabled;
  14708. },
  14709. setPointCloudColoring: (selection) => {
  14710. pointcloudUniforms.coloring.value = selection;
  14711. },
  14712. setElevationRange: (range) => {
  14713. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14714. },
  14715. setMaxIntensity: (intensity) => {
  14716. pointcloudUniforms.maxIntensity.value = intensity;
  14717. },
  14718. setIntensityContrast: (contrast) => {
  14719. pointcloudUniforms.intensityContrast.value = contrast;
  14720. },
  14721. setPointAlpha: (alpha) => {
  14722. pointcloudUniforms.alpha.value = alpha;
  14723. },
  14724. getLatLongHeightFromPosition: (position) => {
  14725. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14726. return {
  14727. lat: cartographicPosition[1],
  14728. long: cartographicPosition[0],
  14729. height: cartographicPosition[2],
  14730. };
  14731. },
  14732. getPositionFromLatLongHeight: (coord) => {
  14733. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14734. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14735. },
  14736. getCameraFrustum: (camera) => {
  14737. const frustum = getCameraFrustum(camera);
  14738. const meshes = frustum.planes
  14739. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14740. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14741. const model = new Group();
  14742. for (const mesh of meshes)
  14743. model.add(mesh);
  14744. return model;
  14745. },
  14746. update: function (dt, renderer, camera, ifForce) {
  14747. cameraReference = camera;
  14748. rendererReference = renderer;
  14749. timer += dt;
  14750. if(!ifForce) ifForce = tileset.nextForceUpdate
  14751. tileset.nextForceUpdate = false
  14752. if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  14753. viewer.dispatchEvent('content_changed')
  14754. }
  14755. tileset.needRenderNext = ifForce
  14756. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  14757. if (!lastRootTransform.equals(root.matrixWorld)) {
  14758. timer = 0;
  14759. lastRootTransform.copy(root.matrixWorld);
  14760. updateResetTransform();
  14761. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14762. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14763. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14764. rootTransformInverse.copy(lastRootTransform).invert();
  14765. if (options.debug) {
  14766. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14767. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14768. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14769. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14770. tileBoxes.matrix.copy(root.matrixWorld);
  14771. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14772. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14773. //boxMap[tileset.root.id].updateWorldMatrix()
  14774. }
  14775. }
  14776. if (this.lastCameraTransform == null) {
  14777. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14778. }
  14779. else {
  14780. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14781. !(camera.aspect == lastCameraAspect);
  14782. if (cameraChanged || ifForce) {
  14783. timer = 0;
  14784. tileset._frameNumber++;
  14785. camera.getWorldPosition(lastCameraPosition);
  14786. this.lastCameraTransform.copy(camera.matrixWorld);
  14787. tilesetUpdate(tileset, renderMap, renderer, camera);
  14788. }
  14789. }
  14790. }/* else{
  14791. console.log('11')
  14792. } */
  14793. },
  14794. dispose: function () {
  14795. disposeFlag = true;
  14796. tileset._destroy();
  14797. while (root.children.length > 0) {
  14798. const obj = root.children[0];
  14799. disposeNode(obj);
  14800. root.remove(obj);
  14801. }
  14802. while (tileBoxes.children.length > 0) {
  14803. const obj = tileBoxes.children[0];
  14804. tileBoxes.remove(obj);
  14805. obj.geometry.dispose();
  14806. obj.material.dispose();
  14807. }
  14808. if (ktx2Loader) {
  14809. ktx2Loader.dispose();
  14810. }
  14811. if (dracoLoader) {
  14812. dracoLoader.dispose();
  14813. }
  14814. },
  14815. },
  14816. };
  14817. });
  14818. }
  14819. }
  14820. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14821. return __awaiter(this, void 0, void 0, function* () {
  14822. return new Promise((resolve, reject) => {
  14823. var _a;
  14824. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14825. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14826. // The computed trasnform already contains the root's transform, so we have to invert it
  14827. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14828. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  14829. // 这句同tile.computedTransform左乘tileTrasnform。 因为tileTrasnform拿不到所以使用modelMatrix。modelMatrix为tileTrasnform左乘rootTransform, 所以再左乘rootTransformInverse
  14830. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  14831. if (shouldRotate) {
  14832. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  14833. }
  14834. gltfLoader.parse(
  14835. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14836. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14837. (gltf) => {
  14838. const tileContent = gltf.scenes[0];
  14839. //tileContent.applyMatrix4(contentTransform);
  14840. tileContent.vertexCount = 0 //xzw add
  14841. tileContent.traverse((object) => {
  14842. if (object.type == "Mesh") {
  14843. const mesh = object;
  14844. //mesh.tileId = tile.id//add
  14845. const originalMaterial = mesh.material;
  14846. const originalMap = originalMaterial.map;
  14847. if (options.material) {
  14848. mesh.material = options.material.clone();
  14849. originalMaterial.dispose();
  14850. }
  14851. else if (options.shading == Shading.FlatTexture) {
  14852. mesh.material = unlitMaterial.clone();
  14853. originalMaterial.dispose();
  14854. }
  14855. if (options.shading != Shading.ShadedNoTexture) {
  14856. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  14857. mesh.material.uniforms.map = { value: originalMap };
  14858. }
  14859. else {
  14860. mesh.material.map = originalMap;
  14861. }
  14862. }
  14863. else {
  14864. if (originalMap) {
  14865. originalMap.dispose();
  14866. }
  14867. mesh.material.map = null;
  14868. }
  14869. if (options.shaderCallback) {
  14870. mesh.onBeforeRender = options.shaderCallback;
  14871. }
  14872. mesh.material.wireframe = options.wireframe;
  14873. if (options.computeNormals) {
  14874. mesh.geometry.computeVertexNormals();
  14875. }
  14876. //xzw add:
  14877. tileContent.vertexCount += mesh.geometry.attributes.position.count
  14878. //------------------add on 2023.1.16----zeg
  14879. mesh.geometry.applyMatrix4(contentTransform)
  14880. if (tile.content.rtcCenter) {
  14881. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  14882. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  14883. } else {
  14884. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  14885. }
  14886. //---------------------
  14887. }
  14888. });
  14889. resolve(tileContent);
  14890. },
  14891. (e) => {
  14892. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  14893. }
  14894. );
  14895. });
  14896. });
  14897. }
  14898. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  14899. const d = {
  14900. rtc_center: tile.content.rtcCenter,
  14901. points: tile.content.attributes.positions,
  14902. intensities: tile.content.attributes.intensity,
  14903. classifications: tile.content.attributes.classification,
  14904. rgb: null,
  14905. rgba: null,
  14906. };
  14907. const { colors } = tile.content.attributes;
  14908. if (colors && colors.size === 3) {
  14909. d.rgb = colors.value;
  14910. }
  14911. if (colors && colors.size === 4) {
  14912. d.rgba = colors.value;
  14913. }
  14914. const geometry = new BufferGeometry();
  14915. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  14916. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  14917. if (d.rgba) {
  14918. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  14919. }
  14920. else if (d.rgb) {
  14921. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  14922. }
  14923. if (d.intensities) {
  14924. geometry.setAttribute('intensity',
  14925. // Handles both 16bit or 8bit intensity values
  14926. new BufferAttribute(d.intensities, 1, true));
  14927. }
  14928. if (d.classifications) {
  14929. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  14930. }
  14931. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  14932. if (d.rtc_center) {
  14933. const c = d.rtc_center;
  14934. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  14935. }
  14936. tileContent.applyMatrix4(contentTransform);
  14937. return tileContent;
  14938. }
  14939. function disposeMaterial(material) {
  14940. var _a, _b, _c, _d;
  14941. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  14942. (_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();
  14943. }
  14944. else if (material.map) {
  14945. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  14946. }
  14947. material.dispose();
  14948. }
  14949. function disposeNode(node) {
  14950. node.traverse((object) => {
  14951. if (object.isMesh) {
  14952. object.geometry.dispose();
  14953. if (object.material.isMaterial) {
  14954. disposeMaterial(object.material);
  14955. }
  14956. else {
  14957. // an array of materials
  14958. for (const material of object.material) {
  14959. disposeMaterial(material);
  14960. }
  14961. }
  14962. }
  14963. });
  14964. for (let i = node.children.length - 1; i >= 0; i--) {
  14965. const obj = node.children[i];
  14966. node.remove(obj);
  14967. }
  14968. }
  14969. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  14970. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  14971. /*
  14972. 关键搜寻:
  14973. Loader3DTiles : const tileset = new Tileset3D
  14974. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  14975. createGLTFNodes(gltfLoader 创建tile
  14976. executeTraversal(root, frameState) 遍历root
  14977. lastRootTransform rootTransformInverse
  14978. tileset._loadTiles 依次加载tiles
  14979. _getPriority 加载优先级 加了一句
  14980. 笔记:
  14981. 主要类:
  14982. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  14983. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  14984. tileset里算的tileTrasnform之后是不会改变的, tile.transform也是,是json里的。
  14985. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  14986. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  14987. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  14988. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  14989. get isVisibleAndInRequestVolume() {
  14990. return this._inRequestVolume; //去掉了_visible ||
  14991. }
  14992. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  14993. 原本会消失的地方虽然不会消失了但一直是模糊的
  14994. */