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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027
  1. import { EventDispatcher, CanvasTexture, LinearFilter, RepeatWrapping, Vector2 as Vector2$1, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1/*, MeshBasicMaterial */, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from '../build/three.module.js';
  2. import { GLTFLoader as GLTFLoader$1 } from '../loaders/GLTFLoader.js';
  3. import { DRACOLoader } from '../loaders/DRACOLoader.js';
  4. import { KTX2Loader } from '../loaders/KTX2Loader.js';
  5. import MeshBasicMaterial from '../../../src/custom/materials/BasicMaterial.js' // xzw改 原先MeshBasicMaterial贴图发黑,可能和贴图有关
  6. let globalThis = window //add 有的app没有globalThis. 2023.1
  7. /*! *****************************************************************************
  8. Copyright (c) Microsoft Corporation.
  9. Permission to use, copy, modify, and/or distribute this software for any
  10. purpose with or without fee is hereby granted.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  12. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  13. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  14. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  15. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  16. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  17. PERFORMANCE OF THIS SOFTWARE.
  18. ***************************************************************************** */
  19. window.visiVertexCount = 0
  20. window.visiGeoCount = 0
  21. const maxVertexVisi = 5e6
  22. const maxTexVisi = 500
  23. function 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. return c
  35. }
  36. function __awaiter(thisArg, _arguments, P, generator) {
  37. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  38. return new (P || (P = Promise))(function (resolve, reject) {
  39. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  40. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  41. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  42. step((generator = generator.apply(thisArg, _arguments || [])).next());
  43. });
  44. }
  45. function assert$7(condition, message) {
  46. if (!condition) {
  47. throw new Error(message || 'loader assertion failed.');
  48. }
  49. }
  50. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  51. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  52. matches$1 && parseFloat(matches$1[1]) || 0;
  53. const VERSION$8 = "3.1.4" ;
  54. function assert$6(condition, message) {
  55. if (!condition) {
  56. throw new Error(message || 'loaders.gl assertion failed.');
  57. }
  58. }
  59. const globals$1 = {
  60. self: typeof self !== 'undefined' && self,
  61. window: typeof window !== 'undefined' && window,
  62. global: typeof global !== 'undefined' && global,
  63. document: typeof document !== 'undefined' && document
  64. };
  65. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  66. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  67. const isWorker = typeof importScripts === 'function';
  68. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  69. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  70. matches && parseFloat(matches[1]) || 0;
  71. function _defineProperty(obj, key, value) {
  72. if (key in obj) {
  73. Object.defineProperty(obj, key, {
  74. value: value,
  75. enumerable: true,
  76. configurable: true,
  77. writable: true
  78. });
  79. } else {
  80. obj[key] = value;
  81. }
  82. return obj;
  83. }
  84. class WorkerJob {
  85. constructor(jobName, workerThread) {
  86. _defineProperty(this, "name", void 0);
  87. _defineProperty(this, "workerThread", void 0);
  88. _defineProperty(this, "isRunning", void 0);
  89. _defineProperty(this, "result", void 0);
  90. _defineProperty(this, "_resolve", void 0);
  91. _defineProperty(this, "_reject", void 0);
  92. this.name = jobName;
  93. this.workerThread = workerThread;
  94. this.isRunning = true;
  95. this._resolve = () => {};
  96. this._reject = () => {};
  97. this.result = new Promise((resolve, reject) => {
  98. this._resolve = resolve;
  99. this._reject = reject;
  100. });
  101. }
  102. postMessage(type, payload) {
  103. this.workerThread.postMessage({
  104. source: 'loaders.gl',
  105. type,
  106. payload
  107. });
  108. }
  109. done(value) {
  110. assert$6(this.isRunning);
  111. this.isRunning = false;
  112. this._resolve(value);
  113. }
  114. error(error) {
  115. assert$6(this.isRunning);
  116. this.isRunning = false;
  117. this._reject(error);
  118. }
  119. }
  120. const workerURLCache = new Map();
  121. function getLoadableWorkerURL(props) {
  122. assert$6(props.source && !props.url || !props.source && props.url);
  123. let workerURL = workerURLCache.get(props.source || props.url);
  124. if (!workerURL) {
  125. if (props.url) {
  126. workerURL = getLoadableWorkerURLFromURL(props.url);
  127. workerURLCache.set(props.url, workerURL);
  128. }
  129. if (props.source) {
  130. workerURL = getLoadableWorkerURLFromSource(props.source);
  131. workerURLCache.set(props.source, workerURL);
  132. }
  133. }
  134. assert$6(workerURL);
  135. return workerURL;
  136. }
  137. function getLoadableWorkerURLFromURL(url) {
  138. if (!url.startsWith('http')) {
  139. return url;
  140. }
  141. const workerSource = buildScriptSource(url);
  142. return getLoadableWorkerURLFromSource(workerSource);
  143. }
  144. function getLoadableWorkerURLFromSource(workerSource) {
  145. const blob = new Blob([workerSource], {
  146. type: 'application/javascript'
  147. });
  148. return URL.createObjectURL(blob);
  149. }
  150. function buildScriptSource(workerUrl) {
  151. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  152. }
  153. function getTransferList(object, recursive = true, transfers) {
  154. const transfersSet = transfers || new Set();
  155. if (!object) ; else if (isTransferable(object)) {
  156. transfersSet.add(object);
  157. } else if (isTransferable(object.buffer)) {
  158. transfersSet.add(object.buffer);
  159. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  160. for (const key in object) {
  161. getTransferList(object[key], recursive, transfersSet);
  162. }
  163. }
  164. return transfers === undefined ? Array.from(transfersSet) : [];
  165. }
  166. function isTransferable(object) {
  167. if (!object) {
  168. return false;
  169. }
  170. if (object instanceof ArrayBuffer) {
  171. return true;
  172. }
  173. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  174. return true;
  175. }
  176. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  177. return true;
  178. }
  179. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  180. return true;
  181. }
  182. return false;
  183. }
  184. const NOOP = () => {};
  185. class WorkerThread {
  186. static isSupported() {
  187. return typeof Worker !== 'undefined';
  188. }
  189. constructor(props) {
  190. _defineProperty(this, "name", void 0);
  191. _defineProperty(this, "source", void 0);
  192. _defineProperty(this, "url", void 0);
  193. _defineProperty(this, "terminated", false);
  194. _defineProperty(this, "worker", void 0);
  195. _defineProperty(this, "onMessage", void 0);
  196. _defineProperty(this, "onError", void 0);
  197. _defineProperty(this, "_loadableURL", '');
  198. const {
  199. name,
  200. source,
  201. url
  202. } = props;
  203. assert$6(source || url);
  204. this.name = name;
  205. this.source = source;
  206. this.url = url;
  207. this.onMessage = NOOP;
  208. this.onError = error => console.log(error);
  209. this.worker = this._createBrowserWorker();
  210. }
  211. destroy() {
  212. this.onMessage = NOOP;
  213. this.onError = NOOP;
  214. this.worker.terminate();
  215. this.terminated = true;
  216. }
  217. get isRunning() {
  218. return Boolean(this.onMessage);
  219. }
  220. postMessage(data, transferList) {
  221. transferList = transferList || getTransferList(data);
  222. this.worker.postMessage(data, transferList);
  223. }
  224. _getErrorFromErrorEvent(event) {
  225. let message = 'Failed to load ';
  226. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  227. if (event.message) {
  228. message += "".concat(event.message, " in ");
  229. }
  230. if (event.lineno) {
  231. message += ":".concat(event.lineno, ":").concat(event.colno);
  232. }
  233. return new Error(message);
  234. }
  235. _createBrowserWorker() {
  236. this._loadableURL = getLoadableWorkerURL({
  237. source: this.source,
  238. url: this.url
  239. });
  240. const worker = new Worker(this._loadableURL, {
  241. name: this.name
  242. });
  243. worker.onmessage = event => {
  244. if (!event.data) {
  245. this.onError(new Error('No data received'));
  246. } else {
  247. this.onMessage(event.data);
  248. }
  249. };
  250. worker.onerror = error => {
  251. this.onError(this._getErrorFromErrorEvent(error));
  252. this.terminated = true;
  253. };
  254. worker.onmessageerror = event => console.error(event);
  255. return worker;
  256. }
  257. }
  258. class WorkerPool {
  259. constructor(props) {
  260. _defineProperty(this, "name", 'unnamed');
  261. _defineProperty(this, "source", void 0);
  262. _defineProperty(this, "url", void 0);
  263. _defineProperty(this, "maxConcurrency", 1);
  264. _defineProperty(this, "maxMobileConcurrency", 1);
  265. _defineProperty(this, "onDebug", () => {});
  266. _defineProperty(this, "reuseWorkers", true);
  267. _defineProperty(this, "props", {});
  268. _defineProperty(this, "jobQueue", []);
  269. _defineProperty(this, "idleQueue", []);
  270. _defineProperty(this, "count", 0);
  271. _defineProperty(this, "isDestroyed", false);
  272. this.source = props.source;
  273. this.url = props.url;
  274. this.setProps(props);
  275. }
  276. destroy() {
  277. this.idleQueue.forEach(worker => worker.destroy());
  278. this.isDestroyed = true;
  279. }
  280. setProps(props) {
  281. this.props = { ...this.props,
  282. ...props
  283. };
  284. if (props.name !== undefined) {
  285. this.name = props.name;
  286. }
  287. if (props.maxConcurrency !== undefined) {
  288. this.maxConcurrency = props.maxConcurrency;
  289. }
  290. if (props.maxMobileConcurrency !== undefined) {
  291. this.maxMobileConcurrency = props.maxMobileConcurrency;
  292. }
  293. if (props.reuseWorkers !== undefined) {
  294. this.reuseWorkers = props.reuseWorkers;
  295. }
  296. if (props.onDebug !== undefined) {
  297. this.onDebug = props.onDebug;
  298. }
  299. }
  300. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  301. const startPromise = new Promise(onStart => {
  302. this.jobQueue.push({
  303. name,
  304. onMessage,
  305. onError,
  306. onStart
  307. });
  308. return this;
  309. });
  310. this._startQueuedJob();
  311. return await startPromise;
  312. }
  313. async _startQueuedJob() {
  314. if (!this.jobQueue.length) {
  315. return;
  316. }
  317. const workerThread = this._getAvailableWorker();
  318. if (!workerThread) {
  319. return;
  320. }
  321. const queuedJob = this.jobQueue.shift();
  322. if (queuedJob) {
  323. this.onDebug({
  324. message: 'Starting job',
  325. name: queuedJob.name,
  326. workerThread,
  327. backlog: this.jobQueue.length
  328. });
  329. const job = new WorkerJob(queuedJob.name, workerThread);
  330. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  331. workerThread.onError = error => queuedJob.onError(job, error);
  332. queuedJob.onStart(job);
  333. try {
  334. await job.result;
  335. } finally {
  336. this.returnWorkerToQueue(workerThread);
  337. }
  338. }
  339. }
  340. returnWorkerToQueue(worker) {
  341. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  342. if (shouldDestroyWorker) {
  343. worker.destroy();
  344. this.count--;
  345. } else {
  346. this.idleQueue.push(worker);
  347. }
  348. if (!this.isDestroyed) {
  349. this._startQueuedJob();
  350. }
  351. }
  352. _getAvailableWorker() {
  353. if (this.idleQueue.length > 0) {
  354. return this.idleQueue.shift() || null;
  355. }
  356. if (this.count < this._getMaxConcurrency()) {
  357. this.count++;
  358. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  359. return new WorkerThread({
  360. name,
  361. source: this.source,
  362. url: this.url
  363. });
  364. }
  365. return null;
  366. }
  367. _getMaxConcurrency() {
  368. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  369. }
  370. }
  371. const DEFAULT_PROPS$3 = {
  372. maxConcurrency: 3,
  373. maxMobileConcurrency: 1,
  374. onDebug: () => {},
  375. reuseWorkers: true
  376. };
  377. class WorkerFarm {
  378. static isSupported() {
  379. return WorkerThread.isSupported();
  380. }
  381. static getWorkerFarm(props = {}) {
  382. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  383. WorkerFarm._workerFarm.setProps(props);
  384. return WorkerFarm._workerFarm;
  385. }
  386. constructor(props) {
  387. _defineProperty(this, "props", void 0);
  388. _defineProperty(this, "workerPools", new Map());
  389. this.props = { ...DEFAULT_PROPS$3
  390. };
  391. this.setProps(props);
  392. this.workerPools = new Map();
  393. }
  394. destroy() {
  395. for (const workerPool of this.workerPools.values()) {
  396. workerPool.destroy();
  397. }
  398. }
  399. setProps(props) {
  400. this.props = { ...this.props,
  401. ...props
  402. };
  403. for (const workerPool of this.workerPools.values()) {
  404. workerPool.setProps(this._getWorkerPoolProps());
  405. }
  406. }
  407. getWorkerPool(options) {
  408. const {
  409. name,
  410. source,
  411. url
  412. } = options;
  413. let workerPool = this.workerPools.get(name);
  414. if (!workerPool) {
  415. workerPool = new WorkerPool({
  416. name,
  417. source,
  418. url
  419. });
  420. workerPool.setProps(this._getWorkerPoolProps());
  421. this.workerPools.set(name, workerPool);
  422. }
  423. return workerPool;
  424. }
  425. _getWorkerPoolProps() {
  426. return {
  427. maxConcurrency: this.props.maxConcurrency,
  428. maxMobileConcurrency: this.props.maxMobileConcurrency,
  429. reuseWorkers: this.props.reuseWorkers,
  430. onDebug: this.props.onDebug
  431. };
  432. }
  433. }
  434. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  435. const NPM_TAG = 'latest';
  436. function getWorkerURL(worker, options = {}) {
  437. const workerOptions = options[worker.id] || {};
  438. const workerFile = "".concat(worker.id, "-worker.js");
  439. let url = workerOptions.workerUrl;
  440. if (!url && worker.id === 'compression') {
  441. url = options.workerUrl;
  442. }
  443. if (options._workerType === 'test') {
  444. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  445. }
  446. if (!url) {
  447. let version = worker.version;
  448. if (version === 'latest') {
  449. version = NPM_TAG;
  450. }
  451. const versionTag = version ? "@".concat(version) : '';
  452. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  453. }
  454. assert$6(url);
  455. return url;
  456. }
  457. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  458. assert$6(worker, 'no worker provided');
  459. const workerVersion = worker.version;
  460. if (!coreVersion || !workerVersion) {
  461. return false;
  462. }
  463. return true;
  464. }
  465. var ChildProcessProxy = {};
  466. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  467. 'default': ChildProcessProxy
  468. }));
  469. const VERSION$7 = "3.1.4" ;
  470. const loadLibraryPromises = {};
  471. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  472. if (moduleName) {
  473. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  474. }
  475. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  476. return await loadLibraryPromises[libraryUrl];
  477. }
  478. function getLibraryUrl(library, moduleName, options) {
  479. if (library.startsWith('http')) {
  480. return library;
  481. }
  482. const modules = options.modules || {};
  483. if (modules[library]) {
  484. return modules[library];
  485. }
  486. if (!isBrowser$1) {
  487. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  488. }
  489. if (options.CDN) {
  490. assert$6(options.CDN.startsWith('http'));
  491. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  492. }
  493. if (isWorker) {
  494. return "../src/libs/".concat(library);
  495. }
  496. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  497. }
  498. async function loadLibraryFromFile(libraryUrl) {
  499. if (libraryUrl.endsWith('wasm')) {
  500. const response = await fetch(libraryUrl);
  501. return await response.arrayBuffer();
  502. }
  503. if (!isBrowser$1) {
  504. try {
  505. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  506. } catch {
  507. return null;
  508. }
  509. }
  510. if (isWorker) {
  511. return importScripts(libraryUrl);
  512. }
  513. const response = await fetch(libraryUrl);
  514. const scriptSource = await response.text();
  515. return loadLibraryFromString(scriptSource, libraryUrl);
  516. }
  517. function loadLibraryFromString(scriptSource, id) {
  518. if (!isBrowser$1) {
  519. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  520. }
  521. if (isWorker) {
  522. eval.call(global_, scriptSource);
  523. return null;
  524. }
  525. const script = document.createElement('script');
  526. script.id = id;
  527. try {
  528. script.appendChild(document.createTextNode(scriptSource));
  529. } catch (e) {
  530. script.text = scriptSource;
  531. }
  532. document.body.appendChild(script);
  533. return null;
  534. }
  535. function canParseWithWorker(loader, options) {
  536. if (!WorkerFarm.isSupported()) {
  537. return false;
  538. }
  539. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  540. }
  541. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  542. const name = loader.id;
  543. const url = getWorkerURL(loader, options);
  544. const workerFarm = WorkerFarm.getWorkerFarm(options);
  545. const workerPool = workerFarm.getWorkerPool({
  546. name,
  547. url
  548. });
  549. options = JSON.parse(JSON.stringify(options));
  550. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  551. job.postMessage('process', {
  552. input: data,
  553. options
  554. });
  555. const result = await job.result;
  556. return await result.result;
  557. }
  558. async function onMessage(parseOnMainThread, job, type, payload) {
  559. switch (type) {
  560. case 'done':
  561. job.done(payload);
  562. break;
  563. case 'error':
  564. job.error(new Error(payload.error));
  565. break;
  566. case 'process':
  567. const {
  568. id,
  569. input,
  570. options
  571. } = payload;
  572. try {
  573. const result = await parseOnMainThread(input, options);
  574. job.postMessage('done', {
  575. id,
  576. result
  577. });
  578. } catch (error) {
  579. const message = error instanceof Error ? error.message : 'unknown error';
  580. job.postMessage('error', {
  581. id,
  582. error: message
  583. });
  584. }
  585. break;
  586. default:
  587. console.warn("parse-with-worker unknown message ".concat(type));
  588. }
  589. }
  590. function getFirstCharacters$1(data, length = 5) {
  591. if (typeof data === 'string') {
  592. return data.slice(0, length);
  593. } else if (ArrayBuffer.isView(data)) {
  594. return getMagicString$3(data.buffer, data.byteOffset, length);
  595. } else if (data instanceof ArrayBuffer) {
  596. const byteOffset = 0;
  597. return getMagicString$3(data, byteOffset, length);
  598. }
  599. return '';
  600. }
  601. function getMagicString$3(arrayBuffer, byteOffset, length) {
  602. if (arrayBuffer.byteLength <= byteOffset + length) {
  603. return '';
  604. }
  605. const dataView = new DataView(arrayBuffer);
  606. let magic = '';
  607. for (let i = 0; i < length; i++) {
  608. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  609. }
  610. return magic;
  611. }
  612. function parseJSON(string) {
  613. try {
  614. return JSON.parse(string);
  615. } catch (_) {
  616. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  617. }
  618. }
  619. function isBuffer$1(value) {
  620. return value && typeof value === 'object' && value.isBuffer;
  621. }
  622. function bufferToArrayBuffer(buffer) {
  623. if (isBuffer$1(buffer)) {
  624. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  625. return typedArray.slice().buffer;
  626. }
  627. return buffer;
  628. }
  629. function toArrayBuffer(data) {
  630. if (isBuffer$1(data)) {
  631. return bufferToArrayBuffer(data);
  632. }
  633. if (data instanceof ArrayBuffer) {
  634. return data;
  635. }
  636. if (ArrayBuffer.isView(data)) {
  637. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  638. return data.buffer;
  639. }
  640. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  641. }
  642. if (typeof data === 'string') {
  643. const text = data;
  644. const uint8Array = new TextEncoder().encode(text);
  645. return uint8Array.buffer;
  646. }
  647. if (data && typeof data === 'object' && data._toArrayBuffer) {
  648. return data._toArrayBuffer();
  649. }
  650. throw new Error('toArrayBuffer');
  651. }
  652. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  653. byteLength = byteLength || arrayBuffer1.byteLength;
  654. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  655. return false;
  656. }
  657. const array1 = new Uint8Array(arrayBuffer1);
  658. const array2 = new Uint8Array(arrayBuffer2);
  659. for (let i = 0; i < array1.length; ++i) {
  660. if (array1[i] !== array2[i]) {
  661. return false;
  662. }
  663. }
  664. return true;
  665. }
  666. function concatenateArrayBuffers(...sources) {
  667. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  668. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  669. const result = new Uint8Array(byteLength);
  670. let offset = 0;
  671. for (const sourceArray of sourceArrays) {
  672. result.set(sourceArray, offset);
  673. offset += sourceArray.byteLength;
  674. }
  675. return result.buffer;
  676. }
  677. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  678. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  679. const arrayCopy = new Uint8Array(subArray);
  680. return arrayCopy.buffer;
  681. }
  682. function padToNBytes(byteLength, padding) {
  683. assert$7(byteLength >= 0);
  684. assert$7(padding > 0);
  685. return byteLength + (padding - 1) & ~(padding - 1);
  686. }
  687. function copyToArray(source, target, targetOffset) {
  688. let sourceArray;
  689. if (source instanceof ArrayBuffer) {
  690. sourceArray = new Uint8Array(source);
  691. } else {
  692. const srcByteOffset = source.byteOffset;
  693. const srcByteLength = source.byteLength;
  694. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  695. }
  696. target.set(sourceArray, targetOffset);
  697. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  698. }
  699. async function concatenateArrayBuffersAsync(asyncIterator) {
  700. const arrayBuffers = [];
  701. for await (const chunk of asyncIterator) {
  702. arrayBuffers.push(chunk);
  703. }
  704. return concatenateArrayBuffers(...arrayBuffers);
  705. }
  706. function getHiResTimestamp$1() {
  707. let timestamp;
  708. if (typeof window !== 'undefined' && window.performance) {
  709. timestamp = window.performance.now();
  710. } else if (typeof process !== 'undefined' && process.hrtime) {
  711. const timeParts = process.hrtime();
  712. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  713. } else {
  714. timestamp = Date.now();
  715. }
  716. return timestamp;
  717. }
  718. class Stat {
  719. constructor(name, type) {
  720. _defineProperty(this, "name", void 0);
  721. _defineProperty(this, "type", void 0);
  722. _defineProperty(this, "sampleSize", 1);
  723. _defineProperty(this, "time", void 0);
  724. _defineProperty(this, "count", void 0);
  725. _defineProperty(this, "samples", void 0);
  726. _defineProperty(this, "lastTiming", void 0);
  727. _defineProperty(this, "lastSampleTime", void 0);
  728. _defineProperty(this, "lastSampleCount", void 0);
  729. _defineProperty(this, "_count", 0);
  730. _defineProperty(this, "_time", 0);
  731. _defineProperty(this, "_samples", 0);
  732. _defineProperty(this, "_startTime", 0);
  733. _defineProperty(this, "_timerPending", false);
  734. this.name = name;
  735. this.type = type;
  736. this.reset();
  737. }
  738. setSampleSize(samples) {
  739. this.sampleSize = samples;
  740. return this;
  741. }
  742. incrementCount() {
  743. this.addCount(1);
  744. return this;
  745. }
  746. decrementCount() {
  747. this.subtractCount(1);
  748. return this;
  749. }
  750. addCount(value) {
  751. this._count += value;
  752. this._samples++;
  753. this._checkSampling();
  754. return this;
  755. }
  756. subtractCount(value) {
  757. this._count -= value;
  758. this._samples++;
  759. this._checkSampling();
  760. return this;
  761. }
  762. addTime(time) {
  763. this._time += time;
  764. this.lastTiming = time;
  765. this._samples++;
  766. this._checkSampling();
  767. return this;
  768. }
  769. timeStart() {
  770. this._startTime = getHiResTimestamp$1();
  771. this._timerPending = true;
  772. return this;
  773. }
  774. timeEnd() {
  775. if (!this._timerPending) {
  776. return this;
  777. }
  778. this.addTime(getHiResTimestamp$1() - this._startTime);
  779. this._timerPending = false;
  780. this._checkSampling();
  781. return this;
  782. }
  783. getSampleAverageCount() {
  784. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  785. }
  786. getSampleAverageTime() {
  787. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  788. }
  789. getSampleHz() {
  790. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  791. }
  792. getAverageCount() {
  793. return this.samples > 0 ? this.count / this.samples : 0;
  794. }
  795. getAverageTime() {
  796. return this.samples > 0 ? this.time / this.samples : 0;
  797. }
  798. getHz() {
  799. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  800. }
  801. reset() {
  802. this.time = 0;
  803. this.count = 0;
  804. this.samples = 0;
  805. this.lastTiming = 0;
  806. this.lastSampleTime = 0;
  807. this.lastSampleCount = 0;
  808. this._count = 0;
  809. this._time = 0;
  810. this._samples = 0;
  811. this._startTime = 0;
  812. this._timerPending = false;
  813. return this;
  814. }
  815. _checkSampling() {
  816. if (this._samples === this.sampleSize) {
  817. this.lastSampleTime = this._time;
  818. this.lastSampleCount = this._count;
  819. this.count += this._count;
  820. this.time += this._time;
  821. this.samples += this._samples;
  822. this._time = 0;
  823. this._count = 0;
  824. this._samples = 0;
  825. }
  826. }
  827. }
  828. class Stats {
  829. constructor(options) {
  830. _defineProperty(this, "id", void 0);
  831. _defineProperty(this, "stats", {});
  832. this.id = options.id;
  833. this.stats = {};
  834. this._initializeStats(options.stats);
  835. Object.seal(this);
  836. }
  837. get(name) {
  838. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  839. return this._getOrCreate({
  840. name,
  841. type
  842. });
  843. }
  844. get size() {
  845. return Object.keys(this.stats).length;
  846. }
  847. reset() {
  848. for (const key in this.stats) {
  849. this.stats[key].reset();
  850. }
  851. return this;
  852. }
  853. forEach(fn) {
  854. for (const key in this.stats) {
  855. fn(this.stats[key]);
  856. }
  857. }
  858. getTable() {
  859. const table = {};
  860. this.forEach(stat => {
  861. table[stat.name] = {
  862. time: stat.time || 0,
  863. count: stat.count || 0,
  864. average: stat.getAverageTime() || 0,
  865. hz: stat.getHz() || 0
  866. };
  867. });
  868. return table;
  869. }
  870. _initializeStats() {
  871. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  872. stats.forEach(stat => this._getOrCreate(stat));
  873. }
  874. _getOrCreate(stat) {
  875. if (!stat || !stat.name) {
  876. return null;
  877. }
  878. const {
  879. name,
  880. type
  881. } = stat;
  882. if (!this.stats[name]) {
  883. if (stat instanceof Stat) {
  884. this.stats[name] = stat;
  885. } else {
  886. this.stats[name] = new Stat(name, type);
  887. }
  888. }
  889. return this.stats[name];
  890. }
  891. }
  892. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  893. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  894. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  895. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  896. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  897. const DEFAULT_PROPS$2 = {
  898. id: 'request-scheduler',
  899. throttleRequests: true,
  900. maxRequests: 6
  901. };
  902. class RequestScheduler {
  903. constructor(props = {}) {
  904. _defineProperty(this, "props", void 0);
  905. _defineProperty(this, "stats", void 0);
  906. _defineProperty(this, "activeRequestCount", 0);
  907. _defineProperty(this, "requestQueue", []);
  908. _defineProperty(this, "requestMap", new Map());
  909. _defineProperty(this, "deferredUpdate", null);
  910. this.props = { ...DEFAULT_PROPS$2,
  911. ...props
  912. };
  913. this.stats = new Stats({
  914. id: this.props.id
  915. });
  916. this.stats.get(STAT_QUEUED_REQUESTS);
  917. this.stats.get(STAT_ACTIVE_REQUESTS);
  918. this.stats.get(STAT_CANCELLED_REQUESTS);
  919. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  920. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  921. }
  922. scheduleRequest(handle, getPriority = () => 0) {
  923. if (!this.props.throttleRequests) {
  924. return Promise.resolve({
  925. done: () => {}
  926. });
  927. }
  928. if (this.requestMap.has(handle)) {
  929. return this.requestMap.get(handle);
  930. }
  931. const request = {
  932. handle,
  933. priority: 0,
  934. getPriority
  935. };
  936. const promise = new Promise(resolve => {
  937. request.resolve = resolve;
  938. return request;
  939. });
  940. this.requestQueue.push(request);
  941. this.requestMap.set(handle, promise);
  942. this._issueNewRequests();
  943. return promise;
  944. }
  945. _issueRequest(request) {
  946. const {
  947. handle,
  948. resolve
  949. } = request;
  950. let isDone = false;
  951. const done = () => {
  952. if (!isDone) {
  953. isDone = true;
  954. this.requestMap.delete(handle);
  955. this.activeRequestCount--;
  956. this._issueNewRequests();
  957. }
  958. };
  959. this.activeRequestCount++;
  960. return resolve ? resolve({
  961. done
  962. }) : Promise.resolve({
  963. done
  964. });
  965. }
  966. _issueNewRequests() {
  967. if (!this.deferredUpdate) {
  968. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  969. }
  970. }
  971. _issueNewRequestsAsync() {
  972. this.deferredUpdate = null;
  973. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  974. if (freeSlots === 0) {
  975. return;
  976. }
  977. this._updateAllRequests();
  978. for (let i = 0; i < freeSlots; ++i) {
  979. const request = this.requestQueue.shift();
  980. if (request) {
  981. this._issueRequest(request);
  982. }
  983. }
  984. }
  985. _updateAllRequests() {
  986. const requestQueue = this.requestQueue;
  987. for (let i = 0; i < requestQueue.length; ++i) {
  988. const request = requestQueue[i];
  989. if (!this._updateRequest(request)) {
  990. requestQueue.splice(i, 1);
  991. this.requestMap.delete(request.handle);
  992. i--;
  993. }
  994. }
  995. requestQueue.sort((a, b) => a.priority - b.priority);
  996. }
  997. _updateRequest(request) {
  998. request.priority = request.getPriority(request.handle);
  999. if (request.priority < 0) {
  1000. request.resolve(null);
  1001. return false;
  1002. }
  1003. return true;
  1004. }
  1005. }
  1006. let pathPrefix = '';
  1007. const fileAliases = {};
  1008. function resolvePath(filename) {
  1009. for (const alias in fileAliases) {
  1010. if (filename.startsWith(alias)) {
  1011. const replacement = fileAliases[alias];
  1012. filename = filename.replace(alias, replacement);
  1013. }
  1014. }
  1015. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1016. filename = "".concat(pathPrefix).concat(filename);
  1017. }
  1018. return filename;
  1019. }
  1020. function filename(url) {
  1021. const slashIndex = url && url.lastIndexOf('/');
  1022. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1023. }
  1024. function dirname(url) {
  1025. const slashIndex = url && url.lastIndexOf('/');
  1026. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1027. }
  1028. const isBoolean = x => typeof x === 'boolean';
  1029. const isFunction = x => typeof x === 'function';
  1030. const isObject = x => x !== null && typeof x === 'object';
  1031. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1032. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1033. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1034. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1035. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1036. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1037. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1038. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1039. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1040. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1041. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1042. function parseMIMEType(mimeString) {
  1043. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1044. if (matches) {
  1045. return matches[1];
  1046. }
  1047. return mimeString;
  1048. }
  1049. function parseMIMETypeFromURL(url) {
  1050. const matches = DATA_URL_PATTERN.exec(url);
  1051. if (matches) {
  1052. return matches[1];
  1053. }
  1054. return '';
  1055. }
  1056. const QUERY_STRING_PATTERN = /\?.*/;
  1057. function getResourceUrlAndType(resource) {
  1058. if (isResponse(resource)) {
  1059. const url = stripQueryString(resource.url || '');
  1060. const contentTypeHeader = resource.headers.get('content-type') || '';
  1061. return {
  1062. url,
  1063. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1064. };
  1065. }
  1066. if (isBlob(resource)) {
  1067. return {
  1068. url: stripQueryString(resource.name || ''),
  1069. type: resource.type || ''
  1070. };
  1071. }
  1072. if (typeof resource === 'string') {
  1073. return {
  1074. url: stripQueryString(resource),
  1075. type: parseMIMETypeFromURL(resource)
  1076. };
  1077. }
  1078. return {
  1079. url: '',
  1080. type: ''
  1081. };
  1082. }
  1083. function getResourceContentLength(resource) {
  1084. if (isResponse(resource)) {
  1085. return resource.headers['content-length'] || -1;
  1086. }
  1087. if (isBlob(resource)) {
  1088. return resource.size;
  1089. }
  1090. if (typeof resource === 'string') {
  1091. return resource.length;
  1092. }
  1093. if (resource instanceof ArrayBuffer) {
  1094. return resource.byteLength;
  1095. }
  1096. if (ArrayBuffer.isView(resource)) {
  1097. return resource.byteLength;
  1098. }
  1099. return -1;
  1100. }
  1101. function stripQueryString(url) {
  1102. return url.replace(QUERY_STRING_PATTERN, '');
  1103. }
  1104. async function makeResponse(resource) {
  1105. if (isResponse(resource)) {
  1106. return resource;
  1107. }
  1108. const headers = {};
  1109. const contentLength = getResourceContentLength(resource);
  1110. if (contentLength >= 0) {
  1111. headers['content-length'] = String(contentLength);
  1112. }
  1113. const {
  1114. url,
  1115. type
  1116. } = getResourceUrlAndType(resource);
  1117. if (type) {
  1118. headers['content-type'] = type;
  1119. }
  1120. const initialDataUrl = await getInitialDataUrl(resource);
  1121. if (initialDataUrl) {
  1122. headers['x-first-bytes'] = initialDataUrl;
  1123. }
  1124. if (typeof resource === 'string') {
  1125. resource = new TextEncoder().encode(resource);
  1126. }
  1127. const response = new Response(resource, {
  1128. headers
  1129. });
  1130. Object.defineProperty(response, 'url', {
  1131. value: url
  1132. });
  1133. return response;
  1134. }
  1135. async function checkResponse(response) {
  1136. if (!response.ok) {
  1137. const message = await getResponseError(response);
  1138. throw new Error(message);
  1139. }
  1140. }
  1141. async function getResponseError(response) {
  1142. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1143. try {
  1144. const contentType = response.headers.get('Content-Type');
  1145. let text = response.statusText;
  1146. if (contentType.includes('application/json')) {
  1147. text += " ".concat(await response.text());
  1148. }
  1149. message += text;
  1150. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1151. } catch (error) {}
  1152. return message;
  1153. }
  1154. async function getInitialDataUrl(resource) {
  1155. const INITIAL_DATA_LENGTH = 5;
  1156. if (typeof resource === 'string') {
  1157. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1158. }
  1159. if (resource instanceof Blob) {
  1160. const blobSlice = resource.slice(0, 5);
  1161. return await new Promise(resolve => {
  1162. const reader = new FileReader();
  1163. reader.onload = event => {
  1164. var _event$target;
  1165. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1166. };
  1167. reader.readAsDataURL(blobSlice);
  1168. });
  1169. }
  1170. if (resource instanceof ArrayBuffer) {
  1171. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1172. const base64 = arrayBufferToBase64(slice);
  1173. return "data:base64,".concat(base64);
  1174. }
  1175. return null;
  1176. }
  1177. function arrayBufferToBase64(buffer) {
  1178. let binary = '';
  1179. const bytes = new Uint8Array(buffer);
  1180. for (let i = 0; i < bytes.byteLength; i++) {
  1181. binary += String.fromCharCode(bytes[i]);
  1182. }
  1183. return btoa(binary);
  1184. }
  1185. async function fetchFile(url, options) {
  1186. if (typeof url === 'string') {
  1187. url = resolvePath(url);
  1188. let fetchOptions = options;
  1189. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1190. fetchOptions = options.fetch;
  1191. }
  1192. return await fetch(url, fetchOptions);
  1193. }
  1194. return await makeResponse(url);
  1195. }
  1196. function isElectron(mockUserAgent) {
  1197. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1198. return true;
  1199. }
  1200. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1201. return true;
  1202. }
  1203. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1204. const userAgent = mockUserAgent || realUserAgent;
  1205. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1206. return true;
  1207. }
  1208. return false;
  1209. }
  1210. function isBrowser() {
  1211. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1212. return !isNode || isElectron();
  1213. }
  1214. const globals = {
  1215. self: typeof self !== 'undefined' && self,
  1216. window: typeof window !== 'undefined' && window,
  1217. global: typeof global !== 'undefined' && global,
  1218. document: typeof document !== 'undefined' && document,
  1219. process: typeof process === 'object' && process
  1220. };
  1221. const window_ = globals.window || globals.self || globals.global;
  1222. const process_ = globals.process || {};
  1223. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1224. isBrowser();
  1225. function getStorage(type) {
  1226. try {
  1227. const storage = window[type];
  1228. const x = '__storage_test__';
  1229. storage.setItem(x, x);
  1230. storage.removeItem(x);
  1231. return storage;
  1232. } catch (e) {
  1233. return null;
  1234. }
  1235. }
  1236. class LocalStorage {
  1237. constructor(id) {
  1238. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1239. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1240. _defineProperty(this, "storage", void 0);
  1241. _defineProperty(this, "id", void 0);
  1242. _defineProperty(this, "config", {});
  1243. this.storage = getStorage(type);
  1244. this.id = id;
  1245. this.config = {};
  1246. Object.assign(this.config, defaultSettings);
  1247. this._loadConfiguration();
  1248. }
  1249. getConfiguration() {
  1250. return this.config;
  1251. }
  1252. setConfiguration(configuration) {
  1253. this.config = {};
  1254. return this.updateConfiguration(configuration);
  1255. }
  1256. updateConfiguration(configuration) {
  1257. Object.assign(this.config, configuration);
  1258. if (this.storage) {
  1259. const serialized = JSON.stringify(this.config);
  1260. this.storage.setItem(this.id, serialized);
  1261. }
  1262. return this;
  1263. }
  1264. _loadConfiguration() {
  1265. let configuration = {};
  1266. if (this.storage) {
  1267. const serializedConfiguration = this.storage.getItem(this.id);
  1268. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1269. }
  1270. Object.assign(this.config, configuration);
  1271. return this;
  1272. }
  1273. }
  1274. function formatTime(ms) {
  1275. let formatted;
  1276. if (ms < 10) {
  1277. formatted = "".concat(ms.toFixed(2), "ms");
  1278. } else if (ms < 100) {
  1279. formatted = "".concat(ms.toFixed(1), "ms");
  1280. } else if (ms < 1000) {
  1281. formatted = "".concat(ms.toFixed(0), "ms");
  1282. } else {
  1283. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1284. }
  1285. return formatted;
  1286. }
  1287. function leftPad(string) {
  1288. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1289. const padLength = Math.max(length - string.length, 0);
  1290. return "".concat(' '.repeat(padLength)).concat(string);
  1291. }
  1292. function formatImage(image, message, scale) {
  1293. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1294. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1295. if (image.width > maxWidth) {
  1296. scale = Math.min(scale, maxWidth / image.width);
  1297. }
  1298. const width = image.width * scale;
  1299. const height = image.height * scale;
  1300. 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('');
  1301. return ["".concat(message, " %c+"), style];
  1302. }
  1303. let COLOR;
  1304. (function (COLOR) {
  1305. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1306. COLOR[COLOR["RED"] = 31] = "RED";
  1307. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1308. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1309. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1310. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1311. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1312. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1313. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1314. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1315. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1316. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1317. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1318. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1319. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1320. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1321. })(COLOR || (COLOR = {}));
  1322. function getColor(color) {
  1323. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1324. }
  1325. function addColor(string, color, background) {
  1326. if (!isBrowser && typeof string === 'string') {
  1327. if (color) {
  1328. color = getColor(color);
  1329. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1330. }
  1331. if (background) {
  1332. color = getColor(background);
  1333. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1334. }
  1335. }
  1336. return string;
  1337. }
  1338. function autobind(obj) {
  1339. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1340. const proto = Object.getPrototypeOf(obj);
  1341. const propNames = Object.getOwnPropertyNames(proto);
  1342. for (const key of propNames) {
  1343. if (typeof obj[key] === 'function') {
  1344. if (!predefined.find(name => key === name)) {
  1345. obj[key] = obj[key].bind(obj);
  1346. }
  1347. }
  1348. }
  1349. }
  1350. function assert$5(condition, message) {
  1351. if (!condition) {
  1352. throw new Error(message || 'Assertion failed');
  1353. }
  1354. }
  1355. function getHiResTimestamp() {
  1356. let timestamp;
  1357. if (isBrowser && 'performance' in window_) {
  1358. var _window$performance, _window$performance$n;
  1359. 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);
  1360. } else if ('hrtime' in process_) {
  1361. var _process$hrtime;
  1362. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1363. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1364. } else {
  1365. timestamp = Date.now();
  1366. }
  1367. return timestamp;
  1368. }
  1369. const originalConsole = {
  1370. debug: isBrowser ? console.debug || console.log : console.log,
  1371. log: console.log,
  1372. info: console.info,
  1373. warn: console.warn,
  1374. error: console.error
  1375. };
  1376. const DEFAULT_SETTINGS = {
  1377. enabled: true,
  1378. level: 0
  1379. };
  1380. function noop$1() {}
  1381. const cache = {};
  1382. const ONCE = {
  1383. once: true
  1384. };
  1385. class Log {
  1386. constructor() {
  1387. let {
  1388. id
  1389. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1390. id: ''
  1391. };
  1392. _defineProperty(this, "id", void 0);
  1393. _defineProperty(this, "VERSION", VERSION$6);
  1394. _defineProperty(this, "_startTs", getHiResTimestamp());
  1395. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1396. _defineProperty(this, "_storage", void 0);
  1397. _defineProperty(this, "userData", {});
  1398. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1399. this.id = id;
  1400. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1401. this.userData = {};
  1402. this.timeStamp("".concat(this.id, " started"));
  1403. autobind(this);
  1404. Object.seal(this);
  1405. }
  1406. set level(newLevel) {
  1407. this.setLevel(newLevel);
  1408. }
  1409. get level() {
  1410. return this.getLevel();
  1411. }
  1412. isEnabled() {
  1413. return this._storage.config.enabled;
  1414. }
  1415. getLevel() {
  1416. return this._storage.config.level;
  1417. }
  1418. getTotal() {
  1419. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1420. }
  1421. getDelta() {
  1422. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1423. }
  1424. set priority(newPriority) {
  1425. this.level = newPriority;
  1426. }
  1427. get priority() {
  1428. return this.level;
  1429. }
  1430. getPriority() {
  1431. return this.level;
  1432. }
  1433. enable() {
  1434. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1435. this._storage.updateConfiguration({
  1436. enabled
  1437. });
  1438. return this;
  1439. }
  1440. setLevel(level) {
  1441. this._storage.updateConfiguration({
  1442. level
  1443. });
  1444. return this;
  1445. }
  1446. get(setting) {
  1447. return this._storage.config[setting];
  1448. }
  1449. set(setting, value) {
  1450. this._storage.updateConfiguration({
  1451. [setting]: value
  1452. });
  1453. }
  1454. settings() {
  1455. if (console.table) {
  1456. console.table(this._storage.config);
  1457. } else {
  1458. console.log(this._storage.config);
  1459. }
  1460. }
  1461. assert(condition, message) {
  1462. assert$5(condition, message);
  1463. }
  1464. warn(message) {
  1465. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1466. }
  1467. error(message) {
  1468. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1469. }
  1470. deprecated(oldUsage, newUsage) {
  1471. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1472. }
  1473. removed(oldUsage, newUsage) {
  1474. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1475. }
  1476. probe(logLevel, message) {
  1477. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1478. time: true,
  1479. once: true
  1480. });
  1481. }
  1482. log(logLevel, message) {
  1483. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1484. }
  1485. info(logLevel, message) {
  1486. return this._getLogFunction(logLevel, message, console.info, arguments);
  1487. }
  1488. once(logLevel, message) {
  1489. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1490. args[_key - 2] = arguments[_key];
  1491. }
  1492. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1493. }
  1494. table(logLevel, table, columns) {
  1495. if (table) {
  1496. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1497. tag: getTableHeader(table)
  1498. });
  1499. }
  1500. return noop$1;
  1501. }
  1502. image(_ref) {
  1503. let {
  1504. logLevel,
  1505. priority,
  1506. image,
  1507. message = '',
  1508. scale = 1
  1509. } = _ref;
  1510. if (!this._shouldLog(logLevel || priority)) {
  1511. return noop$1;
  1512. }
  1513. return isBrowser ? logImageInBrowser({
  1514. image,
  1515. message,
  1516. scale
  1517. }) : logImageInNode({
  1518. image,
  1519. message,
  1520. scale
  1521. });
  1522. }
  1523. time(logLevel, message) {
  1524. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1525. }
  1526. timeEnd(logLevel, message) {
  1527. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1528. }
  1529. timeStamp(logLevel, message) {
  1530. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1531. }
  1532. group(logLevel, message) {
  1533. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1534. collapsed: false
  1535. };
  1536. const options = normalizeArguments({
  1537. logLevel,
  1538. message,
  1539. opts
  1540. });
  1541. const {
  1542. collapsed
  1543. } = opts;
  1544. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1545. return this._getLogFunction(options);
  1546. }
  1547. groupCollapsed(logLevel, message) {
  1548. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1549. return this.group(logLevel, message, Object.assign({}, opts, {
  1550. collapsed: true
  1551. }));
  1552. }
  1553. groupEnd(logLevel) {
  1554. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1555. }
  1556. withGroup(logLevel, message, func) {
  1557. this.group(logLevel, message)();
  1558. try {
  1559. func();
  1560. } finally {
  1561. this.groupEnd(logLevel)();
  1562. }
  1563. }
  1564. trace() {
  1565. if (console.trace) {
  1566. console.trace();
  1567. }
  1568. }
  1569. _shouldLog(logLevel) {
  1570. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1571. }
  1572. _getLogFunction(logLevel, message, method, args, opts) {
  1573. if (this._shouldLog(logLevel)) {
  1574. opts = normalizeArguments({
  1575. logLevel,
  1576. message,
  1577. args,
  1578. opts
  1579. });
  1580. method = method || opts.method;
  1581. assert$5(method);
  1582. opts.total = this.getTotal();
  1583. opts.delta = this.getDelta();
  1584. this._deltaTs = getHiResTimestamp();
  1585. const tag = opts.tag || opts.message;
  1586. if (opts.once) {
  1587. if (!cache[tag]) {
  1588. cache[tag] = getHiResTimestamp();
  1589. } else {
  1590. return noop$1;
  1591. }
  1592. }
  1593. message = decorateMessage(this.id, opts.message, opts);
  1594. return method.bind(console, message, ...opts.args);
  1595. }
  1596. return noop$1;
  1597. }
  1598. }
  1599. _defineProperty(Log, "VERSION", VERSION$6);
  1600. function normalizeLogLevel(logLevel) {
  1601. if (!logLevel) {
  1602. return 0;
  1603. }
  1604. let resolvedLevel;
  1605. switch (typeof logLevel) {
  1606. case 'number':
  1607. resolvedLevel = logLevel;
  1608. break;
  1609. case 'object':
  1610. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1611. break;
  1612. default:
  1613. return 0;
  1614. }
  1615. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1616. return resolvedLevel;
  1617. }
  1618. function normalizeArguments(opts) {
  1619. const {
  1620. logLevel,
  1621. message
  1622. } = opts;
  1623. opts.logLevel = normalizeLogLevel(logLevel);
  1624. const args = opts.args ? Array.from(opts.args) : [];
  1625. while (args.length && args.shift() !== message) {}
  1626. switch (typeof logLevel) {
  1627. case 'string':
  1628. case 'function':
  1629. if (message !== undefined) {
  1630. args.unshift(message);
  1631. }
  1632. opts.message = logLevel;
  1633. break;
  1634. case 'object':
  1635. Object.assign(opts, logLevel);
  1636. break;
  1637. }
  1638. if (typeof opts.message === 'function') {
  1639. opts.message = opts.message();
  1640. }
  1641. const messageType = typeof opts.message;
  1642. assert$5(messageType === 'string' || messageType === 'object');
  1643. return Object.assign(opts, {
  1644. args
  1645. }, opts.opts);
  1646. }
  1647. function decorateMessage(id, message, opts) {
  1648. if (typeof message === 'string') {
  1649. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1650. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1651. message = addColor(message, opts.color, opts.background);
  1652. }
  1653. return message;
  1654. }
  1655. function logImageInNode(_ref2) {
  1656. let {
  1657. image,
  1658. message = '',
  1659. scale = 1
  1660. } = _ref2;
  1661. let asciify = null;
  1662. try {
  1663. asciify = module.require('asciify-image');
  1664. } catch (error) {}
  1665. if (asciify) {
  1666. return () => asciify(image, {
  1667. fit: 'box',
  1668. width: "".concat(Math.round(80 * scale), "%")
  1669. }).then(data => console.log(data));
  1670. }
  1671. return noop$1;
  1672. }
  1673. function logImageInBrowser(_ref3) {
  1674. let {
  1675. image,
  1676. message = '',
  1677. scale = 1
  1678. } = _ref3;
  1679. if (typeof image === 'string') {
  1680. const img = new Image();
  1681. img.onload = () => {
  1682. const args = formatImage(img, message, scale);
  1683. console.log(...args);
  1684. };
  1685. img.src = image;
  1686. return noop$1;
  1687. }
  1688. const element = image.nodeName || '';
  1689. if (element.toLowerCase() === 'img') {
  1690. console.log(...formatImage(image, message, scale));
  1691. return noop$1;
  1692. }
  1693. if (element.toLowerCase() === 'canvas') {
  1694. const img = new Image();
  1695. img.onload = () => console.log(...formatImage(img, message, scale));
  1696. img.src = image.toDataURL();
  1697. return noop$1;
  1698. }
  1699. return noop$1;
  1700. }
  1701. function getTableHeader(table) {
  1702. for (const key in table) {
  1703. for (const title in table[key]) {
  1704. return title || 'untitled';
  1705. }
  1706. }
  1707. return 'empty';
  1708. }
  1709. const probeLog = new Log({
  1710. id: 'loaders.gl'
  1711. });
  1712. class NullLog {
  1713. log() {
  1714. return () => {};
  1715. }
  1716. info() {
  1717. return () => {};
  1718. }
  1719. warn() {
  1720. return () => {};
  1721. }
  1722. error() {
  1723. return () => {};
  1724. }
  1725. }
  1726. class ConsoleLog {
  1727. constructor() {
  1728. _defineProperty(this, "console", void 0);
  1729. this.console = console;
  1730. }
  1731. log(...args) {
  1732. return this.console.log.bind(this.console, ...args);
  1733. }
  1734. info(...args) {
  1735. return this.console.info.bind(this.console, ...args);
  1736. }
  1737. warn(...args) {
  1738. return this.console.warn.bind(this.console, ...args);
  1739. }
  1740. error(...args) {
  1741. return this.console.error.bind(this.console, ...args);
  1742. }
  1743. }
  1744. const DEFAULT_LOADER_OPTIONS = {
  1745. fetch: null,
  1746. mimeType: undefined,
  1747. nothrow: false,
  1748. log: new ConsoleLog(),
  1749. CDN: 'https://unpkg.com/@loaders.gl',
  1750. worker: true,
  1751. maxConcurrency: 3,
  1752. maxMobileConcurrency: 1,
  1753. reuseWorkers: true,
  1754. _workerType: '',
  1755. limit: 0,
  1756. _limitMB: 0,
  1757. batchSize: 'auto',
  1758. batchDebounceMs: 0,
  1759. metadata: false,
  1760. transforms: []
  1761. };
  1762. const REMOVED_LOADER_OPTIONS = {
  1763. throws: 'nothrow',
  1764. dataType: '(no longer used)',
  1765. uri: 'baseUri',
  1766. method: 'fetch.method',
  1767. headers: 'fetch.headers',
  1768. body: 'fetch.body',
  1769. mode: 'fetch.mode',
  1770. credentials: 'fetch.credentials',
  1771. cache: 'fetch.cache',
  1772. redirect: 'fetch.redirect',
  1773. referrer: 'fetch.referrer',
  1774. referrerPolicy: 'fetch.referrerPolicy',
  1775. integrity: 'fetch.integrity',
  1776. keepalive: 'fetch.keepalive',
  1777. signal: 'fetch.signal'
  1778. };
  1779. function getGlobalLoaderState() {
  1780. globalThis.loaders = globalThis.loaders || {};
  1781. const {
  1782. loaders
  1783. } = globalThis;
  1784. loaders._state = loaders._state || {};
  1785. return loaders._state;
  1786. }
  1787. const getGlobalLoaderOptions = () => {
  1788. const state = getGlobalLoaderState();
  1789. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1790. };
  1791. return state.globalOptions;
  1792. };
  1793. function normalizeOptions(options, loader, loaders, url) {
  1794. loaders = loaders || [];
  1795. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1796. validateOptions(options, loaders);
  1797. return normalizeOptionsInternal(loader, options, url);
  1798. }
  1799. function getFetchFunction(options, context) {
  1800. const globalOptions = getGlobalLoaderOptions();
  1801. const fetchOptions = options || globalOptions;
  1802. if (typeof fetchOptions.fetch === 'function') {
  1803. return fetchOptions.fetch;
  1804. }
  1805. if (isObject(fetchOptions.fetch)) {
  1806. return url => fetchFile(url, fetchOptions);
  1807. }
  1808. if (context !== null && context !== void 0 && context.fetch) {
  1809. return context === null || context === void 0 ? void 0 : context.fetch;
  1810. }
  1811. return fetchFile;
  1812. }
  1813. function validateOptions(options, loaders) {
  1814. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1815. for (const loader of loaders) {
  1816. const idOptions = options && options[loader.id] || {};
  1817. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1818. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1819. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1820. }
  1821. }
  1822. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1823. const loaderName = id || 'Top level';
  1824. const prefix = id ? "".concat(id, ".") : '';
  1825. for (const key in options) {
  1826. const isSubOptions = !id && isObject(options[key]);
  1827. const isBaseUriOption = key === 'baseUri' && !id;
  1828. const isWorkerUrlOption = key === 'workerUrl' && id;
  1829. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1830. if (key in deprecatedOptions) {
  1831. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1832. } else if (!isSubOptions) {
  1833. const suggestion = findSimilarOption(key, loaders);
  1834. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1835. }
  1836. }
  1837. }
  1838. }
  1839. function findSimilarOption(optionKey, loaders) {
  1840. const lowerCaseOptionKey = optionKey.toLowerCase();
  1841. let bestSuggestion = '';
  1842. for (const loader of loaders) {
  1843. for (const key in loader.options) {
  1844. if (optionKey === key) {
  1845. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1846. }
  1847. const lowerCaseKey = key.toLowerCase();
  1848. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1849. if (isPartialMatch) {
  1850. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1851. }
  1852. }
  1853. }
  1854. return bestSuggestion;
  1855. }
  1856. function normalizeOptionsInternal(loader, options, url) {
  1857. const loaderDefaultOptions = loader.options || {};
  1858. const mergedOptions = { ...loaderDefaultOptions
  1859. };
  1860. addUrlOptions(mergedOptions, url);
  1861. if (mergedOptions.log === null) {
  1862. mergedOptions.log = new NullLog();
  1863. }
  1864. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1865. mergeNestedFields(mergedOptions, options);
  1866. return mergedOptions;
  1867. }
  1868. function mergeNestedFields(mergedOptions, options) {
  1869. for (const key in options) {
  1870. if (key in options) {
  1871. const value = options[key];
  1872. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1873. mergedOptions[key] = { ...mergedOptions[key],
  1874. ...options[key]
  1875. };
  1876. } else {
  1877. mergedOptions[key] = options[key];
  1878. }
  1879. }
  1880. }
  1881. }
  1882. function addUrlOptions(options, url) {
  1883. if (url && !('baseUri' in options)) {
  1884. options.baseUri = url;
  1885. }
  1886. }
  1887. function isLoaderObject(loader) {
  1888. var _loader;
  1889. if (!loader) {
  1890. return false;
  1891. }
  1892. if (Array.isArray(loader)) {
  1893. loader = loader[0];
  1894. }
  1895. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1896. return hasExtensions;
  1897. }
  1898. function normalizeLoader(loader) {
  1899. var _loader2, _loader3;
  1900. assert$7(loader, 'null loader');
  1901. assert$7(isLoaderObject(loader), 'invalid loader');
  1902. let options;
  1903. if (Array.isArray(loader)) {
  1904. options = loader[1];
  1905. loader = loader[0];
  1906. loader = { ...loader,
  1907. options: { ...loader.options,
  1908. ...options
  1909. }
  1910. };
  1911. }
  1912. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1913. loader.text = true;
  1914. }
  1915. if (!loader.text) {
  1916. loader.binary = true;
  1917. }
  1918. return loader;
  1919. }
  1920. const getGlobalLoaderRegistry = () => {
  1921. const state = getGlobalLoaderState();
  1922. state.loaderRegistry = state.loaderRegistry || [];
  1923. return state.loaderRegistry;
  1924. };
  1925. function getRegisteredLoaders() {
  1926. return getGlobalLoaderRegistry();
  1927. }
  1928. const EXT_PATTERN = /\.([^.]+)$/;
  1929. async function selectLoader(data, loaders = [], options, context) {
  1930. if (!validHTTPResponse(data)) {
  1931. return null;
  1932. }
  1933. let loader = selectLoaderSync(data, loaders, { ...options,
  1934. nothrow: true
  1935. }, context);
  1936. if (loader) {
  1937. return loader;
  1938. }
  1939. if (isBlob(data)) {
  1940. data = await data.slice(0, 10).arrayBuffer();
  1941. loader = selectLoaderSync(data, loaders, options, context);
  1942. }
  1943. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1944. throw new Error(getNoValidLoaderMessage(data));
  1945. }
  1946. return loader;
  1947. }
  1948. function selectLoaderSync(data, loaders = [], options, context) {
  1949. if (!validHTTPResponse(data)) {
  1950. return null;
  1951. }
  1952. if (loaders && !Array.isArray(loaders)) {
  1953. return normalizeLoader(loaders);
  1954. }
  1955. let candidateLoaders = [];
  1956. if (loaders) {
  1957. candidateLoaders = candidateLoaders.concat(loaders);
  1958. }
  1959. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1960. candidateLoaders.push(...getRegisteredLoaders());
  1961. }
  1962. normalizeLoaders(candidateLoaders);
  1963. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1964. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1965. throw new Error(getNoValidLoaderMessage(data));
  1966. }
  1967. return loader;
  1968. }
  1969. function selectLoaderInternal(data, loaders, options, context) {
  1970. const {
  1971. url,
  1972. type
  1973. } = getResourceUrlAndType(data);
  1974. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1975. let loader = null;
  1976. if (options !== null && options !== void 0 && options.mimeType) {
  1977. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  1978. }
  1979. loader = loader || findLoaderByUrl(loaders, testUrl);
  1980. loader = loader || findLoaderByMIMEType(loaders, type);
  1981. loader = loader || findLoaderByInitialBytes(loaders, data);
  1982. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  1983. return loader;
  1984. }
  1985. function validHTTPResponse(data) {
  1986. if (data instanceof Response) {
  1987. if (data.status === 204) {
  1988. return false;
  1989. }
  1990. }
  1991. return true;
  1992. }
  1993. function getNoValidLoaderMessage(data) {
  1994. const {
  1995. url,
  1996. type
  1997. } = getResourceUrlAndType(data);
  1998. let message = 'No valid loader found (';
  1999. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2000. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2001. const firstCharacters = data ? getFirstCharacters(data) : '';
  2002. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2003. message += ')';
  2004. return message;
  2005. }
  2006. function normalizeLoaders(loaders) {
  2007. for (const loader of loaders) {
  2008. normalizeLoader(loader);
  2009. }
  2010. }
  2011. function findLoaderByUrl(loaders, url) {
  2012. const match = url && EXT_PATTERN.exec(url);
  2013. const extension = match && match[1];
  2014. return extension ? findLoaderByExtension(loaders, extension) : null;
  2015. }
  2016. function findLoaderByExtension(loaders, extension) {
  2017. extension = extension.toLowerCase();
  2018. for (const loader of loaders) {
  2019. for (const loaderExtension of loader.extensions) {
  2020. if (loaderExtension.toLowerCase() === extension) {
  2021. return loader;
  2022. }
  2023. }
  2024. }
  2025. return null;
  2026. }
  2027. function findLoaderByMIMEType(loaders, mimeType) {
  2028. for (const loader of loaders) {
  2029. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2030. return loader;
  2031. }
  2032. if (mimeType === "application/x.".concat(loader.id)) {
  2033. return loader;
  2034. }
  2035. }
  2036. return null;
  2037. }
  2038. function findLoaderByInitialBytes(loaders, data) {
  2039. if (!data) {
  2040. return null;
  2041. }
  2042. for (const loader of loaders) {
  2043. if (typeof data === 'string') {
  2044. if (testDataAgainstText(data, loader)) {
  2045. return loader;
  2046. }
  2047. } else if (ArrayBuffer.isView(data)) {
  2048. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2049. return loader;
  2050. }
  2051. } else if (data instanceof ArrayBuffer) {
  2052. const byteOffset = 0;
  2053. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2054. return loader;
  2055. }
  2056. }
  2057. }
  2058. return null;
  2059. }
  2060. function testDataAgainstText(data, loader) {
  2061. if (loader.testText) {
  2062. return loader.testText(data);
  2063. }
  2064. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2065. return tests.some(test => data.startsWith(test));
  2066. }
  2067. function testDataAgainstBinary(data, byteOffset, loader) {
  2068. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2069. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2070. }
  2071. function testBinary(data, byteOffset, loader, test) {
  2072. if (test instanceof ArrayBuffer) {
  2073. return compareArrayBuffers(test, data, test.byteLength);
  2074. }
  2075. switch (typeof test) {
  2076. case 'function':
  2077. return test(data, loader);
  2078. case 'string':
  2079. const magic = getMagicString$2(data, byteOffset, test.length);
  2080. return test === magic;
  2081. default:
  2082. return false;
  2083. }
  2084. }
  2085. function getFirstCharacters(data, length = 5) {
  2086. if (typeof data === 'string') {
  2087. return data.slice(0, length);
  2088. } else if (ArrayBuffer.isView(data)) {
  2089. return getMagicString$2(data.buffer, data.byteOffset, length);
  2090. } else if (data instanceof ArrayBuffer) {
  2091. const byteOffset = 0;
  2092. return getMagicString$2(data, byteOffset, length);
  2093. }
  2094. return '';
  2095. }
  2096. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2097. if (arrayBuffer.byteLength < byteOffset + length) {
  2098. return '';
  2099. }
  2100. const dataView = new DataView(arrayBuffer);
  2101. let magic = '';
  2102. for (let i = 0; i < length; i++) {
  2103. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2104. }
  2105. return magic;
  2106. }
  2107. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2108. function* makeStringIterator(string, options) {
  2109. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2110. let offset = 0;
  2111. const textEncoder = new TextEncoder();
  2112. while (offset < string.length) {
  2113. const chunkLength = Math.min(string.length - offset, chunkSize);
  2114. const chunk = string.slice(offset, offset + chunkLength);
  2115. offset += chunkLength;
  2116. yield textEncoder.encode(chunk);
  2117. }
  2118. }
  2119. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2120. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2121. const {
  2122. chunkSize = DEFAULT_CHUNK_SIZE$1
  2123. } = options;
  2124. let byteOffset = 0;
  2125. while (byteOffset < arrayBuffer.byteLength) {
  2126. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2127. const chunk = new ArrayBuffer(chunkByteLength);
  2128. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2129. const chunkArray = new Uint8Array(chunk);
  2130. chunkArray.set(sourceArray);
  2131. byteOffset += chunkByteLength;
  2132. yield chunk;
  2133. }
  2134. }
  2135. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2136. async function* makeBlobIterator(blob, options) {
  2137. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2138. let offset = 0;
  2139. while (offset < blob.size) {
  2140. const end = offset + chunkSize;
  2141. const chunk = await blob.slice(offset, end).arrayBuffer();
  2142. offset = end;
  2143. yield chunk;
  2144. }
  2145. }
  2146. function makeStreamIterator(stream, options) {
  2147. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2148. }
  2149. async function* makeBrowserStreamIterator(stream, options) {
  2150. const reader = stream.getReader();
  2151. let nextBatchPromise;
  2152. try {
  2153. while (true) {
  2154. const currentBatchPromise = nextBatchPromise || reader.read();
  2155. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2156. nextBatchPromise = reader.read();
  2157. }
  2158. const {
  2159. done,
  2160. value
  2161. } = await currentBatchPromise;
  2162. if (done) {
  2163. return;
  2164. }
  2165. yield toArrayBuffer(value);
  2166. }
  2167. } catch (error) {
  2168. reader.releaseLock();
  2169. }
  2170. }
  2171. async function* makeNodeStreamIterator(stream, options) {
  2172. for await (const chunk of stream) {
  2173. yield toArrayBuffer(chunk);
  2174. }
  2175. }
  2176. function makeIterator(data, options) {
  2177. if (typeof data === 'string') {
  2178. return makeStringIterator(data, options);
  2179. }
  2180. if (data instanceof ArrayBuffer) {
  2181. return makeArrayBufferIterator(data, options);
  2182. }
  2183. if (isBlob(data)) {
  2184. return makeBlobIterator(data, options);
  2185. }
  2186. if (isReadableStream(data)) {
  2187. return makeStreamIterator(data, options);
  2188. }
  2189. if (isResponse(data)) {
  2190. const response = data;
  2191. return makeStreamIterator(response.body, options);
  2192. }
  2193. throw new Error('makeIterator');
  2194. }
  2195. const ERR_DATA = 'Cannot convert supplied data type';
  2196. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2197. if (loader.text && typeof data === 'string') {
  2198. return data;
  2199. }
  2200. if (isBuffer(data)) {
  2201. data = data.buffer;
  2202. }
  2203. if (data instanceof ArrayBuffer) {
  2204. const arrayBuffer = data;
  2205. if (loader.text && !loader.binary) {
  2206. const textDecoder = new TextDecoder('utf8');
  2207. return textDecoder.decode(arrayBuffer);
  2208. }
  2209. return arrayBuffer;
  2210. }
  2211. if (ArrayBuffer.isView(data)) {
  2212. if (loader.text && !loader.binary) {
  2213. const textDecoder = new TextDecoder('utf8');
  2214. return textDecoder.decode(data);
  2215. }
  2216. let arrayBuffer = data.buffer;
  2217. const byteLength = data.byteLength || data.length;
  2218. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2219. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2220. }
  2221. return arrayBuffer;
  2222. }
  2223. throw new Error(ERR_DATA);
  2224. }
  2225. async function getArrayBufferOrStringFromData(data, loader, options) {
  2226. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2227. if (typeof data === 'string' || isArrayBuffer) {
  2228. return getArrayBufferOrStringFromDataSync(data, loader);
  2229. }
  2230. if (isBlob(data)) {
  2231. data = await makeResponse(data);
  2232. }
  2233. if (isResponse(data)) {
  2234. const response = data;
  2235. await checkResponse(response);
  2236. return loader.binary ? await response.arrayBuffer() : await response.text();
  2237. }
  2238. if (isReadableStream(data)) {
  2239. data = makeIterator(data, options);
  2240. }
  2241. if (isIterable(data) || isAsyncIterable(data)) {
  2242. return concatenateArrayBuffersAsync(data);
  2243. }
  2244. throw new Error(ERR_DATA);
  2245. }
  2246. function getLoaderContext(context, options, previousContext = null) {
  2247. if (previousContext) {
  2248. return previousContext;
  2249. }
  2250. const resolvedContext = {
  2251. fetch: getFetchFunction(options, context),
  2252. ...context
  2253. };
  2254. if (!Array.isArray(resolvedContext.loaders)) {
  2255. resolvedContext.loaders = null;
  2256. }
  2257. return resolvedContext;
  2258. }
  2259. function getLoadersFromContext(loaders, context) {
  2260. if (!context && loaders && !Array.isArray(loaders)) {
  2261. return loaders;
  2262. }
  2263. let candidateLoaders;
  2264. if (loaders) {
  2265. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2266. }
  2267. if (context && context.loaders) {
  2268. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2269. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2270. }
  2271. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2272. }
  2273. async function parse$3(data, loaders, options, context) {
  2274. assert$6(!context || typeof context === 'object');
  2275. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2276. context = undefined;
  2277. options = loaders;
  2278. loaders = undefined;
  2279. }
  2280. data = await data;
  2281. options = options || {};
  2282. const {
  2283. url
  2284. } = getResourceUrlAndType(data);
  2285. const typedLoaders = loaders;
  2286. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2287. const loader = await selectLoader(data, candidateLoaders, options);
  2288. if (!loader) {
  2289. return null;
  2290. }
  2291. options = normalizeOptions(options, loader, candidateLoaders, url);
  2292. context = getLoaderContext({
  2293. url,
  2294. parse: parse$3,
  2295. loaders: candidateLoaders
  2296. }, options, context);
  2297. return await parseWithLoader(loader, data, options, context);
  2298. }
  2299. async function parseWithLoader(loader, data, options, context) {
  2300. validateWorkerVersion(loader);
  2301. data = await getArrayBufferOrStringFromData(data, loader, options);
  2302. if (loader.parseTextSync && typeof data === 'string') {
  2303. options.dataType = 'text';
  2304. return loader.parseTextSync(data, options, context, loader);
  2305. }
  2306. if (canParseWithWorker(loader, options)) {
  2307. return await parseWithWorker(loader, data, options, context, parse$3);
  2308. }
  2309. if (loader.parseText && typeof data === 'string') {
  2310. return await loader.parseText(data, options, context, loader);
  2311. }
  2312. if (loader.parse) {
  2313. return await loader.parse(data, options, context, loader);
  2314. }
  2315. assert$6(!loader.parseSync);
  2316. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2317. }
  2318. async function load(url, loaders, options, context) {
  2319. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2320. options = loaders;
  2321. loaders = undefined;
  2322. }
  2323. const fetch = getFetchFunction(options);
  2324. let data = url;
  2325. if (typeof url === 'string') {
  2326. data = await fetch(url);
  2327. }
  2328. if (isBlob(url)) {
  2329. data = await fetch(url);
  2330. }
  2331. return await parse$3(data, loaders, options);
  2332. }
  2333. function assert$4(condition, message) {
  2334. if (!condition) {
  2335. throw new Error("math.gl assertion ".concat(message));
  2336. }
  2337. }
  2338. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2339. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2340. const config = {};
  2341. config.EPSILON = 1e-12;
  2342. config.debug = false;
  2343. config.precision = 4;
  2344. config.printTypes = false;
  2345. config.printDegrees = false;
  2346. config.printRowMajor = true;
  2347. function round(value) {
  2348. return Math.round(value / config.EPSILON) * config.EPSILON;
  2349. }
  2350. function formatValue(value, {
  2351. precision = config.precision || 4
  2352. } = {}) {
  2353. value = round(value);
  2354. return "".concat(parseFloat(value.toPrecision(precision)));
  2355. }
  2356. function isArray(value) {
  2357. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2358. }
  2359. function duplicateArray(array) {
  2360. return array.clone ? array.clone() : new Array(array.length);
  2361. }
  2362. function map$1(value, func, result) {
  2363. if (isArray(value)) {
  2364. result = result || duplicateArray(value);
  2365. for (let i = 0; i < result.length && i < value.length; ++i) {
  2366. result[i] = func(value[i], i, result);
  2367. }
  2368. return result;
  2369. }
  2370. return func(value);
  2371. }
  2372. function toRadians(degrees) {
  2373. return radians(degrees);
  2374. }
  2375. function toDegrees(radians) {
  2376. return degrees(radians);
  2377. }
  2378. function radians(degrees, result) {
  2379. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2380. }
  2381. function degrees(radians, result) {
  2382. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2383. }
  2384. function clamp(value, min, max) {
  2385. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2386. }
  2387. function equals(a, b, epsilon) {
  2388. const oldEpsilon = config.EPSILON;
  2389. if (epsilon) {
  2390. config.EPSILON = epsilon;
  2391. }
  2392. try {
  2393. if (a === b) {
  2394. return true;
  2395. }
  2396. if (isArray(a) && isArray(b)) {
  2397. if (a.length !== b.length) {
  2398. return false;
  2399. }
  2400. for (let i = 0; i < a.length; ++i) {
  2401. if (!equals(a[i], b[i])) {
  2402. return false;
  2403. }
  2404. }
  2405. return true;
  2406. }
  2407. if (a && a.equals) {
  2408. return a.equals(b);
  2409. }
  2410. if (b && b.equals) {
  2411. return b.equals(a);
  2412. }
  2413. if (Number.isFinite(a) && Number.isFinite(b)) {
  2414. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2415. }
  2416. return false;
  2417. } finally {
  2418. config.EPSILON = oldEpsilon;
  2419. }
  2420. }
  2421. function _extendableBuiltin(cls) {
  2422. function ExtendableBuiltin() {
  2423. var instance = Reflect.construct(cls, Array.from(arguments));
  2424. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2425. return instance;
  2426. }
  2427. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2428. constructor: {
  2429. value: cls,
  2430. enumerable: false,
  2431. writable: true,
  2432. configurable: true
  2433. }
  2434. });
  2435. if (Object.setPrototypeOf) {
  2436. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2437. } else {
  2438. ExtendableBuiltin.__proto__ = cls;
  2439. }
  2440. return ExtendableBuiltin;
  2441. }
  2442. class MathArray extends _extendableBuiltin(Array) {
  2443. get ELEMENTS() {
  2444. assert$4(false);
  2445. return 0;
  2446. }
  2447. clone() {
  2448. return new this.constructor().copy(this);
  2449. }
  2450. from(arrayOrObject) {
  2451. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2452. }
  2453. fromArray(array, offset = 0) {
  2454. for (let i = 0; i < this.ELEMENTS; ++i) {
  2455. this[i] = array[i + offset];
  2456. }
  2457. return this.check();
  2458. }
  2459. to(arrayOrObject) {
  2460. if (arrayOrObject === this) {
  2461. return this;
  2462. }
  2463. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2464. }
  2465. toTarget(target) {
  2466. return target ? this.to(target) : this;
  2467. }
  2468. toArray(array = [], offset = 0) {
  2469. for (let i = 0; i < this.ELEMENTS; ++i) {
  2470. array[offset + i] = this[i];
  2471. }
  2472. return array;
  2473. }
  2474. toFloat32Array() {
  2475. return new Float32Array(this);
  2476. }
  2477. toString() {
  2478. return this.formatString(config);
  2479. }
  2480. formatString(opts) {
  2481. let string = '';
  2482. for (let i = 0; i < this.ELEMENTS; ++i) {
  2483. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2484. }
  2485. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2486. }
  2487. equals(array) {
  2488. if (!array || this.length !== array.length) {
  2489. return false;
  2490. }
  2491. for (let i = 0; i < this.ELEMENTS; ++i) {
  2492. if (!equals(this[i], array[i])) {
  2493. return false;
  2494. }
  2495. }
  2496. return true;
  2497. }
  2498. exactEquals(array) {
  2499. if (!array || this.length !== array.length) {
  2500. return false;
  2501. }
  2502. for (let i = 0; i < this.ELEMENTS; ++i) {
  2503. if (this[i] !== array[i]) {
  2504. return false;
  2505. }
  2506. }
  2507. return true;
  2508. }
  2509. negate() {
  2510. for (let i = 0; i < this.ELEMENTS; ++i) {
  2511. this[i] = -this[i];
  2512. }
  2513. return this.check();
  2514. }
  2515. lerp(a, b, t) {
  2516. if (t === undefined) {
  2517. t = b;
  2518. b = a;
  2519. a = this;
  2520. }
  2521. for (let i = 0; i < this.ELEMENTS; ++i) {
  2522. const ai = a[i];
  2523. this[i] = ai + t * (b[i] - ai);
  2524. }
  2525. return this.check();
  2526. }
  2527. min(vector) {
  2528. for (let i = 0; i < this.ELEMENTS; ++i) {
  2529. this[i] = Math.min(vector[i], this[i]);
  2530. }
  2531. return this.check();
  2532. }
  2533. max(vector) {
  2534. for (let i = 0; i < this.ELEMENTS; ++i) {
  2535. this[i] = Math.max(vector[i], this[i]);
  2536. }
  2537. return this.check();
  2538. }
  2539. clamp(minVector, maxVector) {
  2540. for (let i = 0; i < this.ELEMENTS; ++i) {
  2541. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2542. }
  2543. return this.check();
  2544. }
  2545. add(...vectors) {
  2546. for (const vector of vectors) {
  2547. for (let i = 0; i < this.ELEMENTS; ++i) {
  2548. this[i] += vector[i];
  2549. }
  2550. }
  2551. return this.check();
  2552. }
  2553. subtract(...vectors) {
  2554. for (const vector of vectors) {
  2555. for (let i = 0; i < this.ELEMENTS; ++i) {
  2556. this[i] -= vector[i];
  2557. }
  2558. }
  2559. return this.check();
  2560. }
  2561. scale(scale) {
  2562. if (Array.isArray(scale)) {
  2563. return this.multiply(scale);
  2564. }
  2565. for (let i = 0; i < this.ELEMENTS; ++i) {
  2566. this[i] *= scale;
  2567. }
  2568. return this.check();
  2569. }
  2570. sub(a) {
  2571. return this.subtract(a);
  2572. }
  2573. setScalar(a) {
  2574. for (let i = 0; i < this.ELEMENTS; ++i) {
  2575. this[i] = a;
  2576. }
  2577. return this.check();
  2578. }
  2579. addScalar(a) {
  2580. for (let i = 0; i < this.ELEMENTS; ++i) {
  2581. this[i] += a;
  2582. }
  2583. return this.check();
  2584. }
  2585. subScalar(a) {
  2586. return this.addScalar(-a);
  2587. }
  2588. multiplyScalar(scalar) {
  2589. for (let i = 0; i < this.ELEMENTS; ++i) {
  2590. this[i] *= scalar;
  2591. }
  2592. return this.check();
  2593. }
  2594. divideScalar(a) {
  2595. return this.scale(1 / a);
  2596. }
  2597. clampScalar(min, max) {
  2598. for (let i = 0; i < this.ELEMENTS; ++i) {
  2599. this[i] = Math.min(Math.max(this[i], min), max);
  2600. }
  2601. return this.check();
  2602. }
  2603. multiplyByScalar(scalar) {
  2604. return this.scale(scalar);
  2605. }
  2606. get elements() {
  2607. return this;
  2608. }
  2609. check() {
  2610. if (config.debug && !this.validate()) {
  2611. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2612. }
  2613. return this;
  2614. }
  2615. validate() {
  2616. let valid = this.length === this.ELEMENTS;
  2617. for (let i = 0; i < this.ELEMENTS; ++i) {
  2618. valid = valid && Number.isFinite(this[i]);
  2619. }
  2620. return valid;
  2621. }
  2622. }
  2623. function validateVector(v, length) {
  2624. if (v.length !== length) {
  2625. return false;
  2626. }
  2627. for (let i = 0; i < v.length; ++i) {
  2628. if (!Number.isFinite(v[i])) {
  2629. return false;
  2630. }
  2631. }
  2632. return true;
  2633. }
  2634. function checkNumber(value) {
  2635. if (!Number.isFinite(value)) {
  2636. throw new Error("Invalid number ".concat(value));
  2637. }
  2638. return value;
  2639. }
  2640. function checkVector(v, length, callerName = '') {
  2641. if (config.debug && !validateVector(v, length)) {
  2642. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2643. }
  2644. return v;
  2645. }
  2646. const map = {};
  2647. function deprecated(method, version) {
  2648. if (!map[method]) {
  2649. map[method] = true;
  2650. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2651. }
  2652. }
  2653. class Vector extends MathArray {
  2654. get ELEMENTS() {
  2655. assert$4(false);
  2656. return 0;
  2657. }
  2658. copy(vector) {
  2659. assert$4(false);
  2660. return this;
  2661. }
  2662. get x() {
  2663. return this[0];
  2664. }
  2665. set x(value) {
  2666. this[0] = checkNumber(value);
  2667. }
  2668. get y() {
  2669. return this[1];
  2670. }
  2671. set y(value) {
  2672. this[1] = checkNumber(value);
  2673. }
  2674. len() {
  2675. return Math.sqrt(this.lengthSquared());
  2676. }
  2677. magnitude() {
  2678. return this.len();
  2679. }
  2680. lengthSquared() {
  2681. let length = 0;
  2682. for (let i = 0; i < this.ELEMENTS; ++i) {
  2683. length += this[i] * this[i];
  2684. }
  2685. return length;
  2686. }
  2687. magnitudeSquared() {
  2688. return this.lengthSquared();
  2689. }
  2690. distance(mathArray) {
  2691. return Math.sqrt(this.distanceSquared(mathArray));
  2692. }
  2693. distanceSquared(mathArray) {
  2694. let length = 0;
  2695. for (let i = 0; i < this.ELEMENTS; ++i) {
  2696. const dist = this[i] - mathArray[i];
  2697. length += dist * dist;
  2698. }
  2699. return checkNumber(length);
  2700. }
  2701. dot(mathArray) {
  2702. let product = 0;
  2703. for (let i = 0; i < this.ELEMENTS; ++i) {
  2704. product += this[i] * mathArray[i];
  2705. }
  2706. return checkNumber(product);
  2707. }
  2708. normalize() {
  2709. const length = this.magnitude();
  2710. if (length !== 0) {
  2711. for (let i = 0; i < this.ELEMENTS; ++i) {
  2712. this[i] /= length;
  2713. }
  2714. }
  2715. return this.check();
  2716. }
  2717. multiply(...vectors) {
  2718. for (const vector of vectors) {
  2719. for (let i = 0; i < this.ELEMENTS; ++i) {
  2720. this[i] *= vector[i];
  2721. }
  2722. }
  2723. return this.check();
  2724. }
  2725. divide(...vectors) {
  2726. for (const vector of vectors) {
  2727. for (let i = 0; i < this.ELEMENTS; ++i) {
  2728. this[i] /= vector[i];
  2729. }
  2730. }
  2731. return this.check();
  2732. }
  2733. lengthSq() {
  2734. return this.lengthSquared();
  2735. }
  2736. distanceTo(vector) {
  2737. return this.distance(vector);
  2738. }
  2739. distanceToSquared(vector) {
  2740. return this.distanceSquared(vector);
  2741. }
  2742. getComponent(i) {
  2743. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2744. return checkNumber(this[i]);
  2745. }
  2746. setComponent(i, value) {
  2747. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2748. this[i] = value;
  2749. return this.check();
  2750. }
  2751. addVectors(a, b) {
  2752. return this.copy(a).add(b);
  2753. }
  2754. subVectors(a, b) {
  2755. return this.copy(a).subtract(b);
  2756. }
  2757. multiplyVectors(a, b) {
  2758. return this.copy(a).multiply(b);
  2759. }
  2760. addScaledVector(a, b) {
  2761. return this.add(new this.constructor(a).multiplyScalar(b));
  2762. }
  2763. }
  2764. /**
  2765. * Common utilities
  2766. * @module glMatrix
  2767. */
  2768. // Configuration Constants
  2769. var EPSILON = 0.000001;
  2770. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2771. if (!Math.hypot) Math.hypot = function () {
  2772. var y = 0,
  2773. i = arguments.length;
  2774. while (i--) {
  2775. y += arguments[i] * arguments[i];
  2776. }
  2777. return Math.sqrt(y);
  2778. };
  2779. /**
  2780. * 2 Dimensional Vector
  2781. * @module vec2
  2782. */
  2783. /**
  2784. * Creates a new, empty vec2
  2785. *
  2786. * @returns {vec2} a new 2D vector
  2787. */
  2788. function create$4() {
  2789. var out = new ARRAY_TYPE(2);
  2790. if (ARRAY_TYPE != Float32Array) {
  2791. out[0] = 0;
  2792. out[1] = 0;
  2793. }
  2794. return out;
  2795. }
  2796. /**
  2797. * Transforms the vec2 with a mat2
  2798. *
  2799. * @param {vec2} out the receiving vector
  2800. * @param {ReadonlyVec2} a the vector to transform
  2801. * @param {ReadonlyMat2} m matrix to transform with
  2802. * @returns {vec2} out
  2803. */
  2804. function transformMat2(out, a, m) {
  2805. var x = a[0],
  2806. y = a[1];
  2807. out[0] = m[0] * x + m[2] * y;
  2808. out[1] = m[1] * x + m[3] * y;
  2809. return out;
  2810. }
  2811. /**
  2812. * Transforms the vec2 with a mat2d
  2813. *
  2814. * @param {vec2} out the receiving vector
  2815. * @param {ReadonlyVec2} a the vector to transform
  2816. * @param {ReadonlyMat2d} m matrix to transform with
  2817. * @returns {vec2} out
  2818. */
  2819. function transformMat2d(out, a, m) {
  2820. var x = a[0],
  2821. y = a[1];
  2822. out[0] = m[0] * x + m[2] * y + m[4];
  2823. out[1] = m[1] * x + m[3] * y + m[5];
  2824. return out;
  2825. }
  2826. /**
  2827. * Transforms the vec2 with a mat3
  2828. * 3rd vector component is implicitly '1'
  2829. *
  2830. * @param {vec2} out the receiving vector
  2831. * @param {ReadonlyVec2} a the vector to transform
  2832. * @param {ReadonlyMat3} m matrix to transform with
  2833. * @returns {vec2} out
  2834. */
  2835. function transformMat3$1(out, a, m) {
  2836. var x = a[0],
  2837. y = a[1];
  2838. out[0] = m[0] * x + m[3] * y + m[6];
  2839. out[1] = m[1] * x + m[4] * y + m[7];
  2840. return out;
  2841. }
  2842. /**
  2843. * Transforms the vec2 with a mat4
  2844. * 3rd vector component is implicitly '0'
  2845. * 4th vector component is implicitly '1'
  2846. *
  2847. * @param {vec2} out the receiving vector
  2848. * @param {ReadonlyVec2} a the vector to transform
  2849. * @param {ReadonlyMat4} m matrix to transform with
  2850. * @returns {vec2} out
  2851. */
  2852. function transformMat4$2(out, a, m) {
  2853. var x = a[0];
  2854. var y = a[1];
  2855. out[0] = m[0] * x + m[4] * y + m[12];
  2856. out[1] = m[1] * x + m[5] * y + m[13];
  2857. return out;
  2858. }
  2859. /**
  2860. * Perform some operation over an array of vec2s.
  2861. *
  2862. * @param {Array} a the array of vectors to iterate over
  2863. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2864. * @param {Number} offset Number of elements to skip at the beginning of the array
  2865. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2866. * @param {Function} fn Function to call for each vector in the array
  2867. * @param {Object} [arg] additional argument to pass to fn
  2868. * @returns {Array} a
  2869. * @function
  2870. */
  2871. (function () {
  2872. var vec = create$4();
  2873. return function (a, stride, offset, count, fn, arg) {
  2874. var i, l;
  2875. if (!stride) {
  2876. stride = 2;
  2877. }
  2878. if (!offset) {
  2879. offset = 0;
  2880. }
  2881. if (count) {
  2882. l = Math.min(count * stride + offset, a.length);
  2883. } else {
  2884. l = a.length;
  2885. }
  2886. for (i = offset; i < l; i += stride) {
  2887. vec[0] = a[i];
  2888. vec[1] = a[i + 1];
  2889. fn(vec, vec, arg);
  2890. a[i] = vec[0];
  2891. a[i + 1] = vec[1];
  2892. }
  2893. return a;
  2894. };
  2895. })();
  2896. function vec2_transformMat4AsVector(out, a, m) {
  2897. const x = a[0];
  2898. const y = a[1];
  2899. const w = m[3] * x + m[7] * y || 1.0;
  2900. out[0] = (m[0] * x + m[4] * y) / w;
  2901. out[1] = (m[1] * x + m[5] * y) / w;
  2902. return out;
  2903. }
  2904. function vec3_transformMat4AsVector(out, a, m) {
  2905. const x = a[0];
  2906. const y = a[1];
  2907. const z = a[2];
  2908. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2909. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2910. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2911. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2912. return out;
  2913. }
  2914. function vec3_transformMat2(out, a, m) {
  2915. const x = a[0];
  2916. const y = a[1];
  2917. out[0] = m[0] * x + m[2] * y;
  2918. out[1] = m[1] * x + m[3] * y;
  2919. out[2] = a[2];
  2920. return out;
  2921. }
  2922. function vec4_transformMat3(out, a, m) {
  2923. const x = a[0];
  2924. const y = a[1];
  2925. const z = a[2];
  2926. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2927. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2928. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2929. out[3] = a[3];
  2930. return out;
  2931. }
  2932. class Vector2 extends Vector {
  2933. constructor(x = 0, y = 0) {
  2934. super(2);
  2935. if (isArray(x) && arguments.length === 1) {
  2936. this.copy(x);
  2937. } else {
  2938. if (config.debug) {
  2939. checkNumber(x);
  2940. checkNumber(y);
  2941. }
  2942. this[0] = x;
  2943. this[1] = y;
  2944. }
  2945. }
  2946. set(x, y) {
  2947. this[0] = x;
  2948. this[1] = y;
  2949. return this.check();
  2950. }
  2951. copy(array) {
  2952. this[0] = array[0];
  2953. this[1] = array[1];
  2954. return this.check();
  2955. }
  2956. fromObject(object) {
  2957. if (config.debug) {
  2958. checkNumber(object.x);
  2959. checkNumber(object.y);
  2960. }
  2961. this[0] = object.x;
  2962. this[1] = object.y;
  2963. return this.check();
  2964. }
  2965. toObject(object) {
  2966. object.x = this[0];
  2967. object.y = this[1];
  2968. return object;
  2969. }
  2970. get ELEMENTS() {
  2971. return 2;
  2972. }
  2973. horizontalAngle() {
  2974. return Math.atan2(this.y, this.x);
  2975. }
  2976. verticalAngle() {
  2977. return Math.atan2(this.x, this.y);
  2978. }
  2979. transform(matrix4) {
  2980. return this.transformAsPoint(matrix4);
  2981. }
  2982. transformAsPoint(matrix4) {
  2983. transformMat4$2(this, this, matrix4);
  2984. return this.check();
  2985. }
  2986. transformAsVector(matrix4) {
  2987. vec2_transformMat4AsVector(this, this, matrix4);
  2988. return this.check();
  2989. }
  2990. transformByMatrix3(matrix3) {
  2991. transformMat3$1(this, this, matrix3);
  2992. return this.check();
  2993. }
  2994. transformByMatrix2x3(matrix2x3) {
  2995. transformMat2d(this, this, matrix2x3);
  2996. return this.check();
  2997. }
  2998. transformByMatrix2(matrix2) {
  2999. transformMat2(this, this, matrix2);
  3000. return this.check();
  3001. }
  3002. }
  3003. /**
  3004. * 3 Dimensional Vector
  3005. * @module vec3
  3006. */
  3007. /**
  3008. * Creates a new, empty vec3
  3009. *
  3010. * @returns {vec3} a new 3D vector
  3011. */
  3012. function create$3() {
  3013. var out = new ARRAY_TYPE(3);
  3014. if (ARRAY_TYPE != Float32Array) {
  3015. out[0] = 0;
  3016. out[1] = 0;
  3017. out[2] = 0;
  3018. }
  3019. return out;
  3020. }
  3021. /**
  3022. * Calculates the length of a vec3
  3023. *
  3024. * @param {ReadonlyVec3} a vector to calculate length of
  3025. * @returns {Number} length of a
  3026. */
  3027. function length$2(a) {
  3028. var x = a[0];
  3029. var y = a[1];
  3030. var z = a[2];
  3031. return Math.hypot(x, y, z);
  3032. }
  3033. /**
  3034. * Creates a new vec3 initialized with the given values
  3035. *
  3036. * @param {Number} x X component
  3037. * @param {Number} y Y component
  3038. * @param {Number} z Z component
  3039. * @returns {vec3} a new 3D vector
  3040. */
  3041. function fromValues(x, y, z) {
  3042. var out = new ARRAY_TYPE(3);
  3043. out[0] = x;
  3044. out[1] = y;
  3045. out[2] = z;
  3046. return out;
  3047. }
  3048. /**
  3049. * Normalize a vec3
  3050. *
  3051. * @param {vec3} out the receiving vector
  3052. * @param {ReadonlyVec3} a vector to normalize
  3053. * @returns {vec3} out
  3054. */
  3055. function normalize$2(out, a) {
  3056. var x = a[0];
  3057. var y = a[1];
  3058. var z = a[2];
  3059. var len = x * x + y * y + z * z;
  3060. if (len > 0) {
  3061. //TODO: evaluate use of glm_invsqrt here?
  3062. len = 1 / Math.sqrt(len);
  3063. }
  3064. out[0] = a[0] * len;
  3065. out[1] = a[1] * len;
  3066. out[2] = a[2] * len;
  3067. return out;
  3068. }
  3069. /**
  3070. * Calculates the dot product of two vec3's
  3071. *
  3072. * @param {ReadonlyVec3} a the first operand
  3073. * @param {ReadonlyVec3} b the second operand
  3074. * @returns {Number} dot product of a and b
  3075. */
  3076. function dot$2(a, b) {
  3077. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3078. }
  3079. /**
  3080. * Computes the cross product of two vec3's
  3081. *
  3082. * @param {vec3} out the receiving vector
  3083. * @param {ReadonlyVec3} a the first operand
  3084. * @param {ReadonlyVec3} b the second operand
  3085. * @returns {vec3} out
  3086. */
  3087. function cross(out, a, b) {
  3088. var ax = a[0],
  3089. ay = a[1],
  3090. az = a[2];
  3091. var bx = b[0],
  3092. by = b[1],
  3093. bz = b[2];
  3094. out[0] = ay * bz - az * by;
  3095. out[1] = az * bx - ax * bz;
  3096. out[2] = ax * by - ay * bx;
  3097. return out;
  3098. }
  3099. /**
  3100. * Transforms the vec3 with a mat4.
  3101. * 4th vector component is implicitly '1'
  3102. *
  3103. * @param {vec3} out the receiving vector
  3104. * @param {ReadonlyVec3} a the vector to transform
  3105. * @param {ReadonlyMat4} m matrix to transform with
  3106. * @returns {vec3} out
  3107. */
  3108. function transformMat4$1(out, a, m) {
  3109. var x = a[0],
  3110. y = a[1],
  3111. z = a[2];
  3112. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3113. w = w || 1.0;
  3114. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3115. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3116. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3117. return out;
  3118. }
  3119. /**
  3120. * Transforms the vec3 with a mat3.
  3121. *
  3122. * @param {vec3} out the receiving vector
  3123. * @param {ReadonlyVec3} a the vector to transform
  3124. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3125. * @returns {vec3} out
  3126. */
  3127. function transformMat3(out, a, m) {
  3128. var x = a[0],
  3129. y = a[1],
  3130. z = a[2];
  3131. out[0] = x * m[0] + y * m[3] + z * m[6];
  3132. out[1] = x * m[1] + y * m[4] + z * m[7];
  3133. out[2] = x * m[2] + y * m[5] + z * m[8];
  3134. return out;
  3135. }
  3136. /**
  3137. * Transforms the vec3 with a quat
  3138. * Can also be used for dual quaternions. (Multiply it with the real part)
  3139. *
  3140. * @param {vec3} out the receiving vector
  3141. * @param {ReadonlyVec3} a the vector to transform
  3142. * @param {ReadonlyQuat} q quaternion to transform with
  3143. * @returns {vec3} out
  3144. */
  3145. function transformQuat$1(out, a, q) {
  3146. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3147. var qx = q[0],
  3148. qy = q[1],
  3149. qz = q[2],
  3150. qw = q[3];
  3151. var x = a[0],
  3152. y = a[1],
  3153. z = a[2]; // var qvec = [qx, qy, qz];
  3154. // var uv = vec3.cross([], qvec, a);
  3155. var uvx = qy * z - qz * y,
  3156. uvy = qz * x - qx * z,
  3157. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3158. var uuvx = qy * uvz - qz * uvy,
  3159. uuvy = qz * uvx - qx * uvz,
  3160. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3161. var w2 = qw * 2;
  3162. uvx *= w2;
  3163. uvy *= w2;
  3164. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3165. uuvx *= 2;
  3166. uuvy *= 2;
  3167. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3168. out[0] = x + uvx + uuvx;
  3169. out[1] = y + uvy + uuvy;
  3170. out[2] = z + uvz + uuvz;
  3171. return out;
  3172. }
  3173. /**
  3174. * Rotate a 3D vector around the x-axis
  3175. * @param {vec3} out The receiving vec3
  3176. * @param {ReadonlyVec3} a The vec3 point to rotate
  3177. * @param {ReadonlyVec3} b The origin of the rotation
  3178. * @param {Number} rad The angle of rotation in radians
  3179. * @returns {vec3} out
  3180. */
  3181. function rotateX$2(out, a, b, rad) {
  3182. var p = [],
  3183. r = []; //Translate point to the origin
  3184. p[0] = a[0] - b[0];
  3185. p[1] = a[1] - b[1];
  3186. p[2] = a[2] - b[2]; //perform rotation
  3187. r[0] = p[0];
  3188. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3189. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3190. out[0] = r[0] + b[0];
  3191. out[1] = r[1] + b[1];
  3192. out[2] = r[2] + b[2];
  3193. return out;
  3194. }
  3195. /**
  3196. * Rotate a 3D vector around the y-axis
  3197. * @param {vec3} out The receiving vec3
  3198. * @param {ReadonlyVec3} a The vec3 point to rotate
  3199. * @param {ReadonlyVec3} b The origin of the rotation
  3200. * @param {Number} rad The angle of rotation in radians
  3201. * @returns {vec3} out
  3202. */
  3203. function rotateY$2(out, a, b, rad) {
  3204. var p = [],
  3205. r = []; //Translate point to the origin
  3206. p[0] = a[0] - b[0];
  3207. p[1] = a[1] - b[1];
  3208. p[2] = a[2] - b[2]; //perform rotation
  3209. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3210. r[1] = p[1];
  3211. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3212. out[0] = r[0] + b[0];
  3213. out[1] = r[1] + b[1];
  3214. out[2] = r[2] + b[2];
  3215. return out;
  3216. }
  3217. /**
  3218. * Rotate a 3D vector around the z-axis
  3219. * @param {vec3} out The receiving vec3
  3220. * @param {ReadonlyVec3} a The vec3 point to rotate
  3221. * @param {ReadonlyVec3} b The origin of the rotation
  3222. * @param {Number} rad The angle of rotation in radians
  3223. * @returns {vec3} out
  3224. */
  3225. function rotateZ$2(out, a, b, rad) {
  3226. var p = [],
  3227. r = []; //Translate point to the origin
  3228. p[0] = a[0] - b[0];
  3229. p[1] = a[1] - b[1];
  3230. p[2] = a[2] - b[2]; //perform rotation
  3231. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3232. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3233. r[2] = p[2]; //translate to correct position
  3234. out[0] = r[0] + b[0];
  3235. out[1] = r[1] + b[1];
  3236. out[2] = r[2] + b[2];
  3237. return out;
  3238. }
  3239. /**
  3240. * Get the angle between two 3D vectors
  3241. * @param {ReadonlyVec3} a The first operand
  3242. * @param {ReadonlyVec3} b The second operand
  3243. * @returns {Number} The angle in radians
  3244. */
  3245. function angle(a, b) {
  3246. var ax = a[0],
  3247. ay = a[1],
  3248. az = a[2],
  3249. bx = b[0],
  3250. by = b[1],
  3251. bz = b[2],
  3252. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3253. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3254. mag = mag1 * mag2,
  3255. cosine = mag && dot$2(a, b) / mag;
  3256. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3257. }
  3258. /**
  3259. * Alias for {@link vec3.length}
  3260. * @function
  3261. */
  3262. var len = length$2;
  3263. /**
  3264. * Perform some operation over an array of vec3s.
  3265. *
  3266. * @param {Array} a the array of vectors to iterate over
  3267. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3268. * @param {Number} offset Number of elements to skip at the beginning of the array
  3269. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3270. * @param {Function} fn Function to call for each vector in the array
  3271. * @param {Object} [arg] additional argument to pass to fn
  3272. * @returns {Array} a
  3273. * @function
  3274. */
  3275. (function () {
  3276. var vec = create$3();
  3277. return function (a, stride, offset, count, fn, arg) {
  3278. var i, l;
  3279. if (!stride) {
  3280. stride = 3;
  3281. }
  3282. if (!offset) {
  3283. offset = 0;
  3284. }
  3285. if (count) {
  3286. l = Math.min(count * stride + offset, a.length);
  3287. } else {
  3288. l = a.length;
  3289. }
  3290. for (i = offset; i < l; i += stride) {
  3291. vec[0] = a[i];
  3292. vec[1] = a[i + 1];
  3293. vec[2] = a[i + 2];
  3294. fn(vec, vec, arg);
  3295. a[i] = vec[0];
  3296. a[i + 1] = vec[1];
  3297. a[i + 2] = vec[2];
  3298. }
  3299. return a;
  3300. };
  3301. })();
  3302. const ORIGIN = [0, 0, 0];
  3303. const constants$2 = {};
  3304. class Vector3 extends Vector {
  3305. static get ZERO() {
  3306. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3307. }
  3308. constructor(x = 0, y = 0, z = 0) {
  3309. super(-0, -0, -0);
  3310. if (arguments.length === 1 && isArray(x)) {
  3311. this.copy(x);
  3312. } else {
  3313. if (config.debug) {
  3314. checkNumber(x);
  3315. checkNumber(y);
  3316. checkNumber(z);
  3317. }
  3318. this[0] = x;
  3319. this[1] = y;
  3320. this[2] = z;
  3321. }
  3322. }
  3323. set(x, y, z) {
  3324. this[0] = x;
  3325. this[1] = y;
  3326. this[2] = z;
  3327. return this.check();
  3328. }
  3329. copy(array) {
  3330. this[0] = array[0];
  3331. this[1] = array[1];
  3332. this[2] = array[2];
  3333. return this.check();
  3334. }
  3335. fromObject(object) {
  3336. if (config.debug) {
  3337. checkNumber(object.x);
  3338. checkNumber(object.y);
  3339. checkNumber(object.z);
  3340. }
  3341. this[0] = object.x;
  3342. this[1] = object.y;
  3343. this[2] = object.z;
  3344. return this.check();
  3345. }
  3346. toObject(object) {
  3347. object.x = this[0];
  3348. object.y = this[1];
  3349. object.z = this[2];
  3350. return object;
  3351. }
  3352. get ELEMENTS() {
  3353. return 3;
  3354. }
  3355. get z() {
  3356. return this[2];
  3357. }
  3358. set z(value) {
  3359. this[2] = checkNumber(value);
  3360. }
  3361. angle(vector) {
  3362. return angle(this, vector);
  3363. }
  3364. cross(vector) {
  3365. cross(this, this, vector);
  3366. return this.check();
  3367. }
  3368. rotateX({
  3369. radians,
  3370. origin = ORIGIN
  3371. }) {
  3372. rotateX$2(this, this, origin, radians);
  3373. return this.check();
  3374. }
  3375. rotateY({
  3376. radians,
  3377. origin = ORIGIN
  3378. }) {
  3379. rotateY$2(this, this, origin, radians);
  3380. return this.check();
  3381. }
  3382. rotateZ({
  3383. radians,
  3384. origin = ORIGIN
  3385. }) {
  3386. rotateZ$2(this, this, origin, radians);
  3387. return this.check();
  3388. }
  3389. transform(matrix4) {
  3390. return this.transformAsPoint(matrix4);
  3391. }
  3392. transformAsPoint(matrix4) {
  3393. transformMat4$1(this, this, matrix4);
  3394. return this.check();
  3395. }
  3396. transformAsVector(matrix4) {
  3397. vec3_transformMat4AsVector(this, this, matrix4);
  3398. return this.check();
  3399. }
  3400. transformByMatrix3(matrix3) {
  3401. transformMat3(this, this, matrix3);
  3402. return this.check();
  3403. }
  3404. transformByMatrix2(matrix2) {
  3405. vec3_transformMat2(this, this, matrix2);
  3406. return this.check();
  3407. }
  3408. transformByQuaternion(quaternion) {
  3409. transformQuat$1(this, this, quaternion);
  3410. return this.check();
  3411. }
  3412. }
  3413. class Matrix extends MathArray {
  3414. get ELEMENTS() {
  3415. assert$4(false);
  3416. return 0;
  3417. }
  3418. get RANK() {
  3419. assert$4(false);
  3420. return 0;
  3421. }
  3422. toString() {
  3423. let string = '[';
  3424. if (config.printRowMajor) {
  3425. string += 'row-major:';
  3426. for (let row = 0; row < this.RANK; ++row) {
  3427. for (let col = 0; col < this.RANK; ++col) {
  3428. string += " ".concat(this[col * this.RANK + row]);
  3429. }
  3430. }
  3431. } else {
  3432. string += 'column-major:';
  3433. for (let i = 0; i < this.ELEMENTS; ++i) {
  3434. string += " ".concat(this[i]);
  3435. }
  3436. }
  3437. string += ']';
  3438. return string;
  3439. }
  3440. getElementIndex(row, col) {
  3441. return col * this.RANK + row;
  3442. }
  3443. getElement(row, col) {
  3444. return this[col * this.RANK + row];
  3445. }
  3446. setElement(row, col, value) {
  3447. this[col * this.RANK + row] = checkNumber(value);
  3448. return this;
  3449. }
  3450. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3451. const firstIndex = columnIndex * this.RANK;
  3452. for (let i = 0; i < this.RANK; ++i) {
  3453. result[i] = this[firstIndex + i];
  3454. }
  3455. return result;
  3456. }
  3457. setColumn(columnIndex, columnVector) {
  3458. const firstIndex = columnIndex * this.RANK;
  3459. for (let i = 0; i < this.RANK; ++i) {
  3460. this[firstIndex + i] = columnVector[i];
  3461. }
  3462. return this;
  3463. }
  3464. }
  3465. /**
  3466. * 3x3 Matrix
  3467. * @module mat3
  3468. */
  3469. /**
  3470. * Creates a new identity mat3
  3471. *
  3472. * @returns {mat3} a new 3x3 matrix
  3473. */
  3474. function create$2() {
  3475. var out = new ARRAY_TYPE(9);
  3476. if (ARRAY_TYPE != Float32Array) {
  3477. out[1] = 0;
  3478. out[2] = 0;
  3479. out[3] = 0;
  3480. out[5] = 0;
  3481. out[6] = 0;
  3482. out[7] = 0;
  3483. }
  3484. out[0] = 1;
  3485. out[4] = 1;
  3486. out[8] = 1;
  3487. return out;
  3488. }
  3489. /**
  3490. * Transpose the values of a mat3
  3491. *
  3492. * @param {mat3} out the receiving matrix
  3493. * @param {ReadonlyMat3} a the source matrix
  3494. * @returns {mat3} out
  3495. */
  3496. function transpose$1(out, a) {
  3497. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3498. if (out === a) {
  3499. var a01 = a[1],
  3500. a02 = a[2],
  3501. a12 = a[5];
  3502. out[1] = a[3];
  3503. out[2] = a[6];
  3504. out[3] = a01;
  3505. out[5] = a[7];
  3506. out[6] = a02;
  3507. out[7] = a12;
  3508. } else {
  3509. out[0] = a[0];
  3510. out[1] = a[3];
  3511. out[2] = a[6];
  3512. out[3] = a[1];
  3513. out[4] = a[4];
  3514. out[5] = a[7];
  3515. out[6] = a[2];
  3516. out[7] = a[5];
  3517. out[8] = a[8];
  3518. }
  3519. return out;
  3520. }
  3521. /**
  3522. * Inverts a mat3
  3523. *
  3524. * @param {mat3} out the receiving matrix
  3525. * @param {ReadonlyMat3} a the source matrix
  3526. * @returns {mat3} out
  3527. */
  3528. function invert$2(out, a) {
  3529. var a00 = a[0],
  3530. a01 = a[1],
  3531. a02 = a[2];
  3532. var a10 = a[3],
  3533. a11 = a[4],
  3534. a12 = a[5];
  3535. var a20 = a[6],
  3536. a21 = a[7],
  3537. a22 = a[8];
  3538. var b01 = a22 * a11 - a12 * a21;
  3539. var b11 = -a22 * a10 + a12 * a20;
  3540. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3541. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3542. if (!det) {
  3543. return null;
  3544. }
  3545. det = 1.0 / det;
  3546. out[0] = b01 * det;
  3547. out[1] = (-a22 * a01 + a02 * a21) * det;
  3548. out[2] = (a12 * a01 - a02 * a11) * det;
  3549. out[3] = b11 * det;
  3550. out[4] = (a22 * a00 - a02 * a20) * det;
  3551. out[5] = (-a12 * a00 + a02 * a10) * det;
  3552. out[6] = b21 * det;
  3553. out[7] = (-a21 * a00 + a01 * a20) * det;
  3554. out[8] = (a11 * a00 - a01 * a10) * det;
  3555. return out;
  3556. }
  3557. /**
  3558. * Calculates the determinant of a mat3
  3559. *
  3560. * @param {ReadonlyMat3} a the source matrix
  3561. * @returns {Number} determinant of a
  3562. */
  3563. function determinant$1(a) {
  3564. var a00 = a[0],
  3565. a01 = a[1],
  3566. a02 = a[2];
  3567. var a10 = a[3],
  3568. a11 = a[4],
  3569. a12 = a[5];
  3570. var a20 = a[6],
  3571. a21 = a[7],
  3572. a22 = a[8];
  3573. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3574. }
  3575. /**
  3576. * Multiplies two mat3's
  3577. *
  3578. * @param {mat3} out the receiving matrix
  3579. * @param {ReadonlyMat3} a the first operand
  3580. * @param {ReadonlyMat3} b the second operand
  3581. * @returns {mat3} out
  3582. */
  3583. function multiply$2(out, a, b) {
  3584. var a00 = a[0],
  3585. a01 = a[1],
  3586. a02 = a[2];
  3587. var a10 = a[3],
  3588. a11 = a[4],
  3589. a12 = a[5];
  3590. var a20 = a[6],
  3591. a21 = a[7],
  3592. a22 = a[8];
  3593. var b00 = b[0],
  3594. b01 = b[1],
  3595. b02 = b[2];
  3596. var b10 = b[3],
  3597. b11 = b[4],
  3598. b12 = b[5];
  3599. var b20 = b[6],
  3600. b21 = b[7],
  3601. b22 = b[8];
  3602. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3603. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3604. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3605. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3606. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3607. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3608. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3609. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3610. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3611. return out;
  3612. }
  3613. /**
  3614. * Translate a mat3 by the given vector
  3615. *
  3616. * @param {mat3} out the receiving matrix
  3617. * @param {ReadonlyMat3} a the matrix to translate
  3618. * @param {ReadonlyVec2} v vector to translate by
  3619. * @returns {mat3} out
  3620. */
  3621. function translate$1(out, a, v) {
  3622. var a00 = a[0],
  3623. a01 = a[1],
  3624. a02 = a[2],
  3625. a10 = a[3],
  3626. a11 = a[4],
  3627. a12 = a[5],
  3628. a20 = a[6],
  3629. a21 = a[7],
  3630. a22 = a[8],
  3631. x = v[0],
  3632. y = v[1];
  3633. out[0] = a00;
  3634. out[1] = a01;
  3635. out[2] = a02;
  3636. out[3] = a10;
  3637. out[4] = a11;
  3638. out[5] = a12;
  3639. out[6] = x * a00 + y * a10 + a20;
  3640. out[7] = x * a01 + y * a11 + a21;
  3641. out[8] = x * a02 + y * a12 + a22;
  3642. return out;
  3643. }
  3644. /**
  3645. * Rotates a mat3 by the given angle
  3646. *
  3647. * @param {mat3} out the receiving matrix
  3648. * @param {ReadonlyMat3} a the matrix to rotate
  3649. * @param {Number} rad the angle to rotate the matrix by
  3650. * @returns {mat3} out
  3651. */
  3652. function rotate$1(out, a, rad) {
  3653. var a00 = a[0],
  3654. a01 = a[1],
  3655. a02 = a[2],
  3656. a10 = a[3],
  3657. a11 = a[4],
  3658. a12 = a[5],
  3659. a20 = a[6],
  3660. a21 = a[7],
  3661. a22 = a[8],
  3662. s = Math.sin(rad),
  3663. c = Math.cos(rad);
  3664. out[0] = c * a00 + s * a10;
  3665. out[1] = c * a01 + s * a11;
  3666. out[2] = c * a02 + s * a12;
  3667. out[3] = c * a10 - s * a00;
  3668. out[4] = c * a11 - s * a01;
  3669. out[5] = c * a12 - s * a02;
  3670. out[6] = a20;
  3671. out[7] = a21;
  3672. out[8] = a22;
  3673. return out;
  3674. }
  3675. /**
  3676. * Scales the mat3 by the dimensions in the given vec2
  3677. *
  3678. * @param {mat3} out the receiving matrix
  3679. * @param {ReadonlyMat3} a the matrix to rotate
  3680. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3681. * @returns {mat3} out
  3682. **/
  3683. function scale$3(out, a, v) {
  3684. var x = v[0],
  3685. y = v[1];
  3686. out[0] = x * a[0];
  3687. out[1] = x * a[1];
  3688. out[2] = x * a[2];
  3689. out[3] = y * a[3];
  3690. out[4] = y * a[4];
  3691. out[5] = y * a[5];
  3692. out[6] = a[6];
  3693. out[7] = a[7];
  3694. out[8] = a[8];
  3695. return out;
  3696. }
  3697. /**
  3698. * Calculates a 3x3 matrix from the given quaternion
  3699. *
  3700. * @param {mat3} out mat3 receiving operation result
  3701. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3702. *
  3703. * @returns {mat3} out
  3704. */
  3705. function fromQuat$1(out, q) {
  3706. var x = q[0],
  3707. y = q[1],
  3708. z = q[2],
  3709. w = q[3];
  3710. var x2 = x + x;
  3711. var y2 = y + y;
  3712. var z2 = z + z;
  3713. var xx = x * x2;
  3714. var yx = y * x2;
  3715. var yy = y * y2;
  3716. var zx = z * x2;
  3717. var zy = z * y2;
  3718. var zz = z * z2;
  3719. var wx = w * x2;
  3720. var wy = w * y2;
  3721. var wz = w * z2;
  3722. out[0] = 1 - yy - zz;
  3723. out[3] = yx - wz;
  3724. out[6] = zx + wy;
  3725. out[1] = yx + wz;
  3726. out[4] = 1 - xx - zz;
  3727. out[7] = zy - wx;
  3728. out[2] = zx - wy;
  3729. out[5] = zy + wx;
  3730. out[8] = 1 - xx - yy;
  3731. return out;
  3732. }
  3733. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3734. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3735. const INDICES$1 = Object.freeze({
  3736. COL0ROW0: 0,
  3737. COL0ROW1: 1,
  3738. COL0ROW2: 2,
  3739. COL1ROW0: 3,
  3740. COL1ROW1: 4,
  3741. COL1ROW2: 5,
  3742. COL2ROW0: 6,
  3743. COL2ROW1: 7,
  3744. COL2ROW2: 8
  3745. });
  3746. const constants$1 = {};
  3747. class Matrix3 extends Matrix {
  3748. static get IDENTITY() {
  3749. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3750. return constants$1.IDENTITY;
  3751. }
  3752. static get ZERO() {
  3753. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3754. return constants$1.ZERO;
  3755. }
  3756. get ELEMENTS() {
  3757. return 9;
  3758. }
  3759. get RANK() {
  3760. return 3;
  3761. }
  3762. get INDICES() {
  3763. return INDICES$1;
  3764. }
  3765. constructor(array) {
  3766. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3767. if (arguments.length === 1 && Array.isArray(array)) {
  3768. this.copy(array);
  3769. } else {
  3770. this.identity();
  3771. }
  3772. }
  3773. copy(array) {
  3774. this[0] = array[0];
  3775. this[1] = array[1];
  3776. this[2] = array[2];
  3777. this[3] = array[3];
  3778. this[4] = array[4];
  3779. this[5] = array[5];
  3780. this[6] = array[6];
  3781. this[7] = array[7];
  3782. this[8] = array[8];
  3783. return this.check();
  3784. }
  3785. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3786. this[0] = m00;
  3787. this[1] = m10;
  3788. this[2] = m20;
  3789. this[3] = m01;
  3790. this[4] = m11;
  3791. this[5] = m21;
  3792. this[6] = m02;
  3793. this[7] = m12;
  3794. this[8] = m22;
  3795. return this.check();
  3796. }
  3797. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3798. this[0] = m00;
  3799. this[1] = m10;
  3800. this[2] = m20;
  3801. this[3] = m01;
  3802. this[4] = m11;
  3803. this[5] = m21;
  3804. this[6] = m02;
  3805. this[7] = m12;
  3806. this[8] = m22;
  3807. return this.check();
  3808. }
  3809. determinant() {
  3810. return determinant$1(this);
  3811. }
  3812. identity() {
  3813. return this.copy(IDENTITY$1);
  3814. }
  3815. fromQuaternion(q) {
  3816. fromQuat$1(this, q);
  3817. return this.check();
  3818. }
  3819. transpose() {
  3820. transpose$1(this, this);
  3821. return this.check();
  3822. }
  3823. invert() {
  3824. invert$2(this, this);
  3825. return this.check();
  3826. }
  3827. multiplyLeft(a) {
  3828. multiply$2(this, a, this);
  3829. return this.check();
  3830. }
  3831. multiplyRight(a) {
  3832. multiply$2(this, this, a);
  3833. return this.check();
  3834. }
  3835. rotate(radians) {
  3836. rotate$1(this, this, radians);
  3837. return this.check();
  3838. }
  3839. scale(factor) {
  3840. if (Array.isArray(factor)) {
  3841. scale$3(this, this, factor);
  3842. } else {
  3843. scale$3(this, this, [factor, factor, factor]);
  3844. }
  3845. return this.check();
  3846. }
  3847. translate(vec) {
  3848. translate$1(this, this, vec);
  3849. return this.check();
  3850. }
  3851. transform(vector, result) {
  3852. switch (vector.length) {
  3853. case 2:
  3854. result = transformMat3$1(result || [-0, -0], vector, this);
  3855. break;
  3856. case 3:
  3857. result = transformMat3(result || [-0, -0, -0], vector, this);
  3858. break;
  3859. case 4:
  3860. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3861. break;
  3862. default:
  3863. throw new Error('Illegal vector');
  3864. }
  3865. checkVector(result, vector.length);
  3866. return result;
  3867. }
  3868. transformVector(vector, result) {
  3869. deprecated('Matrix3.transformVector');
  3870. return this.transform(vector, result);
  3871. }
  3872. transformVector2(vector, result) {
  3873. deprecated('Matrix3.transformVector');
  3874. return this.transform(vector, result);
  3875. }
  3876. transformVector3(vector, result) {
  3877. deprecated('Matrix3.transformVector');
  3878. return this.transform(vector, result);
  3879. }
  3880. }
  3881. /**
  3882. * Set a mat4 to the identity matrix
  3883. *
  3884. * @param {mat4} out the receiving matrix
  3885. * @returns {mat4} out
  3886. */
  3887. function identity$1(out) {
  3888. out[0] = 1;
  3889. out[1] = 0;
  3890. out[2] = 0;
  3891. out[3] = 0;
  3892. out[4] = 0;
  3893. out[5] = 1;
  3894. out[6] = 0;
  3895. out[7] = 0;
  3896. out[8] = 0;
  3897. out[9] = 0;
  3898. out[10] = 1;
  3899. out[11] = 0;
  3900. out[12] = 0;
  3901. out[13] = 0;
  3902. out[14] = 0;
  3903. out[15] = 1;
  3904. return out;
  3905. }
  3906. /**
  3907. * Transpose the values of a mat4
  3908. *
  3909. * @param {mat4} out the receiving matrix
  3910. * @param {ReadonlyMat4} a the source matrix
  3911. * @returns {mat4} out
  3912. */
  3913. function transpose(out, a) {
  3914. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3915. if (out === a) {
  3916. var a01 = a[1],
  3917. a02 = a[2],
  3918. a03 = a[3];
  3919. var a12 = a[6],
  3920. a13 = a[7];
  3921. var a23 = a[11];
  3922. out[1] = a[4];
  3923. out[2] = a[8];
  3924. out[3] = a[12];
  3925. out[4] = a01;
  3926. out[6] = a[9];
  3927. out[7] = a[13];
  3928. out[8] = a02;
  3929. out[9] = a12;
  3930. out[11] = a[14];
  3931. out[12] = a03;
  3932. out[13] = a13;
  3933. out[14] = a23;
  3934. } else {
  3935. out[0] = a[0];
  3936. out[1] = a[4];
  3937. out[2] = a[8];
  3938. out[3] = a[12];
  3939. out[4] = a[1];
  3940. out[5] = a[5];
  3941. out[6] = a[9];
  3942. out[7] = a[13];
  3943. out[8] = a[2];
  3944. out[9] = a[6];
  3945. out[10] = a[10];
  3946. out[11] = a[14];
  3947. out[12] = a[3];
  3948. out[13] = a[7];
  3949. out[14] = a[11];
  3950. out[15] = a[15];
  3951. }
  3952. return out;
  3953. }
  3954. /**
  3955. * Inverts a mat4
  3956. *
  3957. * @param {mat4} out the receiving matrix
  3958. * @param {ReadonlyMat4} a the source matrix
  3959. * @returns {mat4} out
  3960. */
  3961. function invert$1(out, a) {
  3962. var a00 = a[0],
  3963. a01 = a[1],
  3964. a02 = a[2],
  3965. a03 = a[3];
  3966. var a10 = a[4],
  3967. a11 = a[5],
  3968. a12 = a[6],
  3969. a13 = a[7];
  3970. var a20 = a[8],
  3971. a21 = a[9],
  3972. a22 = a[10],
  3973. a23 = a[11];
  3974. var a30 = a[12],
  3975. a31 = a[13],
  3976. a32 = a[14],
  3977. a33 = a[15];
  3978. var b00 = a00 * a11 - a01 * a10;
  3979. var b01 = a00 * a12 - a02 * a10;
  3980. var b02 = a00 * a13 - a03 * a10;
  3981. var b03 = a01 * a12 - a02 * a11;
  3982. var b04 = a01 * a13 - a03 * a11;
  3983. var b05 = a02 * a13 - a03 * a12;
  3984. var b06 = a20 * a31 - a21 * a30;
  3985. var b07 = a20 * a32 - a22 * a30;
  3986. var b08 = a20 * a33 - a23 * a30;
  3987. var b09 = a21 * a32 - a22 * a31;
  3988. var b10 = a21 * a33 - a23 * a31;
  3989. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  3990. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  3991. if (!det) {
  3992. return null;
  3993. }
  3994. det = 1.0 / det;
  3995. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  3996. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  3997. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  3998. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  3999. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4000. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4001. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4002. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4003. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4004. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4005. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4006. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4007. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4008. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4009. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4010. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4011. return out;
  4012. }
  4013. /**
  4014. * Calculates the determinant of a mat4
  4015. *
  4016. * @param {ReadonlyMat4} a the source matrix
  4017. * @returns {Number} determinant of a
  4018. */
  4019. function determinant(a) {
  4020. var a00 = a[0],
  4021. a01 = a[1],
  4022. a02 = a[2],
  4023. a03 = a[3];
  4024. var a10 = a[4],
  4025. a11 = a[5],
  4026. a12 = a[6],
  4027. a13 = a[7];
  4028. var a20 = a[8],
  4029. a21 = a[9],
  4030. a22 = a[10],
  4031. a23 = a[11];
  4032. var a30 = a[12],
  4033. a31 = a[13],
  4034. a32 = a[14],
  4035. a33 = a[15];
  4036. var b00 = a00 * a11 - a01 * a10;
  4037. var b01 = a00 * a12 - a02 * a10;
  4038. var b02 = a00 * a13 - a03 * a10;
  4039. var b03 = a01 * a12 - a02 * a11;
  4040. var b04 = a01 * a13 - a03 * a11;
  4041. var b05 = a02 * a13 - a03 * a12;
  4042. var b06 = a20 * a31 - a21 * a30;
  4043. var b07 = a20 * a32 - a22 * a30;
  4044. var b08 = a20 * a33 - a23 * a30;
  4045. var b09 = a21 * a32 - a22 * a31;
  4046. var b10 = a21 * a33 - a23 * a31;
  4047. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4048. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4049. }
  4050. /**
  4051. * Multiplies two mat4s
  4052. *
  4053. * @param {mat4} out the receiving matrix
  4054. * @param {ReadonlyMat4} a the first operand
  4055. * @param {ReadonlyMat4} b the second operand
  4056. * @returns {mat4} out
  4057. */
  4058. function multiply$1(out, a, b) {
  4059. var a00 = a[0],
  4060. a01 = a[1],
  4061. a02 = a[2],
  4062. a03 = a[3];
  4063. var a10 = a[4],
  4064. a11 = a[5],
  4065. a12 = a[6],
  4066. a13 = a[7];
  4067. var a20 = a[8],
  4068. a21 = a[9],
  4069. a22 = a[10],
  4070. a23 = a[11];
  4071. var a30 = a[12],
  4072. a31 = a[13],
  4073. a32 = a[14],
  4074. a33 = a[15]; // Cache only the current line of the second matrix
  4075. var b0 = b[0],
  4076. b1 = b[1],
  4077. b2 = b[2],
  4078. b3 = b[3];
  4079. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4080. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4081. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4082. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4083. b0 = b[4];
  4084. b1 = b[5];
  4085. b2 = b[6];
  4086. b3 = b[7];
  4087. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4088. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4089. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4090. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4091. b0 = b[8];
  4092. b1 = b[9];
  4093. b2 = b[10];
  4094. b3 = b[11];
  4095. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4096. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4097. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4098. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4099. b0 = b[12];
  4100. b1 = b[13];
  4101. b2 = b[14];
  4102. b3 = b[15];
  4103. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4104. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4105. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4106. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4107. return out;
  4108. }
  4109. /**
  4110. * Translate a mat4 by the given vector
  4111. *
  4112. * @param {mat4} out the receiving matrix
  4113. * @param {ReadonlyMat4} a the matrix to translate
  4114. * @param {ReadonlyVec3} v vector to translate by
  4115. * @returns {mat4} out
  4116. */
  4117. function translate(out, a, v) {
  4118. var x = v[0],
  4119. y = v[1],
  4120. z = v[2];
  4121. var a00, a01, a02, a03;
  4122. var a10, a11, a12, a13;
  4123. var a20, a21, a22, a23;
  4124. if (a === out) {
  4125. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4126. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4127. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4128. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4129. } else {
  4130. a00 = a[0];
  4131. a01 = a[1];
  4132. a02 = a[2];
  4133. a03 = a[3];
  4134. a10 = a[4];
  4135. a11 = a[5];
  4136. a12 = a[6];
  4137. a13 = a[7];
  4138. a20 = a[8];
  4139. a21 = a[9];
  4140. a22 = a[10];
  4141. a23 = a[11];
  4142. out[0] = a00;
  4143. out[1] = a01;
  4144. out[2] = a02;
  4145. out[3] = a03;
  4146. out[4] = a10;
  4147. out[5] = a11;
  4148. out[6] = a12;
  4149. out[7] = a13;
  4150. out[8] = a20;
  4151. out[9] = a21;
  4152. out[10] = a22;
  4153. out[11] = a23;
  4154. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4155. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4156. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4157. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4158. }
  4159. return out;
  4160. }
  4161. /**
  4162. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4163. *
  4164. * @param {mat4} out the receiving matrix
  4165. * @param {ReadonlyMat4} a the matrix to scale
  4166. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4167. * @returns {mat4} out
  4168. **/
  4169. function scale$2(out, a, v) {
  4170. var x = v[0],
  4171. y = v[1],
  4172. z = v[2];
  4173. out[0] = a[0] * x;
  4174. out[1] = a[1] * x;
  4175. out[2] = a[2] * x;
  4176. out[3] = a[3] * x;
  4177. out[4] = a[4] * y;
  4178. out[5] = a[5] * y;
  4179. out[6] = a[6] * y;
  4180. out[7] = a[7] * y;
  4181. out[8] = a[8] * z;
  4182. out[9] = a[9] * z;
  4183. out[10] = a[10] * z;
  4184. out[11] = a[11] * z;
  4185. out[12] = a[12];
  4186. out[13] = a[13];
  4187. out[14] = a[14];
  4188. out[15] = a[15];
  4189. return out;
  4190. }
  4191. /**
  4192. * Rotates a mat4 by the given angle around the given axis
  4193. *
  4194. * @param {mat4} out the receiving matrix
  4195. * @param {ReadonlyMat4} a the matrix to rotate
  4196. * @param {Number} rad the angle to rotate the matrix by
  4197. * @param {ReadonlyVec3} axis the axis to rotate around
  4198. * @returns {mat4} out
  4199. */
  4200. function rotate(out, a, rad, axis) {
  4201. var x = axis[0],
  4202. y = axis[1],
  4203. z = axis[2];
  4204. var len = Math.hypot(x, y, z);
  4205. var s, c, t;
  4206. var a00, a01, a02, a03;
  4207. var a10, a11, a12, a13;
  4208. var a20, a21, a22, a23;
  4209. var b00, b01, b02;
  4210. var b10, b11, b12;
  4211. var b20, b21, b22;
  4212. if (len < EPSILON) {
  4213. return null;
  4214. }
  4215. len = 1 / len;
  4216. x *= len;
  4217. y *= len;
  4218. z *= len;
  4219. s = Math.sin(rad);
  4220. c = Math.cos(rad);
  4221. t = 1 - c;
  4222. a00 = a[0];
  4223. a01 = a[1];
  4224. a02 = a[2];
  4225. a03 = a[3];
  4226. a10 = a[4];
  4227. a11 = a[5];
  4228. a12 = a[6];
  4229. a13 = a[7];
  4230. a20 = a[8];
  4231. a21 = a[9];
  4232. a22 = a[10];
  4233. a23 = a[11]; // Construct the elements of the rotation matrix
  4234. b00 = x * x * t + c;
  4235. b01 = y * x * t + z * s;
  4236. b02 = z * x * t - y * s;
  4237. b10 = x * y * t - z * s;
  4238. b11 = y * y * t + c;
  4239. b12 = z * y * t + x * s;
  4240. b20 = x * z * t + y * s;
  4241. b21 = y * z * t - x * s;
  4242. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4243. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4244. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4245. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4246. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4247. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4248. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4249. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4250. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4251. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4252. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4253. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4254. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4255. if (a !== out) {
  4256. // If the source and destination differ, copy the unchanged last row
  4257. out[12] = a[12];
  4258. out[13] = a[13];
  4259. out[14] = a[14];
  4260. out[15] = a[15];
  4261. }
  4262. return out;
  4263. }
  4264. /**
  4265. * Rotates a matrix by the given angle around the X axis
  4266. *
  4267. * @param {mat4} out the receiving matrix
  4268. * @param {ReadonlyMat4} a the matrix to rotate
  4269. * @param {Number} rad the angle to rotate the matrix by
  4270. * @returns {mat4} out
  4271. */
  4272. function rotateX$1(out, a, rad) {
  4273. var s = Math.sin(rad);
  4274. var c = Math.cos(rad);
  4275. var a10 = a[4];
  4276. var a11 = a[5];
  4277. var a12 = a[6];
  4278. var a13 = a[7];
  4279. var a20 = a[8];
  4280. var a21 = a[9];
  4281. var a22 = a[10];
  4282. var a23 = a[11];
  4283. if (a !== out) {
  4284. // If the source and destination differ, copy the unchanged rows
  4285. out[0] = a[0];
  4286. out[1] = a[1];
  4287. out[2] = a[2];
  4288. out[3] = a[3];
  4289. out[12] = a[12];
  4290. out[13] = a[13];
  4291. out[14] = a[14];
  4292. out[15] = a[15];
  4293. } // Perform axis-specific matrix multiplication
  4294. out[4] = a10 * c + a20 * s;
  4295. out[5] = a11 * c + a21 * s;
  4296. out[6] = a12 * c + a22 * s;
  4297. out[7] = a13 * c + a23 * s;
  4298. out[8] = a20 * c - a10 * s;
  4299. out[9] = a21 * c - a11 * s;
  4300. out[10] = a22 * c - a12 * s;
  4301. out[11] = a23 * c - a13 * s;
  4302. return out;
  4303. }
  4304. /**
  4305. * Rotates a matrix by the given angle around the Y axis
  4306. *
  4307. * @param {mat4} out the receiving matrix
  4308. * @param {ReadonlyMat4} a the matrix to rotate
  4309. * @param {Number} rad the angle to rotate the matrix by
  4310. * @returns {mat4} out
  4311. */
  4312. function rotateY$1(out, a, rad) {
  4313. var s = Math.sin(rad);
  4314. var c = Math.cos(rad);
  4315. var a00 = a[0];
  4316. var a01 = a[1];
  4317. var a02 = a[2];
  4318. var a03 = a[3];
  4319. var a20 = a[8];
  4320. var a21 = a[9];
  4321. var a22 = a[10];
  4322. var a23 = a[11];
  4323. if (a !== out) {
  4324. // If the source and destination differ, copy the unchanged rows
  4325. out[4] = a[4];
  4326. out[5] = a[5];
  4327. out[6] = a[6];
  4328. out[7] = a[7];
  4329. out[12] = a[12];
  4330. out[13] = a[13];
  4331. out[14] = a[14];
  4332. out[15] = a[15];
  4333. } // Perform axis-specific matrix multiplication
  4334. out[0] = a00 * c - a20 * s;
  4335. out[1] = a01 * c - a21 * s;
  4336. out[2] = a02 * c - a22 * s;
  4337. out[3] = a03 * c - a23 * s;
  4338. out[8] = a00 * s + a20 * c;
  4339. out[9] = a01 * s + a21 * c;
  4340. out[10] = a02 * s + a22 * c;
  4341. out[11] = a03 * s + a23 * c;
  4342. return out;
  4343. }
  4344. /**
  4345. * Rotates a matrix by the given angle around the Z axis
  4346. *
  4347. * @param {mat4} out the receiving matrix
  4348. * @param {ReadonlyMat4} a the matrix to rotate
  4349. * @param {Number} rad the angle to rotate the matrix by
  4350. * @returns {mat4} out
  4351. */
  4352. function rotateZ$1(out, a, rad) {
  4353. var s = Math.sin(rad);
  4354. var c = Math.cos(rad);
  4355. var a00 = a[0];
  4356. var a01 = a[1];
  4357. var a02 = a[2];
  4358. var a03 = a[3];
  4359. var a10 = a[4];
  4360. var a11 = a[5];
  4361. var a12 = a[6];
  4362. var a13 = a[7];
  4363. if (a !== out) {
  4364. // If the source and destination differ, copy the unchanged last row
  4365. out[8] = a[8];
  4366. out[9] = a[9];
  4367. out[10] = a[10];
  4368. out[11] = a[11];
  4369. out[12] = a[12];
  4370. out[13] = a[13];
  4371. out[14] = a[14];
  4372. out[15] = a[15];
  4373. } // Perform axis-specific matrix multiplication
  4374. out[0] = a00 * c + a10 * s;
  4375. out[1] = a01 * c + a11 * s;
  4376. out[2] = a02 * c + a12 * s;
  4377. out[3] = a03 * c + a13 * s;
  4378. out[4] = a10 * c - a00 * s;
  4379. out[5] = a11 * c - a01 * s;
  4380. out[6] = a12 * c - a02 * s;
  4381. out[7] = a13 * c - a03 * s;
  4382. return out;
  4383. }
  4384. /**
  4385. * Returns the scaling factor component of a transformation
  4386. * matrix. If a matrix is built with fromRotationTranslationScale
  4387. * with a normalized Quaternion paramter, the returned vector will be
  4388. * the same as the scaling vector
  4389. * originally supplied.
  4390. * @param {vec3} out Vector to receive scaling factor component
  4391. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4392. * @return {vec3} out
  4393. */
  4394. function getScaling(out, mat) {
  4395. var m11 = mat[0];
  4396. var m12 = mat[1];
  4397. var m13 = mat[2];
  4398. var m21 = mat[4];
  4399. var m22 = mat[5];
  4400. var m23 = mat[6];
  4401. var m31 = mat[8];
  4402. var m32 = mat[9];
  4403. var m33 = mat[10];
  4404. out[0] = Math.hypot(m11, m12, m13);
  4405. out[1] = Math.hypot(m21, m22, m23);
  4406. out[2] = Math.hypot(m31, m32, m33);
  4407. return out;
  4408. }
  4409. /**
  4410. * Calculates a 4x4 matrix from the given quaternion
  4411. *
  4412. * @param {mat4} out mat4 receiving operation result
  4413. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4414. *
  4415. * @returns {mat4} out
  4416. */
  4417. function fromQuat(out, q) {
  4418. var x = q[0],
  4419. y = q[1],
  4420. z = q[2],
  4421. w = q[3];
  4422. var x2 = x + x;
  4423. var y2 = y + y;
  4424. var z2 = z + z;
  4425. var xx = x * x2;
  4426. var yx = y * x2;
  4427. var yy = y * y2;
  4428. var zx = z * x2;
  4429. var zy = z * y2;
  4430. var zz = z * z2;
  4431. var wx = w * x2;
  4432. var wy = w * y2;
  4433. var wz = w * z2;
  4434. out[0] = 1 - yy - zz;
  4435. out[1] = yx + wz;
  4436. out[2] = zx - wy;
  4437. out[3] = 0;
  4438. out[4] = yx - wz;
  4439. out[5] = 1 - xx - zz;
  4440. out[6] = zy + wx;
  4441. out[7] = 0;
  4442. out[8] = zx + wy;
  4443. out[9] = zy - wx;
  4444. out[10] = 1 - xx - yy;
  4445. out[11] = 0;
  4446. out[12] = 0;
  4447. out[13] = 0;
  4448. out[14] = 0;
  4449. out[15] = 1;
  4450. return out;
  4451. }
  4452. /**
  4453. * Generates a frustum matrix with the given bounds
  4454. *
  4455. * @param {mat4} out mat4 frustum matrix will be written into
  4456. * @param {Number} left Left bound of the frustum
  4457. * @param {Number} right Right bound of the frustum
  4458. * @param {Number} bottom Bottom bound of the frustum
  4459. * @param {Number} top Top bound of the frustum
  4460. * @param {Number} near Near bound of the frustum
  4461. * @param {Number} far Far bound of the frustum
  4462. * @returns {mat4} out
  4463. */
  4464. function frustum(out, left, right, bottom, top, near, far) {
  4465. var rl = 1 / (right - left);
  4466. var tb = 1 / (top - bottom);
  4467. var nf = 1 / (near - far);
  4468. out[0] = near * 2 * rl;
  4469. out[1] = 0;
  4470. out[2] = 0;
  4471. out[3] = 0;
  4472. out[4] = 0;
  4473. out[5] = near * 2 * tb;
  4474. out[6] = 0;
  4475. out[7] = 0;
  4476. out[8] = (right + left) * rl;
  4477. out[9] = (top + bottom) * tb;
  4478. out[10] = (far + near) * nf;
  4479. out[11] = -1;
  4480. out[12] = 0;
  4481. out[13] = 0;
  4482. out[14] = far * near * 2 * nf;
  4483. out[15] = 0;
  4484. return out;
  4485. }
  4486. /**
  4487. * Generates a perspective projection matrix with the given bounds.
  4488. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4489. *
  4490. * @param {mat4} out mat4 frustum matrix will be written into
  4491. * @param {number} fovy Vertical field of view in radians
  4492. * @param {number} aspect Aspect ratio. typically viewport width/height
  4493. * @param {number} near Near bound of the frustum
  4494. * @param {number} far Far bound of the frustum, can be null or Infinity
  4495. * @returns {mat4} out
  4496. */
  4497. function perspective(out, fovy, aspect, near, far) {
  4498. var f = 1.0 / Math.tan(fovy / 2),
  4499. nf;
  4500. out[0] = f / aspect;
  4501. out[1] = 0;
  4502. out[2] = 0;
  4503. out[3] = 0;
  4504. out[4] = 0;
  4505. out[5] = f;
  4506. out[6] = 0;
  4507. out[7] = 0;
  4508. out[8] = 0;
  4509. out[9] = 0;
  4510. out[11] = -1;
  4511. out[12] = 0;
  4512. out[13] = 0;
  4513. out[15] = 0;
  4514. if (far != null && far !== Infinity) {
  4515. nf = 1 / (near - far);
  4516. out[10] = (far + near) * nf;
  4517. out[14] = 2 * far * near * nf;
  4518. } else {
  4519. out[10] = -1;
  4520. out[14] = -2 * near;
  4521. }
  4522. return out;
  4523. }
  4524. /**
  4525. * Generates a orthogonal projection matrix with the given bounds
  4526. *
  4527. * @param {mat4} out mat4 frustum matrix will be written into
  4528. * @param {number} left Left bound of the frustum
  4529. * @param {number} right Right bound of the frustum
  4530. * @param {number} bottom Bottom bound of the frustum
  4531. * @param {number} top Top bound of the frustum
  4532. * @param {number} near Near bound of the frustum
  4533. * @param {number} far Far bound of the frustum
  4534. * @returns {mat4} out
  4535. */
  4536. function ortho(out, left, right, bottom, top, near, far) {
  4537. var lr = 1 / (left - right);
  4538. var bt = 1 / (bottom - top);
  4539. var nf = 1 / (near - far);
  4540. out[0] = -2 * lr;
  4541. out[1] = 0;
  4542. out[2] = 0;
  4543. out[3] = 0;
  4544. out[4] = 0;
  4545. out[5] = -2 * bt;
  4546. out[6] = 0;
  4547. out[7] = 0;
  4548. out[8] = 0;
  4549. out[9] = 0;
  4550. out[10] = 2 * nf;
  4551. out[11] = 0;
  4552. out[12] = (left + right) * lr;
  4553. out[13] = (top + bottom) * bt;
  4554. out[14] = (far + near) * nf;
  4555. out[15] = 1;
  4556. return out;
  4557. }
  4558. /**
  4559. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4560. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4561. *
  4562. * @param {mat4} out mat4 frustum matrix will be written into
  4563. * @param {ReadonlyVec3} eye Position of the viewer
  4564. * @param {ReadonlyVec3} center Point the viewer is looking at
  4565. * @param {ReadonlyVec3} up vec3 pointing up
  4566. * @returns {mat4} out
  4567. */
  4568. function lookAt(out, eye, center, up) {
  4569. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4570. var eyex = eye[0];
  4571. var eyey = eye[1];
  4572. var eyez = eye[2];
  4573. var upx = up[0];
  4574. var upy = up[1];
  4575. var upz = up[2];
  4576. var centerx = center[0];
  4577. var centery = center[1];
  4578. var centerz = center[2];
  4579. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4580. return identity$1(out);
  4581. }
  4582. z0 = eyex - centerx;
  4583. z1 = eyey - centery;
  4584. z2 = eyez - centerz;
  4585. len = 1 / Math.hypot(z0, z1, z2);
  4586. z0 *= len;
  4587. z1 *= len;
  4588. z2 *= len;
  4589. x0 = upy * z2 - upz * z1;
  4590. x1 = upz * z0 - upx * z2;
  4591. x2 = upx * z1 - upy * z0;
  4592. len = Math.hypot(x0, x1, x2);
  4593. if (!len) {
  4594. x0 = 0;
  4595. x1 = 0;
  4596. x2 = 0;
  4597. } else {
  4598. len = 1 / len;
  4599. x0 *= len;
  4600. x1 *= len;
  4601. x2 *= len;
  4602. }
  4603. y0 = z1 * x2 - z2 * x1;
  4604. y1 = z2 * x0 - z0 * x2;
  4605. y2 = z0 * x1 - z1 * x0;
  4606. len = Math.hypot(y0, y1, y2);
  4607. if (!len) {
  4608. y0 = 0;
  4609. y1 = 0;
  4610. y2 = 0;
  4611. } else {
  4612. len = 1 / len;
  4613. y0 *= len;
  4614. y1 *= len;
  4615. y2 *= len;
  4616. }
  4617. out[0] = x0;
  4618. out[1] = y0;
  4619. out[2] = z0;
  4620. out[3] = 0;
  4621. out[4] = x1;
  4622. out[5] = y1;
  4623. out[6] = z1;
  4624. out[7] = 0;
  4625. out[8] = x2;
  4626. out[9] = y2;
  4627. out[10] = z2;
  4628. out[11] = 0;
  4629. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4630. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4631. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4632. out[15] = 1;
  4633. return out;
  4634. }
  4635. /**
  4636. * 4 Dimensional Vector
  4637. * @module vec4
  4638. */
  4639. /**
  4640. * Creates a new, empty vec4
  4641. *
  4642. * @returns {vec4} a new 4D vector
  4643. */
  4644. function create$1() {
  4645. var out = new ARRAY_TYPE(4);
  4646. if (ARRAY_TYPE != Float32Array) {
  4647. out[0] = 0;
  4648. out[1] = 0;
  4649. out[2] = 0;
  4650. out[3] = 0;
  4651. }
  4652. return out;
  4653. }
  4654. /**
  4655. * Adds two vec4's
  4656. *
  4657. * @param {vec4} out the receiving vector
  4658. * @param {ReadonlyVec4} a the first operand
  4659. * @param {ReadonlyVec4} b the second operand
  4660. * @returns {vec4} out
  4661. */
  4662. function add$1(out, a, b) {
  4663. out[0] = a[0] + b[0];
  4664. out[1] = a[1] + b[1];
  4665. out[2] = a[2] + b[2];
  4666. out[3] = a[3] + b[3];
  4667. return out;
  4668. }
  4669. /**
  4670. * Scales a vec4 by a scalar number
  4671. *
  4672. * @param {vec4} out the receiving vector
  4673. * @param {ReadonlyVec4} a the vector to scale
  4674. * @param {Number} b amount to scale the vector by
  4675. * @returns {vec4} out
  4676. */
  4677. function scale$1(out, a, b) {
  4678. out[0] = a[0] * b;
  4679. out[1] = a[1] * b;
  4680. out[2] = a[2] * b;
  4681. out[3] = a[3] * b;
  4682. return out;
  4683. }
  4684. /**
  4685. * Calculates the length of a vec4
  4686. *
  4687. * @param {ReadonlyVec4} a vector to calculate length of
  4688. * @returns {Number} length of a
  4689. */
  4690. function length$1(a) {
  4691. var x = a[0];
  4692. var y = a[1];
  4693. var z = a[2];
  4694. var w = a[3];
  4695. return Math.hypot(x, y, z, w);
  4696. }
  4697. /**
  4698. * Calculates the squared length of a vec4
  4699. *
  4700. * @param {ReadonlyVec4} a vector to calculate squared length of
  4701. * @returns {Number} squared length of a
  4702. */
  4703. function squaredLength$1(a) {
  4704. var x = a[0];
  4705. var y = a[1];
  4706. var z = a[2];
  4707. var w = a[3];
  4708. return x * x + y * y + z * z + w * w;
  4709. }
  4710. /**
  4711. * Normalize a vec4
  4712. *
  4713. * @param {vec4} out the receiving vector
  4714. * @param {ReadonlyVec4} a vector to normalize
  4715. * @returns {vec4} out
  4716. */
  4717. function normalize$1(out, a) {
  4718. var x = a[0];
  4719. var y = a[1];
  4720. var z = a[2];
  4721. var w = a[3];
  4722. var len = x * x + y * y + z * z + w * w;
  4723. if (len > 0) {
  4724. len = 1 / Math.sqrt(len);
  4725. }
  4726. out[0] = x * len;
  4727. out[1] = y * len;
  4728. out[2] = z * len;
  4729. out[3] = w * len;
  4730. return out;
  4731. }
  4732. /**
  4733. * Calculates the dot product of two vec4's
  4734. *
  4735. * @param {ReadonlyVec4} a the first operand
  4736. * @param {ReadonlyVec4} b the second operand
  4737. * @returns {Number} dot product of a and b
  4738. */
  4739. function dot$1(a, b) {
  4740. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4741. }
  4742. /**
  4743. * Performs a linear interpolation between two vec4's
  4744. *
  4745. * @param {vec4} out the receiving vector
  4746. * @param {ReadonlyVec4} a the first operand
  4747. * @param {ReadonlyVec4} b the second operand
  4748. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4749. * @returns {vec4} out
  4750. */
  4751. function lerp$1(out, a, b, t) {
  4752. var ax = a[0];
  4753. var ay = a[1];
  4754. var az = a[2];
  4755. var aw = a[3];
  4756. out[0] = ax + t * (b[0] - ax);
  4757. out[1] = ay + t * (b[1] - ay);
  4758. out[2] = az + t * (b[2] - az);
  4759. out[3] = aw + t * (b[3] - aw);
  4760. return out;
  4761. }
  4762. /**
  4763. * Transforms the vec4 with a mat4.
  4764. *
  4765. * @param {vec4} out the receiving vector
  4766. * @param {ReadonlyVec4} a the vector to transform
  4767. * @param {ReadonlyMat4} m matrix to transform with
  4768. * @returns {vec4} out
  4769. */
  4770. function transformMat4(out, a, m) {
  4771. var x = a[0],
  4772. y = a[1],
  4773. z = a[2],
  4774. w = a[3];
  4775. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4776. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4777. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4778. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4779. return out;
  4780. }
  4781. /**
  4782. * Transforms the vec4 with a quat
  4783. *
  4784. * @param {vec4} out the receiving vector
  4785. * @param {ReadonlyVec4} a the vector to transform
  4786. * @param {ReadonlyQuat} q quaternion to transform with
  4787. * @returns {vec4} out
  4788. */
  4789. function transformQuat(out, a, q) {
  4790. var x = a[0],
  4791. y = a[1],
  4792. z = a[2];
  4793. var qx = q[0],
  4794. qy = q[1],
  4795. qz = q[2],
  4796. qw = q[3]; // calculate quat * vec
  4797. var ix = qw * x + qy * z - qz * y;
  4798. var iy = qw * y + qz * x - qx * z;
  4799. var iz = qw * z + qx * y - qy * x;
  4800. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4801. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4802. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4803. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4804. out[3] = a[3];
  4805. return out;
  4806. }
  4807. /**
  4808. * Perform some operation over an array of vec4s.
  4809. *
  4810. * @param {Array} a the array of vectors to iterate over
  4811. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4812. * @param {Number} offset Number of elements to skip at the beginning of the array
  4813. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4814. * @param {Function} fn Function to call for each vector in the array
  4815. * @param {Object} [arg] additional argument to pass to fn
  4816. * @returns {Array} a
  4817. * @function
  4818. */
  4819. (function () {
  4820. var vec = create$1();
  4821. return function (a, stride, offset, count, fn, arg) {
  4822. var i, l;
  4823. if (!stride) {
  4824. stride = 4;
  4825. }
  4826. if (!offset) {
  4827. offset = 0;
  4828. }
  4829. if (count) {
  4830. l = Math.min(count * stride + offset, a.length);
  4831. } else {
  4832. l = a.length;
  4833. }
  4834. for (i = offset; i < l; i += stride) {
  4835. vec[0] = a[i];
  4836. vec[1] = a[i + 1];
  4837. vec[2] = a[i + 2];
  4838. vec[3] = a[i + 3];
  4839. fn(vec, vec, arg);
  4840. a[i] = vec[0];
  4841. a[i + 1] = vec[1];
  4842. a[i + 2] = vec[2];
  4843. a[i + 3] = vec[3];
  4844. }
  4845. return a;
  4846. };
  4847. })();
  4848. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4849. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4850. const INDICES = Object.freeze({
  4851. COL0ROW0: 0,
  4852. COL0ROW1: 1,
  4853. COL0ROW2: 2,
  4854. COL0ROW3: 3,
  4855. COL1ROW0: 4,
  4856. COL1ROW1: 5,
  4857. COL1ROW2: 6,
  4858. COL1ROW3: 7,
  4859. COL2ROW0: 8,
  4860. COL2ROW1: 9,
  4861. COL2ROW2: 10,
  4862. COL2ROW3: 11,
  4863. COL3ROW0: 12,
  4864. COL3ROW1: 13,
  4865. COL3ROW2: 14,
  4866. COL3ROW3: 15
  4867. });
  4868. const constants = {};
  4869. class Matrix4 extends Matrix {
  4870. static get IDENTITY() {
  4871. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4872. return constants.IDENTITY;
  4873. }
  4874. static get ZERO() {
  4875. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4876. return constants.ZERO;
  4877. }
  4878. get INDICES() {
  4879. return INDICES;
  4880. }
  4881. get ELEMENTS() {
  4882. return 16;
  4883. }
  4884. get RANK() {
  4885. return 4;
  4886. }
  4887. constructor(array) {
  4888. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4889. if (arguments.length === 1 && Array.isArray(array)) {
  4890. this.copy(array);
  4891. } else {
  4892. this.identity();
  4893. }
  4894. }
  4895. copy(array) {
  4896. this[0] = array[0];
  4897. this[1] = array[1];
  4898. this[2] = array[2];
  4899. this[3] = array[3];
  4900. this[4] = array[4];
  4901. this[5] = array[5];
  4902. this[6] = array[6];
  4903. this[7] = array[7];
  4904. this[8] = array[8];
  4905. this[9] = array[9];
  4906. this[10] = array[10];
  4907. this[11] = array[11];
  4908. this[12] = array[12];
  4909. this[13] = array[13];
  4910. this[14] = array[14];
  4911. this[15] = array[15];
  4912. return this.check();
  4913. }
  4914. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4915. this[0] = m00;
  4916. this[1] = m10;
  4917. this[2] = m20;
  4918. this[3] = m30;
  4919. this[4] = m01;
  4920. this[5] = m11;
  4921. this[6] = m21;
  4922. this[7] = m31;
  4923. this[8] = m02;
  4924. this[9] = m12;
  4925. this[10] = m22;
  4926. this[11] = m32;
  4927. this[12] = m03;
  4928. this[13] = m13;
  4929. this[14] = m23;
  4930. this[15] = m33;
  4931. return this.check();
  4932. }
  4933. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4934. this[0] = m00;
  4935. this[1] = m10;
  4936. this[2] = m20;
  4937. this[3] = m30;
  4938. this[4] = m01;
  4939. this[5] = m11;
  4940. this[6] = m21;
  4941. this[7] = m31;
  4942. this[8] = m02;
  4943. this[9] = m12;
  4944. this[10] = m22;
  4945. this[11] = m32;
  4946. this[12] = m03;
  4947. this[13] = m13;
  4948. this[14] = m23;
  4949. this[15] = m33;
  4950. return this.check();
  4951. }
  4952. toRowMajor(result) {
  4953. result[0] = this[0];
  4954. result[1] = this[4];
  4955. result[2] = this[8];
  4956. result[3] = this[12];
  4957. result[4] = this[1];
  4958. result[5] = this[5];
  4959. result[6] = this[9];
  4960. result[7] = this[13];
  4961. result[8] = this[2];
  4962. result[9] = this[6];
  4963. result[10] = this[10];
  4964. result[11] = this[14];
  4965. result[12] = this[3];
  4966. result[13] = this[7];
  4967. result[14] = this[11];
  4968. result[15] = this[15];
  4969. return result;
  4970. }
  4971. identity() {
  4972. return this.copy(IDENTITY);
  4973. }
  4974. fromQuaternion(q) {
  4975. fromQuat(this, q);
  4976. return this.check();
  4977. }
  4978. frustum({
  4979. left,
  4980. right,
  4981. bottom,
  4982. top,
  4983. near,
  4984. far
  4985. }) {
  4986. if (far === Infinity) {
  4987. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  4988. } else {
  4989. frustum(this, left, right, bottom, top, near, far);
  4990. }
  4991. return this.check();
  4992. }
  4993. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  4994. const column0Row0 = 2.0 * near / (right - left);
  4995. const column1Row1 = 2.0 * near / (top - bottom);
  4996. const column2Row0 = (right + left) / (right - left);
  4997. const column2Row1 = (top + bottom) / (top - bottom);
  4998. const column2Row2 = -1.0;
  4999. const column2Row3 = -1.0;
  5000. const column3Row2 = -2.0 * near;
  5001. result[0] = column0Row0;
  5002. result[1] = 0.0;
  5003. result[2] = 0.0;
  5004. result[3] = 0.0;
  5005. result[4] = 0.0;
  5006. result[5] = column1Row1;
  5007. result[6] = 0.0;
  5008. result[7] = 0.0;
  5009. result[8] = column2Row0;
  5010. result[9] = column2Row1;
  5011. result[10] = column2Row2;
  5012. result[11] = column2Row3;
  5013. result[12] = 0.0;
  5014. result[13] = 0.0;
  5015. result[14] = column3Row2;
  5016. result[15] = 0.0;
  5017. return result;
  5018. }
  5019. lookAt(eye, center, up) {
  5020. if (arguments.length === 1) {
  5021. ({
  5022. eye,
  5023. center,
  5024. up
  5025. } = eye);
  5026. }
  5027. center = center || [0, 0, 0];
  5028. up = up || [0, 1, 0];
  5029. lookAt(this, eye, center, up);
  5030. return this.check();
  5031. }
  5032. ortho({
  5033. left,
  5034. right,
  5035. bottom,
  5036. top,
  5037. near = 0.1,
  5038. far = 500
  5039. }) {
  5040. ortho(this, left, right, bottom, top, near, far);
  5041. return this.check();
  5042. }
  5043. orthographic({
  5044. fovy = 45 * Math.PI / 180,
  5045. aspect = 1,
  5046. focalDistance = 1,
  5047. near = 0.1,
  5048. far = 500
  5049. }) {
  5050. if (fovy > Math.PI * 2) {
  5051. throw Error('radians');
  5052. }
  5053. const halfY = fovy / 2;
  5054. const top = focalDistance * Math.tan(halfY);
  5055. const right = top * aspect;
  5056. return new Matrix4().ortho({
  5057. left: -right,
  5058. right,
  5059. bottom: -top,
  5060. top,
  5061. near,
  5062. far
  5063. });
  5064. }
  5065. perspective({
  5066. fovy = undefined,
  5067. fov = 45 * Math.PI / 180,
  5068. aspect = 1,
  5069. near = 0.1,
  5070. far = 500
  5071. } = {}) {
  5072. fovy = fovy || fov;
  5073. if (fovy > Math.PI * 2) {
  5074. throw Error('radians');
  5075. }
  5076. perspective(this, fovy, aspect, near, far);
  5077. return this.check();
  5078. }
  5079. determinant() {
  5080. return determinant(this);
  5081. }
  5082. getScale(result = [-0, -0, -0]) {
  5083. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5084. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5085. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5086. return result;
  5087. }
  5088. getTranslation(result = [-0, -0, -0]) {
  5089. result[0] = this[12];
  5090. result[1] = this[13];
  5091. result[2] = this[14];
  5092. return result;
  5093. }
  5094. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5095. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5096. const inverseScale0 = 1 / scale[0];
  5097. const inverseScale1 = 1 / scale[1];
  5098. const inverseScale2 = 1 / scale[2];
  5099. result[0] = this[0] * inverseScale0;
  5100. result[1] = this[1] * inverseScale1;
  5101. result[2] = this[2] * inverseScale2;
  5102. result[3] = 0;
  5103. result[4] = this[4] * inverseScale0;
  5104. result[5] = this[5] * inverseScale1;
  5105. result[6] = this[6] * inverseScale2;
  5106. result[7] = 0;
  5107. result[8] = this[8] * inverseScale0;
  5108. result[9] = this[9] * inverseScale1;
  5109. result[10] = this[10] * inverseScale2;
  5110. result[11] = 0;
  5111. result[12] = 0;
  5112. result[13] = 0;
  5113. result[14] = 0;
  5114. result[15] = 1;
  5115. return result;
  5116. }
  5117. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5118. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5119. const inverseScale0 = 1 / scale[0];
  5120. const inverseScale1 = 1 / scale[1];
  5121. const inverseScale2 = 1 / scale[2];
  5122. result[0] = this[0] * inverseScale0;
  5123. result[1] = this[1] * inverseScale1;
  5124. result[2] = this[2] * inverseScale2;
  5125. result[3] = this[4] * inverseScale0;
  5126. result[4] = this[5] * inverseScale1;
  5127. result[5] = this[6] * inverseScale2;
  5128. result[6] = this[8] * inverseScale0;
  5129. result[7] = this[9] * inverseScale1;
  5130. result[8] = this[10] * inverseScale2;
  5131. return result;
  5132. }
  5133. transpose() {
  5134. transpose(this, this);
  5135. return this.check();
  5136. }
  5137. invert() {
  5138. invert$1(this, this);
  5139. return this.check();
  5140. }
  5141. multiplyLeft(a) {
  5142. multiply$1(this, a, this);
  5143. return this.check();
  5144. }
  5145. multiplyRight(a) {
  5146. multiply$1(this, this, a);
  5147. return this.check();
  5148. }
  5149. rotateX(radians) {
  5150. rotateX$1(this, this, radians);
  5151. return this.check();
  5152. }
  5153. rotateY(radians) {
  5154. rotateY$1(this, this, radians);
  5155. return this.check();
  5156. }
  5157. rotateZ(radians) {
  5158. rotateZ$1(this, this, radians);
  5159. return this.check();
  5160. }
  5161. rotateXYZ([rx, ry, rz]) {
  5162. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5163. }
  5164. rotateAxis(radians, axis) {
  5165. rotate(this, this, radians, axis);
  5166. return this.check();
  5167. }
  5168. scale(factor) {
  5169. if (Array.isArray(factor)) {
  5170. scale$2(this, this, factor);
  5171. } else {
  5172. scale$2(this, this, [factor, factor, factor]);
  5173. }
  5174. return this.check();
  5175. }
  5176. translate(vec) {
  5177. translate(this, this, vec);
  5178. return this.check();
  5179. }
  5180. transform(vector, result) {
  5181. if (vector.length === 4) {
  5182. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5183. checkVector(result, 4);
  5184. return result;
  5185. }
  5186. return this.transformAsPoint(vector, result);
  5187. }
  5188. transformAsPoint(vector, result) {
  5189. const {
  5190. length
  5191. } = vector;
  5192. switch (length) {
  5193. case 2:
  5194. result = transformMat4$2(result || [-0, -0], vector, this);
  5195. break;
  5196. case 3:
  5197. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5198. break;
  5199. default:
  5200. throw new Error('Illegal vector');
  5201. }
  5202. checkVector(result, vector.length);
  5203. return result;
  5204. }
  5205. transformAsVector(vector, result) {
  5206. switch (vector.length) {
  5207. case 2:
  5208. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5209. break;
  5210. case 3:
  5211. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5212. break;
  5213. default:
  5214. throw new Error('Illegal vector');
  5215. }
  5216. checkVector(result, vector.length);
  5217. return result;
  5218. }
  5219. makeRotationX(radians) {
  5220. return this.identity().rotateX(radians);
  5221. }
  5222. makeTranslation(x, y, z) {
  5223. return this.identity().translate([x, y, z]);
  5224. }
  5225. transformPoint(vector, result) {
  5226. deprecated('Matrix4.transformPoint', '3.0');
  5227. return this.transformAsPoint(vector, result);
  5228. }
  5229. transformVector(vector, result) {
  5230. deprecated('Matrix4.transformVector', '3.0');
  5231. return this.transformAsPoint(vector, result);
  5232. }
  5233. transformDirection(vector, result) {
  5234. deprecated('Matrix4.transformDirection', '3.0');
  5235. return this.transformAsVector(vector, result);
  5236. }
  5237. }
  5238. /**
  5239. * Quaternion
  5240. * @module quat
  5241. */
  5242. /**
  5243. * Creates a new identity quat
  5244. *
  5245. * @returns {quat} a new quaternion
  5246. */
  5247. function create() {
  5248. var out = new ARRAY_TYPE(4);
  5249. if (ARRAY_TYPE != Float32Array) {
  5250. out[0] = 0;
  5251. out[1] = 0;
  5252. out[2] = 0;
  5253. }
  5254. out[3] = 1;
  5255. return out;
  5256. }
  5257. /**
  5258. * Set a quat to the identity quaternion
  5259. *
  5260. * @param {quat} out the receiving quaternion
  5261. * @returns {quat} out
  5262. */
  5263. function identity(out) {
  5264. out[0] = 0;
  5265. out[1] = 0;
  5266. out[2] = 0;
  5267. out[3] = 1;
  5268. return out;
  5269. }
  5270. /**
  5271. * Sets a quat from the given angle and rotation axis,
  5272. * then returns it.
  5273. *
  5274. * @param {quat} out the receiving quaternion
  5275. * @param {ReadonlyVec3} axis the axis around which to rotate
  5276. * @param {Number} rad the angle in radians
  5277. * @returns {quat} out
  5278. **/
  5279. function setAxisAngle(out, axis, rad) {
  5280. rad = rad * 0.5;
  5281. var s = Math.sin(rad);
  5282. out[0] = s * axis[0];
  5283. out[1] = s * axis[1];
  5284. out[2] = s * axis[2];
  5285. out[3] = Math.cos(rad);
  5286. return out;
  5287. }
  5288. /**
  5289. * Multiplies two quat's
  5290. *
  5291. * @param {quat} out the receiving quaternion
  5292. * @param {ReadonlyQuat} a the first operand
  5293. * @param {ReadonlyQuat} b the second operand
  5294. * @returns {quat} out
  5295. */
  5296. function multiply(out, a, b) {
  5297. var ax = a[0],
  5298. ay = a[1],
  5299. az = a[2],
  5300. aw = a[3];
  5301. var bx = b[0],
  5302. by = b[1],
  5303. bz = b[2],
  5304. bw = b[3];
  5305. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5306. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5307. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5308. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5309. return out;
  5310. }
  5311. /**
  5312. * Rotates a quaternion by the given angle about the X axis
  5313. *
  5314. * @param {quat} out quat receiving operation result
  5315. * @param {ReadonlyQuat} a quat to rotate
  5316. * @param {number} rad angle (in radians) to rotate
  5317. * @returns {quat} out
  5318. */
  5319. function rotateX(out, a, rad) {
  5320. rad *= 0.5;
  5321. var ax = a[0],
  5322. ay = a[1],
  5323. az = a[2],
  5324. aw = a[3];
  5325. var bx = Math.sin(rad),
  5326. bw = Math.cos(rad);
  5327. out[0] = ax * bw + aw * bx;
  5328. out[1] = ay * bw + az * bx;
  5329. out[2] = az * bw - ay * bx;
  5330. out[3] = aw * bw - ax * bx;
  5331. return out;
  5332. }
  5333. /**
  5334. * Rotates a quaternion by the given angle about the Y axis
  5335. *
  5336. * @param {quat} out quat receiving operation result
  5337. * @param {ReadonlyQuat} a quat to rotate
  5338. * @param {number} rad angle (in radians) to rotate
  5339. * @returns {quat} out
  5340. */
  5341. function rotateY(out, a, rad) {
  5342. rad *= 0.5;
  5343. var ax = a[0],
  5344. ay = a[1],
  5345. az = a[2],
  5346. aw = a[3];
  5347. var by = Math.sin(rad),
  5348. bw = Math.cos(rad);
  5349. out[0] = ax * bw - az * by;
  5350. out[1] = ay * bw + aw * by;
  5351. out[2] = az * bw + ax * by;
  5352. out[3] = aw * bw - ay * by;
  5353. return out;
  5354. }
  5355. /**
  5356. * Rotates a quaternion by the given angle about the Z axis
  5357. *
  5358. * @param {quat} out quat receiving operation result
  5359. * @param {ReadonlyQuat} a quat to rotate
  5360. * @param {number} rad angle (in radians) to rotate
  5361. * @returns {quat} out
  5362. */
  5363. function rotateZ(out, a, rad) {
  5364. rad *= 0.5;
  5365. var ax = a[0],
  5366. ay = a[1],
  5367. az = a[2],
  5368. aw = a[3];
  5369. var bz = Math.sin(rad),
  5370. bw = Math.cos(rad);
  5371. out[0] = ax * bw + ay * bz;
  5372. out[1] = ay * bw - ax * bz;
  5373. out[2] = az * bw + aw * bz;
  5374. out[3] = aw * bw - az * bz;
  5375. return out;
  5376. }
  5377. /**
  5378. * Calculates the W component of a quat from the X, Y, and Z components.
  5379. * Assumes that quaternion is 1 unit in length.
  5380. * Any existing W component will be ignored.
  5381. *
  5382. * @param {quat} out the receiving quaternion
  5383. * @param {ReadonlyQuat} a quat to calculate W component of
  5384. * @returns {quat} out
  5385. */
  5386. function calculateW(out, a) {
  5387. var x = a[0],
  5388. y = a[1],
  5389. z = a[2];
  5390. out[0] = x;
  5391. out[1] = y;
  5392. out[2] = z;
  5393. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5394. return out;
  5395. }
  5396. /**
  5397. * Performs a spherical linear interpolation between two quat
  5398. *
  5399. * @param {quat} out the receiving quaternion
  5400. * @param {ReadonlyQuat} a the first operand
  5401. * @param {ReadonlyQuat} b the second operand
  5402. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5403. * @returns {quat} out
  5404. */
  5405. function slerp(out, a, b, t) {
  5406. // benchmarks:
  5407. // http://jsperf.com/quaternion-slerp-implementations
  5408. var ax = a[0],
  5409. ay = a[1],
  5410. az = a[2],
  5411. aw = a[3];
  5412. var bx = b[0],
  5413. by = b[1],
  5414. bz = b[2],
  5415. bw = b[3];
  5416. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5417. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5418. if (cosom < 0.0) {
  5419. cosom = -cosom;
  5420. bx = -bx;
  5421. by = -by;
  5422. bz = -bz;
  5423. bw = -bw;
  5424. } // calculate coefficients
  5425. if (1.0 - cosom > EPSILON) {
  5426. // standard case (slerp)
  5427. omega = Math.acos(cosom);
  5428. sinom = Math.sin(omega);
  5429. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5430. scale1 = Math.sin(t * omega) / sinom;
  5431. } else {
  5432. // "from" and "to" quaternions are very close
  5433. // ... so we can do a linear interpolation
  5434. scale0 = 1.0 - t;
  5435. scale1 = t;
  5436. } // calculate final values
  5437. out[0] = scale0 * ax + scale1 * bx;
  5438. out[1] = scale0 * ay + scale1 * by;
  5439. out[2] = scale0 * az + scale1 * bz;
  5440. out[3] = scale0 * aw + scale1 * bw;
  5441. return out;
  5442. }
  5443. /**
  5444. * Calculates the inverse of a quat
  5445. *
  5446. * @param {quat} out the receiving quaternion
  5447. * @param {ReadonlyQuat} a quat to calculate inverse of
  5448. * @returns {quat} out
  5449. */
  5450. function invert(out, a) {
  5451. var a0 = a[0],
  5452. a1 = a[1],
  5453. a2 = a[2],
  5454. a3 = a[3];
  5455. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5456. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5457. out[0] = -a0 * invDot;
  5458. out[1] = -a1 * invDot;
  5459. out[2] = -a2 * invDot;
  5460. out[3] = a3 * invDot;
  5461. return out;
  5462. }
  5463. /**
  5464. * Calculates the conjugate of a quat
  5465. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5466. *
  5467. * @param {quat} out the receiving quaternion
  5468. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5469. * @returns {quat} out
  5470. */
  5471. function conjugate(out, a) {
  5472. out[0] = -a[0];
  5473. out[1] = -a[1];
  5474. out[2] = -a[2];
  5475. out[3] = a[3];
  5476. return out;
  5477. }
  5478. /**
  5479. * Creates a quaternion from the given 3x3 rotation matrix.
  5480. *
  5481. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5482. * to renormalize the quaternion yourself where necessary.
  5483. *
  5484. * @param {quat} out the receiving quaternion
  5485. * @param {ReadonlyMat3} m rotation matrix
  5486. * @returns {quat} out
  5487. * @function
  5488. */
  5489. function fromMat3(out, m) {
  5490. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5491. // article "Quaternion Calculus and Fast Animation".
  5492. var fTrace = m[0] + m[4] + m[8];
  5493. var fRoot;
  5494. if (fTrace > 0.0) {
  5495. // |w| > 1/2, may as well choose w > 1/2
  5496. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5497. out[3] = 0.5 * fRoot;
  5498. fRoot = 0.5 / fRoot; // 1/(4w)
  5499. out[0] = (m[5] - m[7]) * fRoot;
  5500. out[1] = (m[6] - m[2]) * fRoot;
  5501. out[2] = (m[1] - m[3]) * fRoot;
  5502. } else {
  5503. // |w| <= 1/2
  5504. var i = 0;
  5505. if (m[4] > m[0]) i = 1;
  5506. if (m[8] > m[i * 3 + i]) i = 2;
  5507. var j = (i + 1) % 3;
  5508. var k = (i + 2) % 3;
  5509. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5510. out[i] = 0.5 * fRoot;
  5511. fRoot = 0.5 / fRoot;
  5512. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5513. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5514. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5515. }
  5516. return out;
  5517. }
  5518. /**
  5519. * Adds two quat's
  5520. *
  5521. * @param {quat} out the receiving quaternion
  5522. * @param {ReadonlyQuat} a the first operand
  5523. * @param {ReadonlyQuat} b the second operand
  5524. * @returns {quat} out
  5525. * @function
  5526. */
  5527. var add = add$1;
  5528. /**
  5529. * Scales a quat by a scalar number
  5530. *
  5531. * @param {quat} out the receiving vector
  5532. * @param {ReadonlyQuat} a the vector to scale
  5533. * @param {Number} b amount to scale the vector by
  5534. * @returns {quat} out
  5535. * @function
  5536. */
  5537. var scale = scale$1;
  5538. /**
  5539. * Calculates the dot product of two quat's
  5540. *
  5541. * @param {ReadonlyQuat} a the first operand
  5542. * @param {ReadonlyQuat} b the second operand
  5543. * @returns {Number} dot product of a and b
  5544. * @function
  5545. */
  5546. var dot = dot$1;
  5547. /**
  5548. * Performs a linear interpolation between two quat's
  5549. *
  5550. * @param {quat} out the receiving quaternion
  5551. * @param {ReadonlyQuat} a the first operand
  5552. * @param {ReadonlyQuat} b the second operand
  5553. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5554. * @returns {quat} out
  5555. * @function
  5556. */
  5557. var lerp = lerp$1;
  5558. /**
  5559. * Calculates the length of a quat
  5560. *
  5561. * @param {ReadonlyQuat} a vector to calculate length of
  5562. * @returns {Number} length of a
  5563. */
  5564. var length = length$1;
  5565. /**
  5566. * Calculates the squared length of a quat
  5567. *
  5568. * @param {ReadonlyQuat} a vector to calculate squared length of
  5569. * @returns {Number} squared length of a
  5570. * @function
  5571. */
  5572. var squaredLength = squaredLength$1;
  5573. /**
  5574. * Normalize a quat
  5575. *
  5576. * @param {quat} out the receiving quaternion
  5577. * @param {ReadonlyQuat} a quaternion to normalize
  5578. * @returns {quat} out
  5579. * @function
  5580. */
  5581. var normalize = normalize$1;
  5582. /**
  5583. * Sets a quaternion to represent the shortest rotation from one
  5584. * vector to another.
  5585. *
  5586. * Both vectors are assumed to be unit length.
  5587. *
  5588. * @param {quat} out the receiving quaternion.
  5589. * @param {ReadonlyVec3} a the initial vector
  5590. * @param {ReadonlyVec3} b the destination vector
  5591. * @returns {quat} out
  5592. */
  5593. var rotationTo = function () {
  5594. var tmpvec3 = create$3();
  5595. var xUnitVec3 = fromValues(1, 0, 0);
  5596. var yUnitVec3 = fromValues(0, 1, 0);
  5597. return function (out, a, b) {
  5598. var dot = dot$2(a, b);
  5599. if (dot < -0.999999) {
  5600. cross(tmpvec3, xUnitVec3, a);
  5601. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5602. normalize$2(tmpvec3, tmpvec3);
  5603. setAxisAngle(out, tmpvec3, Math.PI);
  5604. return out;
  5605. } else if (dot > 0.999999) {
  5606. out[0] = 0;
  5607. out[1] = 0;
  5608. out[2] = 0;
  5609. out[3] = 1;
  5610. return out;
  5611. } else {
  5612. cross(tmpvec3, a, b);
  5613. out[0] = tmpvec3[0];
  5614. out[1] = tmpvec3[1];
  5615. out[2] = tmpvec3[2];
  5616. out[3] = 1 + dot;
  5617. return normalize(out, out);
  5618. }
  5619. };
  5620. }();
  5621. /**
  5622. * Performs a spherical linear interpolation with two control points
  5623. *
  5624. * @param {quat} out the receiving quaternion
  5625. * @param {ReadonlyQuat} a the first operand
  5626. * @param {ReadonlyQuat} b the second operand
  5627. * @param {ReadonlyQuat} c the third operand
  5628. * @param {ReadonlyQuat} d the fourth operand
  5629. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5630. * @returns {quat} out
  5631. */
  5632. (function () {
  5633. var temp1 = create();
  5634. var temp2 = create();
  5635. return function (out, a, b, c, d, t) {
  5636. slerp(temp1, a, d, t);
  5637. slerp(temp2, b, c, t);
  5638. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5639. return out;
  5640. };
  5641. })();
  5642. /**
  5643. * Sets the specified quaternion with values corresponding to the given
  5644. * axes. Each axis is a vec3 and is expected to be unit length and
  5645. * perpendicular to all other specified axes.
  5646. *
  5647. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5648. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5649. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5650. * @returns {quat} out
  5651. */
  5652. (function () {
  5653. var matr = create$2();
  5654. return function (out, view, right, up) {
  5655. matr[0] = right[0];
  5656. matr[3] = right[1];
  5657. matr[6] = right[2];
  5658. matr[1] = up[0];
  5659. matr[4] = up[1];
  5660. matr[7] = up[2];
  5661. matr[2] = -view[0];
  5662. matr[5] = -view[1];
  5663. matr[8] = -view[2];
  5664. return normalize(out, fromMat3(out, matr));
  5665. };
  5666. })();
  5667. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5668. class Quaternion extends MathArray {
  5669. constructor(x = 0, y = 0, z = 0, w = 1) {
  5670. super(-0, -0, -0, -0);
  5671. if (Array.isArray(x) && arguments.length === 1) {
  5672. this.copy(x);
  5673. } else {
  5674. this.set(x, y, z, w);
  5675. }
  5676. }
  5677. copy(array) {
  5678. this[0] = array[0];
  5679. this[1] = array[1];
  5680. this[2] = array[2];
  5681. this[3] = array[3];
  5682. return this.check();
  5683. }
  5684. set(x, y, z, w) {
  5685. this[0] = x;
  5686. this[1] = y;
  5687. this[2] = z;
  5688. this[3] = w;
  5689. return this.check();
  5690. }
  5691. fromMatrix3(m) {
  5692. fromMat3(this, m);
  5693. return this.check();
  5694. }
  5695. identity() {
  5696. identity(this);
  5697. return this.check();
  5698. }
  5699. fromAxisRotation(axis, rad) {
  5700. setAxisAngle(this, axis, rad);
  5701. return this.check();
  5702. }
  5703. setAxisAngle(axis, rad) {
  5704. return this.fromAxisRotation(axis, rad);
  5705. }
  5706. get ELEMENTS() {
  5707. return 4;
  5708. }
  5709. get x() {
  5710. return this[0];
  5711. }
  5712. set x(value) {
  5713. this[0] = checkNumber(value);
  5714. }
  5715. get y() {
  5716. return this[1];
  5717. }
  5718. set y(value) {
  5719. this[1] = checkNumber(value);
  5720. }
  5721. get z() {
  5722. return this[2];
  5723. }
  5724. set z(value) {
  5725. this[2] = checkNumber(value);
  5726. }
  5727. get w() {
  5728. return this[3];
  5729. }
  5730. set w(value) {
  5731. this[3] = checkNumber(value);
  5732. }
  5733. len() {
  5734. return length(this);
  5735. }
  5736. lengthSquared() {
  5737. return squaredLength(this);
  5738. }
  5739. dot(a, b) {
  5740. if (b !== undefined) {
  5741. throw new Error('Quaternion.dot only takes one argument');
  5742. }
  5743. return dot(this, a);
  5744. }
  5745. rotationTo(vectorA, vectorB) {
  5746. rotationTo(this, vectorA, vectorB);
  5747. return this.check();
  5748. }
  5749. add(a, b) {
  5750. if (b !== undefined) {
  5751. throw new Error('Quaternion.add only takes one argument');
  5752. }
  5753. add(this, this, a);
  5754. return this.check();
  5755. }
  5756. calculateW() {
  5757. calculateW(this, this);
  5758. return this.check();
  5759. }
  5760. conjugate() {
  5761. conjugate(this, this);
  5762. return this.check();
  5763. }
  5764. invert() {
  5765. invert(this, this);
  5766. return this.check();
  5767. }
  5768. lerp(a, b, t) {
  5769. lerp(this, a, b, t);
  5770. return this.check();
  5771. }
  5772. multiplyRight(a, b) {
  5773. assert$4(!b);
  5774. multiply(this, this, a);
  5775. return this.check();
  5776. }
  5777. multiplyLeft(a, b) {
  5778. assert$4(!b);
  5779. multiply(this, a, this);
  5780. return this.check();
  5781. }
  5782. normalize() {
  5783. const length = this.len();
  5784. const l = length > 0 ? 1 / length : 0;
  5785. this[0] = this[0] * l;
  5786. this[1] = this[1] * l;
  5787. this[2] = this[2] * l;
  5788. this[3] = this[3] * l;
  5789. if (length === 0) {
  5790. this[3] = 1;
  5791. }
  5792. return this.check();
  5793. }
  5794. rotateX(rad) {
  5795. rotateX(this, this, rad);
  5796. return this.check();
  5797. }
  5798. rotateY(rad) {
  5799. rotateY(this, this, rad);
  5800. return this.check();
  5801. }
  5802. rotateZ(rad) {
  5803. rotateZ(this, this, rad);
  5804. return this.check();
  5805. }
  5806. scale(b) {
  5807. scale(this, this, b);
  5808. return this.check();
  5809. }
  5810. slerp(start, target, ratio) {
  5811. switch (arguments.length) {
  5812. case 1:
  5813. ({
  5814. start = IDENTITY_QUATERNION,
  5815. target,
  5816. ratio
  5817. } = arguments[0]);
  5818. break;
  5819. case 2:
  5820. [target, ratio] = arguments;
  5821. start = this;
  5822. break;
  5823. }
  5824. slerp(this, start, target, ratio);
  5825. return this.check();
  5826. }
  5827. transformVector4(vector, result = vector) {
  5828. transformQuat(result, vector, this);
  5829. return checkVector(result, 4);
  5830. }
  5831. lengthSq() {
  5832. return this.lengthSquared();
  5833. }
  5834. setFromAxisAngle(axis, rad) {
  5835. return this.setAxisAngle(axis, rad);
  5836. }
  5837. premultiply(a, b) {
  5838. return this.multiplyLeft(a, b);
  5839. }
  5840. multiply(a, b) {
  5841. return this.multiplyRight(a, b);
  5842. }
  5843. }
  5844. var _MathUtils = {
  5845. EPSILON1: 1e-1,
  5846. EPSILON2: 1e-2,
  5847. EPSILON3: 1e-3,
  5848. EPSILON4: 1e-4,
  5849. EPSILON5: 1e-5,
  5850. EPSILON6: 1e-6,
  5851. EPSILON7: 1e-7,
  5852. EPSILON8: 1e-8,
  5853. EPSILON9: 1e-9,
  5854. EPSILON10: 1e-10,
  5855. EPSILON11: 1e-11,
  5856. EPSILON12: 1e-12,
  5857. EPSILON13: 1e-13,
  5858. EPSILON14: 1e-14,
  5859. EPSILON15: 1e-15,
  5860. EPSILON16: 1e-16,
  5861. EPSILON17: 1e-17,
  5862. EPSILON18: 1e-18,
  5863. EPSILON19: 1e-19,
  5864. EPSILON20: 1e-20,
  5865. PI_OVER_TWO: Math.PI / 2,
  5866. PI_OVER_FOUR: Math.PI / 4,
  5867. PI_OVER_SIX: Math.PI / 6,
  5868. TWO_PI: Math.PI * 2
  5869. };
  5870. const WGS84_RADIUS_X$1 = 6378137.0;
  5871. const WGS84_RADIUS_Y$1 = 6378137.0;
  5872. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5873. const noop = x => x;
  5874. const scratchVector$6 = new Vector3();
  5875. function fromCartographic(cartographic, result, map = noop) {
  5876. if (isArray(cartographic)) {
  5877. result[0] = map(cartographic[0]);
  5878. result[1] = map(cartographic[1]);
  5879. result[2] = cartographic[2];
  5880. } else if ('longitude' in cartographic) {
  5881. result[0] = map(cartographic.longitude);
  5882. result[1] = map(cartographic.latitude);
  5883. result[2] = cartographic.height;
  5884. } else {
  5885. result[0] = map(cartographic.x);
  5886. result[1] = map(cartographic.y);
  5887. result[2] = cartographic.z;
  5888. }
  5889. return result;
  5890. }
  5891. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5892. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5893. }
  5894. function toCartographic(vector, cartographic, map = noop) {
  5895. if (isArray(cartographic)) {
  5896. cartographic[0] = map(vector[0]);
  5897. cartographic[1] = map(vector[1]);
  5898. cartographic[2] = vector[2];
  5899. } else if ('longitude' in cartographic) {
  5900. cartographic.longitude = map(vector[0]);
  5901. cartographic.latitude = map(vector[1]);
  5902. cartographic.height = vector[2];
  5903. } else {
  5904. cartographic.x = map(vector[0]);
  5905. cartographic.y = map(vector[1]);
  5906. cartographic.z = vector[2];
  5907. }
  5908. return cartographic;
  5909. }
  5910. function toCartographicFromRadians(vector, cartographic) {
  5911. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5912. }
  5913. const scratchVector$5 = new Vector3();
  5914. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5915. const scaleToGeodeticSurfaceGradient = new Vector3();
  5916. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5917. const {
  5918. oneOverRadii,
  5919. oneOverRadiiSquared,
  5920. centerToleranceSquared
  5921. } = ellipsoid;
  5922. scratchVector$5.from(cartesian);
  5923. const positionX = cartesian.x;
  5924. const positionY = cartesian.y;
  5925. const positionZ = cartesian.z;
  5926. const oneOverRadiiX = oneOverRadii.x;
  5927. const oneOverRadiiY = oneOverRadii.y;
  5928. const oneOverRadiiZ = oneOverRadii.z;
  5929. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5930. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5931. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5932. const squaredNorm = x2 + y2 + z2;
  5933. const ratio = Math.sqrt(1.0 / squaredNorm);
  5934. if (!Number.isFinite(ratio)) {
  5935. return undefined;
  5936. }
  5937. const intersection = scaleToGeodeticSurfaceIntersection;
  5938. intersection.copy(cartesian).scale(ratio);
  5939. if (squaredNorm < centerToleranceSquared) {
  5940. return intersection.to(result);
  5941. }
  5942. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5943. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5944. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5945. const gradient = scaleToGeodeticSurfaceGradient;
  5946. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5947. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5948. let correction = 0.0;
  5949. let xMultiplier;
  5950. let yMultiplier;
  5951. let zMultiplier;
  5952. let func;
  5953. do {
  5954. lambda -= correction;
  5955. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5956. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5957. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5958. const xMultiplier2 = xMultiplier * xMultiplier;
  5959. const yMultiplier2 = yMultiplier * yMultiplier;
  5960. const zMultiplier2 = zMultiplier * zMultiplier;
  5961. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5962. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5963. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5964. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5965. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5966. const derivative = -2.0 * denominator;
  5967. correction = func / derivative;
  5968. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5969. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5970. }
  5971. const EPSILON14 = 1e-14;
  5972. const scratchOrigin = new Vector3();
  5973. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5974. up: {
  5975. south: 'east',
  5976. north: 'west',
  5977. west: 'south',
  5978. east: 'north'
  5979. },
  5980. down: {
  5981. south: 'west',
  5982. north: 'east',
  5983. west: 'north',
  5984. east: 'south'
  5985. },
  5986. south: {
  5987. up: 'west',
  5988. down: 'east',
  5989. west: 'down',
  5990. east: 'up'
  5991. },
  5992. north: {
  5993. up: 'east',
  5994. down: 'west',
  5995. west: 'up',
  5996. east: 'down'
  5997. },
  5998. west: {
  5999. up: 'north',
  6000. down: 'south',
  6001. north: 'down',
  6002. south: 'up'
  6003. },
  6004. east: {
  6005. up: 'south',
  6006. down: 'north',
  6007. north: 'up',
  6008. south: 'down'
  6009. }
  6010. };
  6011. const degeneratePositionLocalFrame = {
  6012. north: [-1, 0, 0],
  6013. east: [0, 1, 0],
  6014. up: [0, 0, 1],
  6015. south: [1, 0, 0],
  6016. west: [0, -1, 0],
  6017. down: [0, 0, -1]
  6018. };
  6019. const scratchAxisVectors = {
  6020. east: new Vector3(),
  6021. north: new Vector3(),
  6022. up: new Vector3(),
  6023. west: new Vector3(),
  6024. south: new Vector3(),
  6025. down: new Vector3()
  6026. };
  6027. const scratchVector1 = new Vector3();
  6028. const scratchVector2$1 = new Vector3();
  6029. const scratchVector3$1 = new Vector3();
  6030. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6031. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6032. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6033. let firstAxisVector;
  6034. let secondAxisVector;
  6035. let thirdAxisVector;
  6036. const origin = scratchOrigin.copy(cartesianOrigin);
  6037. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6038. if (atPole) {
  6039. const sign = Math.sign(origin.z);
  6040. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6041. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6042. firstAxisVector.scale(sign);
  6043. }
  6044. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6045. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6046. secondAxisVector.scale(sign);
  6047. }
  6048. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6049. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6050. thirdAxisVector.scale(sign);
  6051. }
  6052. } else {
  6053. const {
  6054. up,
  6055. east,
  6056. north
  6057. } = scratchAxisVectors;
  6058. east.set(-origin.y, origin.x, 0.0).normalize();
  6059. ellipsoid.geodeticSurfaceNormal(origin, up);
  6060. north.copy(up).cross(east);
  6061. const {
  6062. down,
  6063. west,
  6064. south
  6065. } = scratchAxisVectors;
  6066. down.copy(up).scale(-1);
  6067. west.copy(east).scale(-1);
  6068. south.copy(north).scale(-1);
  6069. firstAxisVector = scratchAxisVectors[firstAxis];
  6070. secondAxisVector = scratchAxisVectors[secondAxis];
  6071. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6072. }
  6073. result[0] = firstAxisVector.x;
  6074. result[1] = firstAxisVector.y;
  6075. result[2] = firstAxisVector.z;
  6076. result[3] = 0.0;
  6077. result[4] = secondAxisVector.x;
  6078. result[5] = secondAxisVector.y;
  6079. result[6] = secondAxisVector.z;
  6080. result[7] = 0.0;
  6081. result[8] = thirdAxisVector.x;
  6082. result[9] = thirdAxisVector.y;
  6083. result[10] = thirdAxisVector.z;
  6084. result[11] = 0.0;
  6085. result[12] = origin.x;
  6086. result[13] = origin.y;
  6087. result[14] = origin.z;
  6088. result[15] = 1.0;
  6089. return result;
  6090. }
  6091. const scratchVector$4 = new Vector3();
  6092. const scratchNormal$2 = new Vector3();
  6093. const scratchK = new Vector3();
  6094. const scratchPosition$2 = new Vector3();
  6095. const scratchHeight = new Vector3();
  6096. const scratchCartesian = new Vector3();
  6097. let wgs84;
  6098. class Ellipsoid {
  6099. static get WGS84() {
  6100. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6101. return wgs84;
  6102. }
  6103. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6104. assert$4(x >= 0.0);
  6105. assert$4(y >= 0.0);
  6106. assert$4(z >= 0.0);
  6107. this.radii = new Vector3(x, y, z);
  6108. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6109. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6110. 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);
  6111. 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));
  6112. this.minimumRadius = Math.min(x, y, z);
  6113. this.maximumRadius = Math.max(x, y, z);
  6114. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6115. if (this.radiiSquared.z !== 0) {
  6116. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6117. }
  6118. Object.freeze(this);
  6119. }
  6120. equals(right) {
  6121. return this === right || Boolean(right && this.radii.equals(right.radii));
  6122. }
  6123. toString() {
  6124. return this.radii.toString();
  6125. }
  6126. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6127. const normal = scratchNormal$2;
  6128. const k = scratchK;
  6129. const [,, height] = cartographic;
  6130. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6131. k.copy(this.radiiSquared).scale(normal);
  6132. const gamma = Math.sqrt(normal.dot(k));
  6133. k.scale(1 / gamma);
  6134. normal.scale(height);
  6135. k.add(normal);
  6136. return k.to(result);
  6137. }
  6138. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6139. scratchCartesian.from(cartesian);
  6140. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6141. if (!point) {
  6142. return undefined;
  6143. }
  6144. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6145. const h = scratchHeight;
  6146. h.copy(scratchCartesian).subtract(point);
  6147. const longitude = Math.atan2(normal.y, normal.x);
  6148. const latitude = Math.asin(normal.z);
  6149. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6150. return toCartographicFromRadians([longitude, latitude, height], result);
  6151. }
  6152. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6153. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6154. }
  6155. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6156. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6157. }
  6158. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6159. return scratchVector$4.from(cartesian).normalize().to(result);
  6160. }
  6161. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6162. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6163. const longitude = cartographicVectorRadians[0];
  6164. const latitude = cartographicVectorRadians[1];
  6165. const cosLatitude = Math.cos(latitude);
  6166. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6167. return scratchVector$4.to(result);
  6168. }
  6169. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6170. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6171. }
  6172. scaleToGeodeticSurface(cartesian, result) {
  6173. return scaleToGeodeticSurface(cartesian, this, result);
  6174. }
  6175. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6176. scratchPosition$2.from(cartesian);
  6177. const positionX = scratchPosition$2.x;
  6178. const positionY = scratchPosition$2.y;
  6179. const positionZ = scratchPosition$2.z;
  6180. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6181. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6182. return scratchPosition$2.multiplyScalar(beta).to(result);
  6183. }
  6184. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6185. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6186. }
  6187. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6188. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6189. }
  6190. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6191. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6192. assert$4(this.radii.z > 0);
  6193. scratchPosition$2.from(position);
  6194. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6195. if (Math.abs(z) >= this.radii.z - buffer) {
  6196. return undefined;
  6197. }
  6198. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6199. }
  6200. }
  6201. class DoublyLinkedListNode {
  6202. constructor(item, previous, next) {
  6203. _defineProperty(this, "item", void 0);
  6204. _defineProperty(this, "previous", void 0);
  6205. _defineProperty(this, "next", void 0);
  6206. this.item = item;
  6207. this.previous = previous;
  6208. this.next = next;
  6209. }
  6210. }
  6211. class DoublyLinkedList {
  6212. constructor() {
  6213. _defineProperty(this, "head", null);
  6214. _defineProperty(this, "tail", null);
  6215. _defineProperty(this, "_length", 0);
  6216. }
  6217. get length() {
  6218. return this._length;
  6219. }
  6220. add(item) {
  6221. const node = new DoublyLinkedListNode(item, this.tail, null);
  6222. if (this.tail) {
  6223. this.tail.next = node;
  6224. this.tail = node;
  6225. } else {
  6226. this.head = node;
  6227. this.tail = node;
  6228. }
  6229. ++this._length;
  6230. return node;
  6231. }
  6232. remove(node) {
  6233. if (!node) {
  6234. return;
  6235. }
  6236. if (node.previous && node.next) {
  6237. node.previous.next = node.next;
  6238. node.next.previous = node.previous;
  6239. } else if (node.previous) {
  6240. node.previous.next = null;
  6241. this.tail = node.previous;
  6242. } else if (node.next) {
  6243. node.next.previous = null;
  6244. this.head = node.next;
  6245. } else {
  6246. this.head = null;
  6247. this.tail = null;
  6248. }
  6249. node.next = null;
  6250. node.previous = null;
  6251. --this._length;
  6252. }
  6253. splice(node, nextNode) {
  6254. if (node === nextNode) {
  6255. return;
  6256. }
  6257. this.remove(nextNode);
  6258. this._insert(node, nextNode);
  6259. }
  6260. _insert(node, nextNode) {
  6261. const oldNodeNext = node.next;
  6262. node.next = nextNode;
  6263. if (this.tail === node) {
  6264. this.tail = nextNode;
  6265. } else {
  6266. oldNodeNext.previous = nextNode;
  6267. }
  6268. nextNode.next = oldNodeNext;
  6269. nextNode.previous = node;
  6270. ++this._length;
  6271. }
  6272. }
  6273. function defined$5(x) {
  6274. return x !== undefined && x !== null;
  6275. }
  6276. class TilesetCache {
  6277. constructor() {
  6278. _defineProperty(this, "_list", void 0);
  6279. _defineProperty(this, "_sentinel", void 0);
  6280. _defineProperty(this, "_trimTiles", void 0);
  6281. this._list = new DoublyLinkedList();
  6282. this._sentinel = this._list.add('sentinel');
  6283. this._trimTiles = false;
  6284. }
  6285. reset() {
  6286. this._list.splice(this._list.tail, this._sentinel);
  6287. }
  6288. touch(tile) {
  6289. const node = tile._cacheNode;
  6290. if (defined$5(node)) {
  6291. this._list.splice(this._sentinel, node);
  6292. }
  6293. }
  6294. add(tileset, tile, addCallback) {
  6295. if (!defined$5(tile._cacheNode)) {
  6296. tile._cacheNode = this._list.add(tile);
  6297. if (addCallback) {
  6298. addCallback(tileset, tile);
  6299. }
  6300. }
  6301. }
  6302. unloadTile(tileset, tile, unloadCallback) {
  6303. const node = tile._cacheNode;
  6304. if (!defined$5(node)) {
  6305. return;
  6306. }
  6307. this._list.remove(node);
  6308. tile._cacheNode = undefined;
  6309. if (unloadCallback) {
  6310. unloadCallback(tileset, tile);
  6311. }
  6312. }
  6313. unloadTiles(tileset, unloadCallback) {
  6314. const trimTiles = this._trimTiles;
  6315. this._trimTiles = false;
  6316. const list = this._list;
  6317. const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
  6318. const sentinel = this._sentinel;
  6319. let node = list.head;
  6320. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6321. const tile = node.item;
  6322. node = node.next;
  6323. this.unloadTile(tileset, tile, unloadCallback);
  6324. } */
  6325. //改
  6326. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  6327. const tile = node.item;
  6328. node = node.next;
  6329. this.unloadTile(tileset, tile, unloadCallback);
  6330. }
  6331. }
  6332. trim() {
  6333. this._trimTiles = true;
  6334. }
  6335. }
  6336. function calculateTransformProps(tileHeader, tile) {
  6337. assert$7(tileHeader);
  6338. assert$7(tile);
  6339. const {
  6340. rtcCenter,
  6341. gltfUpAxis
  6342. } = tile;
  6343. const {
  6344. computedTransform,
  6345. boundingVolume: {
  6346. center
  6347. }
  6348. } = tileHeader;
  6349. let modelMatrix = new Matrix4(computedTransform);
  6350. if (rtcCenter) {
  6351. modelMatrix.translate(rtcCenter);
  6352. }
  6353. switch (gltfUpAxis) {
  6354. case 'Z':
  6355. break;
  6356. case 'Y':
  6357. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6358. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6359. break;
  6360. case 'X':
  6361. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6362. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6363. break;
  6364. }
  6365. if (tile.isQuantized) {
  6366. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6367. }
  6368. const cartesianOrigin = new Vector3(center);
  6369. tile.cartesianModelMatrix = modelMatrix;
  6370. tile.cartesianOrigin = cartesianOrigin;
  6371. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6372. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6373. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6374. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6375. tile.cartographicOrigin = cartographicOrigin;
  6376. if (!tile.coordinateSystem) {
  6377. tile.modelMatrix = tile.cartographicModelMatrix;
  6378. }
  6379. }
  6380. const INTERSECTION = Object.freeze({
  6381. OUTSIDE: -1,
  6382. INTERSECTING: 0,
  6383. INSIDE: 1
  6384. });
  6385. new Vector3();
  6386. new Vector3();
  6387. const scratchVector$3 = new Vector3();
  6388. const scratchVector2 = new Vector3();
  6389. class BoundingSphere {
  6390. constructor(center = [0, 0, 0], radius = 0.0) {
  6391. this.radius = -0;
  6392. this.center = new Vector3();
  6393. this.fromCenterRadius(center, radius);
  6394. }
  6395. fromCenterRadius(center, radius) {
  6396. this.center.from(center);
  6397. this.radius = radius;
  6398. return this;
  6399. }
  6400. fromCornerPoints(corner, oppositeCorner) {
  6401. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6402. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6403. this.radius = this.center.distance(oppositeCorner);
  6404. return this;
  6405. }
  6406. equals(right) {
  6407. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6408. }
  6409. clone() {
  6410. return new BoundingSphere(this.center, this.radius);
  6411. }
  6412. union(boundingSphere) {
  6413. const leftCenter = this.center;
  6414. const leftRadius = this.radius;
  6415. const rightCenter = boundingSphere.center;
  6416. const rightRadius = boundingSphere.radius;
  6417. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6418. const centerSeparation = toRightCenter.magnitude();
  6419. if (leftRadius >= centerSeparation + rightRadius) {
  6420. return this.clone();
  6421. }
  6422. if (rightRadius >= centerSeparation + leftRadius) {
  6423. return boundingSphere.clone();
  6424. }
  6425. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6426. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6427. this.center.copy(scratchVector2);
  6428. this.radius = halfDistanceBetweenTangentPoints;
  6429. return this;
  6430. }
  6431. expand(point) {
  6432. point = scratchVector$3.from(point);
  6433. const radius = point.subtract(this.center).magnitude();
  6434. if (radius > this.radius) {
  6435. this.radius = radius;
  6436. }
  6437. return this;
  6438. }
  6439. transform(transform) {
  6440. this.center.transform(transform);
  6441. const scale = getScaling(scratchVector$3, transform);
  6442. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6443. return this;
  6444. }
  6445. distanceSquaredTo(point) {
  6446. const d = this.distanceTo(point);
  6447. return d * d;
  6448. }
  6449. distanceTo(point) {
  6450. point = scratchVector$3.from(point);
  6451. const delta = point.subtract(this.center);
  6452. return Math.max(0, delta.len() - this.radius);
  6453. }
  6454. intersectPlane(plane) {
  6455. const center = this.center;
  6456. const radius = this.radius;
  6457. const normal = plane.normal;
  6458. const distanceToPlane = normal.dot(center) + plane.distance;
  6459. if (distanceToPlane < -radius) {
  6460. return INTERSECTION.OUTSIDE;
  6461. }
  6462. if (distanceToPlane < radius) {
  6463. return INTERSECTION.INTERSECTING;
  6464. }
  6465. return INTERSECTION.INSIDE;
  6466. }
  6467. }
  6468. const scratchVector3 = new Vector3();
  6469. const scratchOffset = new Vector3();
  6470. const scratchVectorU = new Vector3();
  6471. const scratchVectorV = new Vector3();
  6472. const scratchVectorW = new Vector3();
  6473. const scratchCorner = new Vector3();
  6474. const scratchToCenter = new Vector3();
  6475. const MATRIX3 = {
  6476. COLUMN0ROW0: 0,
  6477. COLUMN0ROW1: 1,
  6478. COLUMN0ROW2: 2,
  6479. COLUMN1ROW0: 3,
  6480. COLUMN1ROW1: 4,
  6481. COLUMN1ROW2: 5,
  6482. COLUMN2ROW0: 6,
  6483. COLUMN2ROW1: 7,
  6484. COLUMN2ROW2: 8
  6485. };
  6486. class OrientedBoundingBox {
  6487. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6488. this.center = new Vector3().from(center);
  6489. this.halfAxes = new Matrix3(halfAxes);
  6490. }
  6491. get halfSize() {
  6492. const xAxis = this.halfAxes.getColumn(0);
  6493. const yAxis = this.halfAxes.getColumn(1);
  6494. const zAxis = this.halfAxes.getColumn(2);
  6495. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6496. }
  6497. get quaternion() {
  6498. const xAxis = this.halfAxes.getColumn(0);
  6499. const yAxis = this.halfAxes.getColumn(1);
  6500. const zAxis = this.halfAxes.getColumn(2);
  6501. const normXAxis = new Vector3(xAxis).normalize();
  6502. const normYAxis = new Vector3(yAxis).normalize();
  6503. const normZAxis = new Vector3(zAxis).normalize();
  6504. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6505. }
  6506. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6507. const quaternionObject = new Quaternion(quaternion);
  6508. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6509. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6510. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6511. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6512. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6513. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6514. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6515. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6516. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6517. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6518. this.center = new Vector3().from(center);
  6519. this.halfAxes = directionsMatrix;
  6520. return this;
  6521. }
  6522. clone() {
  6523. return new OrientedBoundingBox(this.center, this.halfAxes);
  6524. }
  6525. equals(right) {
  6526. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6527. }
  6528. getBoundingSphere(result = new BoundingSphere()) {
  6529. const halfAxes = this.halfAxes;
  6530. const u = halfAxes.getColumn(0, scratchVectorU);
  6531. const v = halfAxes.getColumn(1, scratchVectorV);
  6532. const w = halfAxes.getColumn(2, scratchVectorW);
  6533. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6534. result.center.copy(this.center);
  6535. result.radius = cornerVector.magnitude();
  6536. return result;
  6537. }
  6538. intersectPlane(plane) {
  6539. const center = this.center;
  6540. const normal = plane.normal;
  6541. const halfAxes = this.halfAxes;
  6542. const normalX = normal.x;
  6543. const normalY = normal.y;
  6544. const normalZ = normal.z;
  6545. 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]);
  6546. const distanceToPlane = normal.dot(center) + plane.distance;
  6547. if (distanceToPlane <= -radEffective) {
  6548. return INTERSECTION.OUTSIDE;
  6549. } else if (distanceToPlane >= radEffective) {
  6550. return INTERSECTION.INSIDE;
  6551. }
  6552. return INTERSECTION.INTERSECTING; //在相机frustum内
  6553. }
  6554. distanceTo(point) {
  6555. return Math.sqrt(this.distanceSquaredTo(point));
  6556. }
  6557. distanceSquaredTo(point) {
  6558. const offset = scratchOffset.from(point).subtract(this.center);
  6559. const halfAxes = this.halfAxes;
  6560. const u = halfAxes.getColumn(0, scratchVectorU);
  6561. const v = halfAxes.getColumn(1, scratchVectorV);
  6562. const w = halfAxes.getColumn(2, scratchVectorW);
  6563. const uHalf = u.magnitude();
  6564. const vHalf = v.magnitude();
  6565. const wHalf = w.magnitude();
  6566. u.normalize();
  6567. v.normalize();
  6568. w.normalize();
  6569. let distanceSquared = 0.0;
  6570. let d;
  6571. d = Math.abs(offset.dot(u)) - uHalf;
  6572. if (d > 0) {
  6573. distanceSquared += d * d;
  6574. }
  6575. d = Math.abs(offset.dot(v)) - vHalf;
  6576. if (d > 0) {
  6577. distanceSquared += d * d;
  6578. }
  6579. d = Math.abs(offset.dot(w)) - wHalf;
  6580. if (d > 0) {
  6581. distanceSquared += d * d;
  6582. }
  6583. return distanceSquared;
  6584. }
  6585. computePlaneDistances(position, direction, result = [-0, -0]) {
  6586. let minDist = Number.POSITIVE_INFINITY;
  6587. let maxDist = Number.NEGATIVE_INFINITY;
  6588. const center = this.center;
  6589. const halfAxes = this.halfAxes;
  6590. const u = halfAxes.getColumn(0, scratchVectorU);
  6591. const v = halfAxes.getColumn(1, scratchVectorV);
  6592. const w = halfAxes.getColumn(2, scratchVectorW);
  6593. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6594. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6595. let mag = direction.dot(toCenter);
  6596. minDist = Math.min(mag, minDist);
  6597. maxDist = Math.max(mag, maxDist);
  6598. corner.copy(center).add(u).add(v).subtract(w);
  6599. toCenter.copy(corner).subtract(position);
  6600. mag = direction.dot(toCenter);
  6601. minDist = Math.min(mag, minDist);
  6602. maxDist = Math.max(mag, maxDist);
  6603. corner.copy(center).add(u).subtract(v).add(w);
  6604. toCenter.copy(corner).subtract(position);
  6605. mag = direction.dot(toCenter);
  6606. minDist = Math.min(mag, minDist);
  6607. maxDist = Math.max(mag, maxDist);
  6608. corner.copy(center).add(u).subtract(v).subtract(w);
  6609. toCenter.copy(corner).subtract(position);
  6610. mag = direction.dot(toCenter);
  6611. minDist = Math.min(mag, minDist);
  6612. maxDist = Math.max(mag, maxDist);
  6613. center.copy(corner).subtract(u).add(v).add(w);
  6614. toCenter.copy(corner).subtract(position);
  6615. mag = direction.dot(toCenter);
  6616. minDist = Math.min(mag, minDist);
  6617. maxDist = Math.max(mag, maxDist);
  6618. center.copy(corner).subtract(u).add(v).subtract(w);
  6619. toCenter.copy(corner).subtract(position);
  6620. mag = direction.dot(toCenter);
  6621. minDist = Math.min(mag, minDist);
  6622. maxDist = Math.max(mag, maxDist);
  6623. center.copy(corner).subtract(u).subtract(v).add(w);
  6624. toCenter.copy(corner).subtract(position);
  6625. mag = direction.dot(toCenter);
  6626. minDist = Math.min(mag, minDist);
  6627. maxDist = Math.max(mag, maxDist);
  6628. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6629. toCenter.copy(corner).subtract(position);
  6630. mag = direction.dot(toCenter);
  6631. minDist = Math.min(mag, minDist);
  6632. maxDist = Math.max(mag, maxDist);
  6633. result[0] = minDist;
  6634. result[1] = maxDist;
  6635. return result;
  6636. }
  6637. transform(transformation) {
  6638. this.center.transformAsPoint(transformation);
  6639. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6640. xAxis.transformAsPoint(transformation);
  6641. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6642. yAxis.transformAsPoint(transformation);
  6643. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6644. zAxis.transformAsPoint(transformation);
  6645. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6646. return this;
  6647. }
  6648. getTransform() {
  6649. throw new Error('not implemented');
  6650. }
  6651. }
  6652. const scratchPosition$1 = new Vector3();
  6653. const scratchNormal$1 = new Vector3();
  6654. class Plane {
  6655. constructor(normal = [0, 0, 1], distance = 0) {
  6656. this.normal = new Vector3();
  6657. this.distance = -0;
  6658. this.fromNormalDistance(normal, distance);
  6659. }
  6660. fromNormalDistance(normal, distance) {
  6661. assert$4(Number.isFinite(distance));
  6662. this.normal.from(normal).normalize();
  6663. this.distance = distance;
  6664. return this;
  6665. }
  6666. fromPointNormal(point, normal) {
  6667. point = scratchPosition$1.from(point);
  6668. this.normal.from(normal).normalize();
  6669. const distance = -this.normal.dot(point);
  6670. this.distance = distance;
  6671. return this;
  6672. }
  6673. fromCoefficients(a, b, c, d) {
  6674. this.normal.set(a, b, c);
  6675. assert$4(equals(this.normal.len(), 1));
  6676. this.distance = d;
  6677. return this;
  6678. }
  6679. clone(plane) {
  6680. return new Plane(this.normal, this.distance);
  6681. }
  6682. equals(right) {
  6683. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6684. }
  6685. getPointDistance(point) {
  6686. return this.normal.dot(point) + this.distance;
  6687. }
  6688. transform(matrix4) {
  6689. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6690. const point = this.normal.scale(-this.distance).transform(matrix4);
  6691. return this.fromPointNormal(point, normal);
  6692. }
  6693. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6694. point = scratchPosition$1.from(point);
  6695. const pointDistance = this.getPointDistance(point);
  6696. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6697. return point.subtract(scaledNormal).to(result);
  6698. }
  6699. }
  6700. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6701. const scratchPlaneCenter = new Vector3();
  6702. const scratchPlaneNormal$1 = new Vector3();
  6703. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6704. class CullingVolume {
  6705. static get MASK_OUTSIDE() {
  6706. return 0xffffffff;
  6707. }
  6708. static get MASK_INSIDE() {
  6709. return 0x00000000;
  6710. }
  6711. static get MASK_INDETERMINATE() {
  6712. return 0x7fffffff;
  6713. }
  6714. constructor(planes = []) {
  6715. this.planes = planes;
  6716. assert$4(this.planes.every(plane => plane instanceof Plane));
  6717. }
  6718. fromBoundingSphere(boundingSphere) {
  6719. this.planes.length = 2 * faces.length;
  6720. const center = boundingSphere.center;
  6721. const radius = boundingSphere.radius;
  6722. let planeIndex = 0;
  6723. for (const faceNormal of faces) {
  6724. let plane0 = this.planes[planeIndex];
  6725. let plane1 = this.planes[planeIndex + 1];
  6726. if (!plane0) {
  6727. plane0 = this.planes[planeIndex] = new Plane();
  6728. }
  6729. if (!plane1) {
  6730. plane1 = this.planes[planeIndex + 1] = new Plane();
  6731. }
  6732. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6733. -faceNormal.dot(plane0Center);
  6734. plane0.fromPointNormal(plane0Center, faceNormal);
  6735. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6736. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6737. -negatedFaceNormal.dot(plane1Center);
  6738. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6739. planeIndex += 2;
  6740. }
  6741. return this;
  6742. }
  6743. computeVisibility(boundingVolume) {
  6744. assert$4(boundingVolume);
  6745. let intersect = INTERSECTION.INSIDE;
  6746. for (const plane of this.planes) {
  6747. const result = boundingVolume.intersectPlane(plane);
  6748. switch (result) {
  6749. case INTERSECTION.OUTSIDE:
  6750. return INTERSECTION.OUTSIDE;
  6751. case INTERSECTION.INTERSECTING:
  6752. intersect = INTERSECTION.INTERSECTING;
  6753. break;
  6754. }
  6755. }
  6756. return intersect;
  6757. }
  6758. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6759. assert$4(boundingVolume, 'boundingVolume is required.');
  6760. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6761. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6762. return parentPlaneMask;
  6763. }
  6764. let mask = CullingVolume.MASK_INSIDE;
  6765. const planes = this.planes;
  6766. for (let k = 0; k < this.planes.length; ++k) {
  6767. const flag = k < 31 ? 1 << k : 0;
  6768. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6769. continue;
  6770. }
  6771. const plane = planes[k];
  6772. const result = boundingVolume.intersectPlane(plane);
  6773. if (result === INTERSECTION.OUTSIDE) {
  6774. return CullingVolume.MASK_OUTSIDE;
  6775. } else if (result === INTERSECTION.INTERSECTING) {
  6776. mask |= flag;
  6777. }
  6778. }
  6779. return mask;
  6780. }
  6781. }
  6782. const scratchPlaneUpVector = new Vector3();
  6783. const scratchPlaneRightVector = new Vector3();
  6784. const scratchPlaneNearCenter = new Vector3();
  6785. const scratchPlaneFarCenter = new Vector3();
  6786. const scratchPlaneNormal = new Vector3();
  6787. class PerspectiveOffCenterFrustum {
  6788. constructor(options = {}) {
  6789. options = {
  6790. near: 1.0,
  6791. far: 500000000.0,
  6792. ...options
  6793. };
  6794. this.left = options.left;
  6795. this._left = undefined;
  6796. this.right = options.right;
  6797. this._right = undefined;
  6798. this.top = options.top;
  6799. this._top = undefined;
  6800. this.bottom = options.bottom;
  6801. this._bottom = undefined;
  6802. this.near = options.near;
  6803. this._near = this.near;
  6804. this.far = options.far;
  6805. this._far = this.far;
  6806. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6807. this._perspectiveMatrix = new Matrix4();
  6808. this._infinitePerspective = new Matrix4();
  6809. }
  6810. clone() {
  6811. return new PerspectiveOffCenterFrustum({
  6812. right: this.right,
  6813. left: this.left,
  6814. top: this.top,
  6815. bottom: this.bottom,
  6816. near: this.near,
  6817. far: this.far
  6818. });
  6819. }
  6820. equals(other) {
  6821. 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;
  6822. }
  6823. get projectionMatrix() {
  6824. update$1(this);
  6825. return this._perspectiveMatrix;
  6826. }
  6827. get infiniteProjectionMatrix() {
  6828. update$1(this);
  6829. return this._infinitePerspective;
  6830. }
  6831. computeCullingVolume(position, direction, up) {
  6832. assert$4(position, 'position is required.');
  6833. assert$4(direction, 'direction is required.');
  6834. assert$4(up, 'up is required.');
  6835. const planes = this._cullingVolume.planes;
  6836. up = scratchPlaneUpVector.copy(up).normalize();
  6837. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6838. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6839. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6840. let normal = scratchPlaneNormal;
  6841. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6842. planes[0].fromPointNormal(position, normal);
  6843. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6844. planes[1].fromPointNormal(position, normal);
  6845. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6846. planes[2].fromPointNormal(position, normal);
  6847. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6848. planes[3].fromPointNormal(position, normal);
  6849. normal = new Vector3().copy(direction);
  6850. planes[4].fromPointNormal(nearCenter, normal);
  6851. normal.negate();
  6852. planes[5].fromPointNormal(farCenter, normal);
  6853. return this._cullingVolume;
  6854. }
  6855. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6856. update$1(this);
  6857. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6858. assert$4(drawingBufferWidth > 0);
  6859. assert$4(drawingBufferHeight > 0);
  6860. assert$4(distance > 0);
  6861. assert$4(result);
  6862. const inverseNear = 1.0 / this.near;
  6863. let tanTheta = this.top * inverseNear;
  6864. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6865. tanTheta = this.right * inverseNear;
  6866. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6867. result.x = pixelWidth;
  6868. result.y = pixelHeight;
  6869. return result;
  6870. }
  6871. }
  6872. function update$1(frustum) {
  6873. 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));
  6874. const {
  6875. top,
  6876. bottom,
  6877. right,
  6878. left,
  6879. near,
  6880. far
  6881. } = frustum;
  6882. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6883. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6884. frustum._left = left;
  6885. frustum._right = right;
  6886. frustum._top = top;
  6887. frustum._bottom = bottom;
  6888. frustum._near = near;
  6889. frustum._far = far;
  6890. frustum._perspectiveMatrix = new Matrix4().frustum({
  6891. left,
  6892. right,
  6893. bottom,
  6894. top,
  6895. near,
  6896. far
  6897. });
  6898. frustum._infinitePerspective = new Matrix4().frustum({
  6899. left,
  6900. right,
  6901. bottom,
  6902. top,
  6903. near,
  6904. far: Infinity
  6905. });
  6906. }
  6907. }
  6908. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6909. class PerspectiveFrustum {
  6910. constructor(options = {}) {
  6911. options = {
  6912. near: 1.0,
  6913. far: 500000000.0,
  6914. xOffset: 0.0,
  6915. yOffset: 0.0,
  6916. ...options
  6917. };
  6918. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6919. this.fov = options.fov;
  6920. this._fov = undefined;
  6921. this._fovy = undefined;
  6922. this._sseDenominator = undefined;
  6923. this.aspectRatio = options.aspectRatio;
  6924. this._aspectRatio = undefined;
  6925. this.near = options.near;
  6926. this._near = this.near;
  6927. this.far = options.far;
  6928. this._far = this.far;
  6929. this.xOffset = options.xOffset;
  6930. this._xOffset = this.xOffset;
  6931. this.yOffset = options.yOffset;
  6932. this._yOffset = this.yOffset;
  6933. }
  6934. clone() {
  6935. return new PerspectiveFrustum({
  6936. aspectRatio: this.aspectRatio,
  6937. fov: this.fov,
  6938. near: this.near,
  6939. far: this.far
  6940. });
  6941. }
  6942. equals(other) {
  6943. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  6944. return false;
  6945. }
  6946. update(this);
  6947. update(other);
  6948. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  6949. }
  6950. get projectionMatrix() {
  6951. update(this);
  6952. return this._offCenterFrustum.projectionMatrix;
  6953. }
  6954. get infiniteProjectionMatrix() {
  6955. update(this);
  6956. return this._offCenterFrustum.infiniteProjectionMatrix;
  6957. }
  6958. get fovy() {
  6959. update(this);
  6960. return this._fovy;
  6961. }
  6962. get sseDenominator() {
  6963. update(this);
  6964. return this._sseDenominator;
  6965. }
  6966. computeCullingVolume(position, direction, up) {
  6967. update(this);
  6968. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  6969. }
  6970. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6971. update(this);
  6972. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  6973. }
  6974. }
  6975. function update(frustum) {
  6976. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  6977. const f = frustum._offCenterFrustum;
  6978. 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) {
  6979. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  6980. //assert$4(frustum.aspectRatio > 0);
  6981. if(frustum.aspectRatio == 0){
  6982. console.log(1)
  6983. }
  6984. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  6985. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  6986. frustum._fov = frustum.fov;
  6987. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  6988. frustum._near = frustum.near;
  6989. frustum._far = frustum.far;
  6990. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  6991. frustum._xOffset = frustum.xOffset;
  6992. frustum._yOffset = frustum.yOffset;
  6993. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  6994. f.bottom = -f.top;
  6995. f.right = frustum._aspectRatio * f.top;
  6996. f.left = -f.right;
  6997. f.near = frustum.near;
  6998. f.far = frustum.far;
  6999. f.right += frustum.xOffset;
  7000. f.left += frustum.xOffset;
  7001. f.top += frustum.yOffset;
  7002. f.bottom += frustum.yOffset;
  7003. }
  7004. }
  7005. new Vector3();
  7006. new Vector3();
  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 Matrix3();
  7018. new Matrix3();
  7019. new Matrix3();
  7020. new Matrix3();
  7021. new Matrix3();
  7022. new Vector3();
  7023. new Vector3();
  7024. new Vector3();
  7025. new Vector3();
  7026. new Vector3();
  7027. new Matrix3();
  7028. ({
  7029. diagonal: new Matrix3(),
  7030. unitary: new Matrix3()
  7031. });
  7032. const scratchVector$2 = new Vector3();
  7033. const scratchPosition = new Vector3();
  7034. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7035. function getFrameState(viewport, frameNumber) {
  7036. const {
  7037. cameraDirection,
  7038. cameraUp,
  7039. height
  7040. } = viewport;
  7041. const {
  7042. metersPerUnit
  7043. } = viewport.distanceScales;
  7044. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7045. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7046. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7047. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7048. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7049. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7050. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7051. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7052. return {
  7053. camera: {
  7054. position: cameraPositionCartesian,
  7055. direction: cameraDirectionCartesian,
  7056. up: cameraUpCartesian
  7057. },
  7058. viewport,
  7059. height,
  7060. cullingVolume,
  7061. frameNumber,
  7062. sseDenominator: 1.15
  7063. };
  7064. }
  7065. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7066. const frustumPlanes = viewport.getFrustumPlanes();
  7067. let i = 0;
  7068. for (const dir in frustumPlanes) {
  7069. const plane = frustumPlanes[dir];
  7070. const distanceToCenter = plane.normal.dot(viewport.center);
  7071. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7072. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7073. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7074. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7075. }
  7076. }
  7077. const WGS84_RADIUS_X = 6378137.0;
  7078. const WGS84_RADIUS_Y = 6378137.0;
  7079. const WGS84_RADIUS_Z = 6356752.3142451793;
  7080. const scratchVector$1 = new Vector3();
  7081. function getZoomFromBoundingVolume(boundingVolume) {
  7082. const {
  7083. halfAxes,
  7084. radius,
  7085. width,
  7086. height
  7087. } = boundingVolume;
  7088. if (halfAxes) {
  7089. const obbSize = getObbSize(halfAxes);
  7090. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7091. } else if (radius) {
  7092. return Math.log2(WGS84_RADIUS_Z / radius);
  7093. } else if (height && width) {
  7094. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7095. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7096. return (zoomX + zoomY) / 2;
  7097. }
  7098. return 1;
  7099. }
  7100. function getObbSize(halfAxes) {
  7101. halfAxes.getColumn(0, scratchVector$1);
  7102. const axeY = halfAxes.getColumn(1);
  7103. const axeZ = halfAxes.getColumn(2);
  7104. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7105. const size = farthestVertex.len();
  7106. return size;
  7107. }
  7108. const TILE_CONTENT_STATE = {
  7109. UNLOADED: 0,
  7110. LOADING: 1,
  7111. PROCESSING: 2,
  7112. READY: 3,
  7113. EXPIRED: 4,
  7114. FAILED: 5
  7115. };
  7116. const TILE_REFINEMENT = {
  7117. ADD: 1,
  7118. REPLACE: 2
  7119. };
  7120. const TILE_TYPE = {
  7121. EMPTY: 'empty',
  7122. SCENEGRAPH: 'scenegraph',
  7123. POINTCLOUD: 'pointcloud',
  7124. MESH: 'mesh'
  7125. };
  7126. const TILESET_TYPE = {
  7127. I3S: 'I3S',
  7128. TILES3D: 'TILES3D'
  7129. };
  7130. const LOD_METRIC_TYPE = {
  7131. GEOMETRIC_ERROR: 'geometricError',
  7132. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7133. };
  7134. const TILE3D_OPTIMIZATION_HINT = {
  7135. NOT_COMPUTED: -1,
  7136. USE_OPTIMIZATION: 1,
  7137. SKIP_OPTIMIZATION: 0
  7138. };
  7139. function defined$3(x) {
  7140. return x !== undefined && x !== null;
  7141. }
  7142. const scratchScale = new Vector3();
  7143. const scratchNorthWest = new Vector3();
  7144. const scratchSouthEast = new Vector3();
  7145. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7146. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7147. if (boundingVolumeHeader.box) {
  7148. return createBox(boundingVolumeHeader.box, transform, result);
  7149. }
  7150. if (boundingVolumeHeader.region) {
  7151. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7152. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7153. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7154. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7155. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7156. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7157. }
  7158. if (boundingVolumeHeader.sphere) {
  7159. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7160. }
  7161. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7162. }
  7163. function createBox(box, transform, result) {
  7164. const center = new Vector3(box[0], box[1], box[2]);
  7165. result && (result.oriCenter = center)//add
  7166. transform.transform(center, center);
  7167. let origin = [];
  7168. if (box.length === 10) {
  7169. const halfSize = box.slice(3, 6);
  7170. const quaternion = new Quaternion();
  7171. quaternion.fromArray(box, 6);
  7172. const x = new Vector3([1, 0, 0]);
  7173. const y = new Vector3([0, 1, 0]);
  7174. const z = new Vector3([0, 0, 1]);
  7175. x.transformByQuaternion(quaternion);
  7176. x.scale(halfSize[0]);
  7177. y.transformByQuaternion(quaternion);
  7178. y.scale(halfSize[1]);
  7179. z.transformByQuaternion(quaternion);
  7180. z.scale(halfSize[2]);
  7181. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7182. } else {
  7183. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7184. }
  7185. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7186. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7187. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7188. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7189. if (defined$3(result)) {
  7190. result.center = center;
  7191. result.halfAxes = halfAxes;
  7192. return result;
  7193. }
  7194. return new OrientedBoundingBox(center, halfAxes);
  7195. }
  7196. function createSphere(sphere, transform, result) {
  7197. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7198. transform.transform(center, center);
  7199. const scale = transform.getScale(scratchScale);
  7200. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7201. const radius = sphere[3] * uniformScale;
  7202. if (defined$3(result)) {
  7203. result.center = center;
  7204. result.radius = radius;
  7205. return result;
  7206. }
  7207. return new BoundingSphere(center, radius);
  7208. }
  7209. new Vector3();
  7210. new Vector3();
  7211. new Matrix4();
  7212. new Vector3();
  7213. new Vector3();
  7214. new Vector3();
  7215. function fog(distanceToCamera, density) {
  7216. const scalar = distanceToCamera * density;
  7217. return 1.0 - Math.exp(-(scalar * scalar));
  7218. }
  7219. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7220. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7221. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7222. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7223. const dynamicError = fog(distanceToCamera, density) * factor;
  7224. return dynamicError;
  7225. }
  7226. return 0;
  7227. }
  7228. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7229. const tileset = tile.tileset;
  7230. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7231. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7232. if (lodMetricValue === 0.0) {
  7233. return 0.0;
  7234. }
  7235. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7236. const {
  7237. height,
  7238. sseDenominator
  7239. } = frameState;
  7240. const {
  7241. viewDistanceScale
  7242. } = tileset.options;
  7243. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7244. error -= getDynamicScreenSpaceError(tileset, distance);
  7245. return error;
  7246. }
  7247. function getLodStatus(tile, frameState) {
  7248. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7249. return 'DIG';
  7250. }
  7251. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7252. if (screenSize < 2) {
  7253. return 'OUT';
  7254. }
  7255. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7256. return 'DRAW';
  7257. } else if (tile.header.children) {
  7258. return 'DIG';
  7259. }
  7260. return 'OUT';
  7261. }
  7262. function getProjectedRadius(tile, frameState) {
  7263. const originalViewport = frameState.viewport;
  7264. const ViewportClass = originalViewport.constructor;
  7265. const {
  7266. longitude,
  7267. latitude,
  7268. height,
  7269. width,
  7270. bearing,
  7271. zoom
  7272. } = originalViewport;
  7273. const viewport = new ViewportClass({
  7274. longitude,
  7275. latitude,
  7276. height,
  7277. width,
  7278. bearing,
  7279. zoom,
  7280. pitch: 0
  7281. });
  7282. const mbsLat = tile.header.mbs[1];
  7283. const mbsLon = tile.header.mbs[0];
  7284. const mbsZ = tile.header.mbs[2];
  7285. const mbsR = tile.header.mbs[3];
  7286. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7287. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7288. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7289. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7290. const enuToCartesianMatrix = new Matrix4();
  7291. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7292. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7293. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7294. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7295. const extraZ = projection * projection / cameraPositionEnu[2];
  7296. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7297. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7298. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7299. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7300. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7301. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7302. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7303. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7304. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7305. return projectedRadius;
  7306. }
  7307. function get3dTilesOptions(tileset) {
  7308. return {
  7309. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7310. };
  7311. }
  7312. class ManagedArray {
  7313. constructor(length = 0) {
  7314. _defineProperty(this, "_map", new Map());
  7315. _defineProperty(this, "_array", void 0);
  7316. _defineProperty(this, "_length", void 0);
  7317. this._array = new Array(length);
  7318. this._length = length;
  7319. }
  7320. get length() {
  7321. return this._length;
  7322. }
  7323. set length(length) {
  7324. this._length = length;
  7325. if (length > this._array.length) {
  7326. this._array.length = length;
  7327. }
  7328. }
  7329. get values() {
  7330. return this._array;
  7331. }
  7332. get(index) {
  7333. assert$7(index < this._array.length);
  7334. return this._array[index];
  7335. }
  7336. set(index, element) {
  7337. assert$7(index >= 0);
  7338. if (index >= this.length) {
  7339. this.length = index + 1;
  7340. }
  7341. if (this._map.has(this._array[index])) {
  7342. this._map.delete(this._array[index]);
  7343. }
  7344. this._array[index] = element;
  7345. this._map.set(element, index);
  7346. }
  7347. delete(element) {
  7348. const index = this._map.get(element);
  7349. if (index >= 0) {
  7350. this._array.splice(index, 1);
  7351. this._map.delete(element);
  7352. this.length--;
  7353. }
  7354. }
  7355. peek() {
  7356. return this._array[this._length - 1];
  7357. }
  7358. push(element) {
  7359. if (!this._map.has(element)) {
  7360. const index = this.length++;
  7361. this._array[index] = element;
  7362. this._map.set(element, index);
  7363. }
  7364. }
  7365. pop() {
  7366. const element = this._array[--this.length];
  7367. this._map.delete(element);
  7368. return element;
  7369. }
  7370. reserve(length) {
  7371. assert$7(length >= 0);
  7372. if (length > this._array.length) {
  7373. this._array.length = length;
  7374. }
  7375. }
  7376. resize(length) {
  7377. assert$7(length >= 0);
  7378. this.length = length;
  7379. }
  7380. trim(length) {
  7381. if (length === null || length === undefined) {
  7382. length = this.length;
  7383. }
  7384. this._array.length = length;
  7385. }
  7386. reset() {
  7387. this._array = [];
  7388. this._map = new Map();
  7389. this._length = 0;
  7390. }
  7391. find(target) {
  7392. return this._map.has(target);
  7393. }
  7394. }
  7395. const DEFAULT_PROPS$1 = {
  7396. loadSiblings: false,
  7397. skipLevelOfDetail: false,
  7398. maximumScreenSpaceError: 2,
  7399. updateTransforms: true,
  7400. onTraversalEnd: () => {},
  7401. viewportTraversersMap: {},
  7402. basePath: ''
  7403. };
  7404. class TilesetTraverser {
  7405. constructor(options) {
  7406. _defineProperty(this, "options", void 0);
  7407. _defineProperty(this, "root", void 0);
  7408. _defineProperty(this, "requestedTiles", void 0);
  7409. _defineProperty(this, "selectedTiles", void 0);
  7410. _defineProperty(this, "emptyTiles", void 0);
  7411. _defineProperty(this, "_traversalStack", void 0);
  7412. _defineProperty(this, "_emptyTraversalStack", void 0);
  7413. _defineProperty(this, "_frameNumber", void 0);
  7414. this.options = { ...DEFAULT_PROPS$1,
  7415. ...options
  7416. };
  7417. this._traversalStack = new ManagedArray();
  7418. this._emptyTraversalStack = new ManagedArray();
  7419. this._frameNumber = null;
  7420. this.root = null;
  7421. this.selectedTiles = {};
  7422. this.requestedTiles = {};
  7423. this.emptyTiles = {};
  7424. }
  7425. traverse(root, frameState, options) {
  7426. this.root = root;
  7427. this.options = { ...this.options,
  7428. ...options
  7429. };
  7430. this.reset();
  7431. this.updateTile(root, frameState);
  7432. this._frameNumber = frameState.frameNumber;
  7433. this.executeTraversal(root, frameState);
  7434. }
  7435. reset() {
  7436. this.requestedTiles = {};
  7437. this.selectedTiles = {};
  7438. this.emptyTiles = {};
  7439. this._traversalStack.reset();
  7440. this._emptyTraversalStack.reset();
  7441. }
  7442. executeTraversal(root, frameState) {// 遍历root
  7443. const stack = this._traversalStack;
  7444. root._selectionDepth = 1;
  7445. stack.push(root);
  7446. while (stack.length > 0) {
  7447. const tile = stack.pop();
  7448. let shouldRefine = false;
  7449. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7450. if (this.canTraverse(tile, frameState) && tile.depth < this.options.maxDepth) {//add maxDepth
  7451. this.updateChildTiles(tile, frameState);
  7452. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7453. }
  7454. const parent = tile.parent;
  7455. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7456. const stoppedRefining = !shouldRefine;
  7457. if (!tile.hasRenderContent) {
  7458. this.emptyTiles[tile.id] = tile;
  7459. this.loadTile(tile, frameState);
  7460. if (stoppedRefining) {
  7461. this.selectTile(tile, frameState);
  7462. }
  7463. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7464. this.loadTile(tile, frameState);
  7465. this.selectTile(tile, frameState);
  7466. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7467. this.loadTile(tile, frameState);
  7468. if (stoppedRefining) {
  7469. this.selectTile(tile, frameState);
  7470. }
  7471. }
  7472. this.touchTile(tile, frameState);
  7473. tile._shouldRefine = shouldRefine && parentRefines;
  7474. }
  7475. this.options.onTraversalEnd(frameState);
  7476. }
  7477. updateChildTiles(tile, frameState) {
  7478. const children = tile.children;
  7479. for (const child of children) {
  7480. this.updateTile(child, frameState);
  7481. }
  7482. return true;
  7483. }
  7484. updateAndPushChildren(tile, frameState, stack, depth) {
  7485. const {
  7486. loadSiblings,
  7487. skipLevelOfDetail
  7488. } = this.options;
  7489. const children = tile.children;
  7490. children.sort(this.compareDistanceToCamera.bind(this));
  7491. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7492. let hasVisibleChild = false;
  7493. let refines = true;
  7494. for (const child of children) {
  7495. child._selectionDepth = depth;
  7496. if (child.isVisibleAndInRequestVolume) {
  7497. if (stack.find(child)) {
  7498. stack.delete(child);
  7499. }
  7500. stack.push(child);
  7501. hasVisibleChild = true;
  7502. } else if (checkRefines || loadSiblings) {
  7503. this.loadTile(child, frameState);
  7504. this.touchTile(child, frameState);
  7505. }
  7506. if (checkRefines) {
  7507. let childRefines;
  7508. if (!child._inRequestVolume) {
  7509. childRefines = false;
  7510. } else if (!child.hasRenderContent) {
  7511. childRefines = this.executeEmptyTraversal(child, frameState);
  7512. } else {
  7513. childRefines = child.contentAvailable;
  7514. }
  7515. refines = refines && childRefines;
  7516. if (!refines) {
  7517. return false;
  7518. }
  7519. }
  7520. }
  7521. if (!hasVisibleChild) {
  7522. refines = false;
  7523. }
  7524. return refines;
  7525. }
  7526. updateTile(tile, frameState) {
  7527. this.updateTileVisibility(tile, frameState);
  7528. }
  7529. selectTile(tile, frameState) {
  7530. if (this.shouldSelectTile(tile)) {
  7531. tile._selectedFrame = frameState.frameNumber;
  7532. this.selectedTiles[tile.id] = tile;
  7533. }
  7534. }
  7535. loadTile(tile, frameState) {
  7536. if (this.shouldLoadTile(tile)) {
  7537. tile._requestedFrame = frameState.frameNumber;
  7538. tile._priority = tile._getPriority();
  7539. this.requestedTiles[tile.id] = tile;
  7540. }
  7541. }
  7542. touchTile(tile, frameState) {
  7543. tile.tileset._cache.touch(tile);
  7544. tile._touchedFrame = frameState.frameNumber;
  7545. }
  7546. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7547. if (!tile.hasChildren) {
  7548. return false;
  7549. }
  7550. if (tile.hasTilesetContent) {
  7551. return !tile.contentExpired;
  7552. }
  7553. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7554. return false;
  7555. }
  7556. return this.shouldRefine(tile, frameState, useParentMetric);
  7557. }
  7558. shouldLoadTile(tile) {
  7559. return tile.hasUnloadedContent || tile.contentExpired;
  7560. }
  7561. shouldSelectTile(tile) {
  7562. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7563. }
  7564. shouldRefine(tile, frameState, useParentMetric) {
  7565. let screenSpaceError = tile._screenSpaceError;
  7566. if (useParentMetric) {
  7567. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7568. }
  7569. return screenSpaceError > this.options.maximumScreenSpaceError;
  7570. }
  7571. updateTileVisibility(tile, frameState) {
  7572. const viewportIds = [];
  7573. if (this.options.viewportTraversersMap) {
  7574. for (const key in this.options.viewportTraversersMap) {
  7575. const value = this.options.viewportTraversersMap[key];
  7576. if (value === frameState.viewport.id) {
  7577. viewportIds.push(key);
  7578. }
  7579. }
  7580. } else {
  7581. viewportIds.push(frameState.viewport.id);
  7582. }
  7583. tile.updateVisibility(frameState, viewportIds);
  7584. }
  7585. compareDistanceToCamera(b, a) {
  7586. return b._distanceToCamera - a._distanceToCamera;
  7587. }
  7588. anyChildrenVisible(tile, frameState) {
  7589. let anyVisible = false;
  7590. for (const child of tile.children) {
  7591. child.updateVisibility(frameState);
  7592. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7593. }
  7594. return anyVisible;
  7595. }
  7596. executeEmptyTraversal(root, frameState) {
  7597. let allDescendantsLoaded = true;
  7598. const stack = this._emptyTraversalStack;
  7599. stack.push(root);
  7600. while (stack.length > 0 && allDescendantsLoaded) {
  7601. const tile = stack.pop();
  7602. this.updateTile(tile, frameState);
  7603. if (!tile.isVisibleAndInRequestVolume) {
  7604. this.loadTile(tile, frameState);
  7605. }
  7606. this.touchTile(tile, frameState);
  7607. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7608. if (traverse) {
  7609. const children = tile.children;
  7610. for (const child of children) {
  7611. if (stack.find(child)) {
  7612. stack.delete(child);
  7613. }
  7614. stack.push(child);
  7615. }
  7616. } else if (!tile.contentAvailable) {
  7617. allDescendantsLoaded = false;
  7618. }
  7619. }
  7620. return allDescendantsLoaded;
  7621. }
  7622. }
  7623. const scratchVector = new Vector3();
  7624. function defined$2(x) {
  7625. return x !== undefined && x !== null;
  7626. }
  7627. class TileHeader {
  7628. constructor(tileset, header, parentHeader, extendedId = '') {
  7629. _defineProperty(this, "tileset", void 0);
  7630. _defineProperty(this, "header", void 0);
  7631. _defineProperty(this, "id", void 0);
  7632. _defineProperty(this, "url", void 0);
  7633. _defineProperty(this, "parent", void 0);
  7634. _defineProperty(this, "refine", void 0);
  7635. _defineProperty(this, "type", void 0);
  7636. _defineProperty(this, "contentUrl", void 0);
  7637. _defineProperty(this, "lodMetricType", void 0);
  7638. _defineProperty(this, "lodMetricValue", void 0);
  7639. _defineProperty(this, "boundingVolume", void 0);
  7640. _defineProperty(this, "content", void 0);
  7641. _defineProperty(this, "contentState", void 0);
  7642. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7643. _defineProperty(this, "children", void 0);
  7644. _defineProperty(this, "depth", void 0);
  7645. _defineProperty(this, "viewportIds", void 0);
  7646. _defineProperty(this, "transform", void 0);
  7647. _defineProperty(this, "extensions", void 0);
  7648. _defineProperty(this, "userData", void 0);
  7649. _defineProperty(this, "computedTransform", void 0);
  7650. _defineProperty(this, "hasEmptyContent", void 0);
  7651. _defineProperty(this, "hasTilesetContent", void 0);
  7652. _defineProperty(this, "traverser", void 0);
  7653. _defineProperty(this, "_cacheNode", void 0);
  7654. _defineProperty(this, "_frameNumber", void 0);
  7655. _defineProperty(this, "_lodJudge", void 0);
  7656. _defineProperty(this, "_expireDate", void 0);
  7657. _defineProperty(this, "_expiredContent", void 0);
  7658. _defineProperty(this, "_shouldRefine", void 0);
  7659. _defineProperty(this, "_distanceToCamera", void 0);
  7660. _defineProperty(this, "_centerZDepth", void 0);
  7661. _defineProperty(this, "_screenSpaceError", void 0);
  7662. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7663. _defineProperty(this, "_visible", void 0);
  7664. _defineProperty(this, "_inRequestVolume", void 0);
  7665. _defineProperty(this, "_stackLength", void 0);
  7666. _defineProperty(this, "_selectionDepth", void 0);
  7667. _defineProperty(this, "_touchedFrame", void 0);
  7668. _defineProperty(this, "_visitedFrame", void 0);
  7669. _defineProperty(this, "_selectedFrame", void 0);
  7670. _defineProperty(this, "_requestedFrame", void 0);
  7671. _defineProperty(this, "_priority", void 0);
  7672. _defineProperty(this, "_contentBoundingVolume", void 0);
  7673. _defineProperty(this, "_viewerRequestVolume", void 0);
  7674. _defineProperty(this, "_initialTransform", void 0);
  7675. _defineProperty(this, "tilesetMatrix", void 0);//add
  7676. this.header = header;
  7677. this.tileset = tileset;
  7678. this.id = extendedId || header.id;
  7679. this.url = header.url;
  7680. this.parent = parentHeader;
  7681. this.refine = this._getRefine(header.refine);
  7682. this.type = header.type;
  7683. this.contentUrl = header.contentUrl;
  7684. this.lodMetricType = 'geometricError';
  7685. this.lodMetricValue = 0;
  7686. this.boundingVolume = null;
  7687. this.content = null;
  7688. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7689. this.gpuMemoryUsageInBytes = 0;
  7690. this.children = [];
  7691. this.hasEmptyContent = false;
  7692. this.hasTilesetContent = false;
  7693. this.depth = 0;
  7694. this.viewportIds = [];
  7695. this.userData = {};
  7696. this.extensions = null;
  7697. this._priority = 0;
  7698. this._touchedFrame = 0;
  7699. this._visitedFrame = 0;
  7700. this._selectedFrame = 0;
  7701. this._requestedFrame = 0;
  7702. this._screenSpaceError = 0;
  7703. this._cacheNode = null;
  7704. this._frameNumber = null;
  7705. this._cacheNode = null;
  7706. this.traverser = new TilesetTraverser({});
  7707. this._shouldRefine = false;
  7708. this._distanceToCamera = 0;
  7709. this._centerZDepth = 0;
  7710. this._visible = undefined;
  7711. this._inRequestVolume = false;
  7712. this._stackLength = 0;
  7713. this._selectionDepth = 0;
  7714. this._initialTransform = new Matrix4();
  7715. this.transform = new Matrix4();
  7716. this._initializeLodMetric(header);
  7717. this._initializeTransforms(header);
  7718. this._initializeBoundingVolumes(header);
  7719. this._initializeContent(header);
  7720. this._initializeRenderingState(header);
  7721. this._lodJudge = null;
  7722. this._expireDate = null;
  7723. this._expiredContent = null;
  7724. Object.seal(this);
  7725. }
  7726. destroy() {
  7727. this.header = null;
  7728. }
  7729. isDestroyed() {
  7730. return this.header === null;
  7731. }
  7732. get selected() {
  7733. return this._selectedFrame === this.tileset._frameNumber;
  7734. }
  7735. get isVisible() {
  7736. return this._visible;
  7737. }
  7738. get isVisibleAndInRequestVolume() {
  7739. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  7740. if(window.tileVisi2)v = this._visible && v
  7741. return v
  7742. }
  7743. get hasRenderContent() {
  7744. return !this.hasEmptyContent && !this.hasTilesetContent;
  7745. }
  7746. get hasChildren() {
  7747. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7748. }
  7749. get contentReady() {
  7750. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7751. }
  7752. get contentAvailable() {
  7753. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7754. }
  7755. get hasUnloadedContent() {
  7756. return this.hasRenderContent && this.contentUnloaded;
  7757. }
  7758. get contentUnloaded() {
  7759. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7760. }
  7761. get contentExpired() {
  7762. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7763. }
  7764. get contentFailed() {
  7765. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7766. }
  7767. getScreenSpaceError(frameState, useParentLodMetric) {
  7768. switch (this.tileset.type) {
  7769. case TILESET_TYPE.I3S:
  7770. return getProjectedRadius(this, frameState);
  7771. case TILESET_TYPE.TILES3D:
  7772. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7773. default:
  7774. throw new Error('Unsupported tileset type');
  7775. }
  7776. }
  7777. _getPriority() {
  7778. const traverser = this.tileset._traverser;
  7779. const {
  7780. skipLevelOfDetail
  7781. } = traverser.options;
  7782. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7783. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7784. return -1;
  7785. }
  7786. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7787. return -1;
  7788. }
  7789. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7790. return -1;
  7791. }
  7792. const parent = this.parent;
  7793. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7794. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7795. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7796. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7797. if(!this._visible){
  7798. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  7799. }
  7800. return v
  7801. }
  7802. async loadContent() {
  7803. if (this.hasEmptyContent) {
  7804. return false;
  7805. }
  7806. if (this.content) {
  7807. return true;
  7808. }
  7809. const expired = this.contentExpired;
  7810. if (expired) {
  7811. this._expireDate = null;
  7812. }
  7813. this.contentState = TILE_CONTENT_STATE.LOADING;
  7814. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7815. if (!requestToken) {
  7816. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7817. return false;
  7818. }
  7819. try {
  7820. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  7821. const loader = this.tileset.loader;
  7822. const options = { ...this.tileset.loadOptions,
  7823. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7824. isTileset: this.type === 'json',
  7825. ...this._getLoaderSpecificOptions(loader.id)
  7826. }
  7827. };
  7828. this.content = await load(contentUrl, loader, options);
  7829. // !zeg改
  7830. if (this.tileset.options.maxDepth < this.depth) {
  7831. this.unloadContent()
  7832. return false
  7833. }
  7834. if (this.tileset.options.contentLoader) {
  7835. await this.tileset.options.contentLoader(this);
  7836. }
  7837. if (this._isTileset()) {
  7838. this.tileset._initializeTileHeaders(this.content, this);
  7839. }
  7840. this.contentState = TILE_CONTENT_STATE.READY;
  7841. this._onContentLoaded();
  7842. return true;
  7843. } catch (error) {
  7844. this.contentState = TILE_CONTENT_STATE.FAILED;
  7845. throw error;
  7846. } finally {
  7847. requestToken.done();
  7848. }
  7849. }
  7850. unloadContent() {
  7851. if (this.content && this.content.destroy) {
  7852. this.content.destroy();
  7853. }
  7854. this.content = null;
  7855. if (this.header.content && this.header.content.destroy) {
  7856. this.header.content.destroy();
  7857. }
  7858. this.header.content = null;
  7859. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7860. return true;
  7861. }
  7862. updateVisibility(frameState, viewportIds) {
  7863. if (this._frameNumber === frameState.frameNumber) {
  7864. return;
  7865. }
  7866. const parent = this.parent;
  7867. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7868. if (this.tileset._traverser.options.updateTransforms) {
  7869. const parentTransform = parent ? parent.computedTransform : new Matrix4().elements //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  7870. this._updateTransform(parentTransform);
  7871. }
  7872. this._distanceToCamera = this.distanceToTile(frameState);
  7873. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7874. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7875. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7876. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7877. this._frameNumber = frameState.frameNumber;
  7878. this.viewportIds = viewportIds;
  7879. }
  7880. visibility(frameState, parentVisibilityPlaneMask) {
  7881. const {
  7882. cullingVolume
  7883. } = frameState;
  7884. const {
  7885. boundingVolume
  7886. } = this;
  7887. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7888. }
  7889. contentVisibility() {
  7890. return true;
  7891. }
  7892. distanceToTile(frameState) {
  7893. const boundingVolume = this.boundingVolume;
  7894. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7895. }
  7896. cameraSpaceZDepth({
  7897. camera
  7898. }) {
  7899. const boundingVolume = this.boundingVolume;
  7900. scratchVector.subVectors(boundingVolume.center, camera.position);
  7901. return camera.direction.dot(scratchVector);
  7902. }
  7903. insideViewerRequestVolume(frameState) {
  7904. const viewerRequestVolume = this._viewerRequestVolume;
  7905. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7906. }
  7907. updateExpiration() {
  7908. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7909. const now = Date.now();
  7910. if (Date.lessThan(this._expireDate, now)) {
  7911. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7912. this._expiredContent = this.content;
  7913. }
  7914. }
  7915. }
  7916. get extras() {
  7917. return this.header.extras;
  7918. }
  7919. _initializeLodMetric(header) {
  7920. if ('lodMetricType' in header) {
  7921. this.lodMetricType = header.lodMetricType;
  7922. } else {
  7923. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7924. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7925. }
  7926. if ('lodMetricValue' in header) {
  7927. this.lodMetricValue = header.lodMetricValue;
  7928. } else {
  7929. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  7930. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  7931. }
  7932. }
  7933. _initializeTransforms(tileHeader) {
  7934. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  7935. const parent = this.parent;
  7936. const tileset = this.tileset;
  7937. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4().elements // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  7938. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  7939. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  7940. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  7941. }
  7942. _initializeBoundingVolumes(tileHeader) {
  7943. this._contentBoundingVolume = null;
  7944. this._viewerRequestVolume = null;
  7945. this._updateBoundingVolume(tileHeader);
  7946. }
  7947. _initializeContent(tileHeader) {
  7948. this.content = {
  7949. _tileset: this.tileset,
  7950. _tile: this
  7951. };
  7952. this.hasEmptyContent = true;
  7953. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7954. this.hasTilesetContent = false;
  7955. if (tileHeader.contentUrl) {
  7956. this.content = null;
  7957. this.hasEmptyContent = false;
  7958. }
  7959. }
  7960. _initializeRenderingState(header) {
  7961. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  7962. this._shouldRefine = false;
  7963. this._distanceToCamera = 0;
  7964. this._centerZDepth = 0;
  7965. this._screenSpaceError = 0;
  7966. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  7967. this._visible = undefined;
  7968. this._inRequestVolume = false;
  7969. this._stackLength = 0;
  7970. this._selectionDepth = 0;
  7971. this._frameNumber = 0;
  7972. this._touchedFrame = 0;
  7973. this._visitedFrame = 0;
  7974. this._selectedFrame = 0;
  7975. this._requestedFrame = 0;
  7976. this._priority = 0.0;
  7977. }
  7978. _getRefine(refine) {
  7979. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  7980. }
  7981. _isTileset() {
  7982. return this.contentUrl.indexOf('.json') !== -1;
  7983. }
  7984. _onContentLoaded() {
  7985. switch (this.content && this.content.type) {
  7986. case 'vctr':
  7987. case 'geom':
  7988. this.tileset._traverser.disableSkipLevelOfDetail = true;
  7989. break;
  7990. }
  7991. if (this._isTileset()) {
  7992. this.hasTilesetContent = true;
  7993. }
  7994. }
  7995. _updateBoundingVolume(header) {
  7996. let computedTransform = new Matrix4(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  7997. //console.log('_updateBoundingVolume computedTransform', this.tileset.modelMatrix, computedTransform)
  7998. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  7999. const content = header.content;
  8000. if (!content) {
  8001. return;
  8002. }
  8003. if (content.boundingVolume) {
  8004. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  8005. }
  8006. if (header.viewerRequestVolume) {
  8007. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  8008. }
  8009. }
  8010. _updateTransform(parentTransform = new Matrix4()) {
  8011. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8012. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix) //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  8013. if (!didTransformChange) {
  8014. return;
  8015. }
  8016. this.tileset.modelMatrix
  8017. this.computedTransform = computedTransform;
  8018. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  8019. this._updateBoundingVolume(this.header);
  8020. }
  8021. _getLoaderSpecificOptions(loaderId) {
  8022. switch (loaderId) {
  8023. case 'i3s':
  8024. return { ...this.tileset.options.i3s,
  8025. tile: this.header,
  8026. tileset: this.tileset.tileset,
  8027. isTileHeader: false
  8028. };
  8029. case '3d-tiles':
  8030. case 'cesium-ion':
  8031. default:
  8032. return get3dTilesOptions(this.tileset.tileset);
  8033. }
  8034. }
  8035. }
  8036. class Tileset3DTraverser extends TilesetTraverser {
  8037. compareDistanceToCamera(a, b) {
  8038. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8039. }
  8040. updateTileVisibility(tile, frameState) {
  8041. super.updateTileVisibility(tile, frameState);
  8042. if (!tile.isVisibleAndInRequestVolume) {
  8043. return;
  8044. }
  8045. const hasChildren = tile.children.length > 0;
  8046. if (tile.hasTilesetContent && hasChildren) {
  8047. const firstChild = tile.children[0];
  8048. this.updateTileVisibility(firstChild, frameState);
  8049. tile._visible = firstChild._visible;
  8050. return;
  8051. }
  8052. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8053. tile._visible = false;
  8054. return;
  8055. }
  8056. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8057. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8058. if (replace && useOptimization && hasChildren) {
  8059. if (!this.anyChildrenVisible(tile, frameState)) {
  8060. tile._visible = false;
  8061. return;
  8062. }
  8063. }
  8064. }
  8065. meetsScreenSpaceErrorEarly(tile, frameState) {
  8066. const {
  8067. parent
  8068. } = tile;
  8069. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8070. return false;
  8071. }
  8072. return !this.shouldRefine(tile, frameState, true);
  8073. }
  8074. }
  8075. const STATUS = {
  8076. REQUESTED: 'REQUESTED',
  8077. COMPLETED: 'COMPLETED',
  8078. ERROR: 'ERROR'
  8079. };
  8080. class I3STileManager {
  8081. constructor() {
  8082. _defineProperty(this, "_statusMap", void 0);
  8083. this._statusMap = {};
  8084. }
  8085. add(request, key, callback, frameState) {
  8086. if (!this._statusMap[key]) {
  8087. this._statusMap[key] = {
  8088. request,
  8089. callback,
  8090. key,
  8091. frameState,
  8092. status: STATUS.REQUESTED
  8093. };
  8094. request().then(data => {
  8095. this._statusMap[key].status = STATUS.COMPLETED;
  8096. this._statusMap[key].callback(data, frameState);
  8097. }).catch(error => {
  8098. this._statusMap[key].status = STATUS.ERROR;
  8099. callback(error);
  8100. });
  8101. }
  8102. }
  8103. update(key, frameState) {
  8104. if (this._statusMap[key]) {
  8105. this._statusMap[key].frameState = frameState;
  8106. }
  8107. }
  8108. find(key) {
  8109. return this._statusMap[key];
  8110. }
  8111. }
  8112. class I3STilesetTraverser extends TilesetTraverser {
  8113. constructor(options) {
  8114. super(options);
  8115. _defineProperty(this, "_tileManager", void 0);
  8116. this._tileManager = new I3STileManager();
  8117. }
  8118. shouldRefine(tile, frameState) {
  8119. tile._lodJudge = getLodStatus(tile, frameState);
  8120. return tile._lodJudge === 'DIG';
  8121. }
  8122. updateChildTiles(tile, frameState) {
  8123. const children = tile.header.children || [];
  8124. const childTiles = tile.children;
  8125. const tileset = tile.tileset;
  8126. for (const child of children) {
  8127. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8128. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8129. if (!childTile) {
  8130. let request = () => this._loadTile(child.id, tileset);
  8131. const cachedRequest = this._tileManager.find(extendedId);
  8132. if (!cachedRequest) {
  8133. if (tileset.tileset.nodePages) {
  8134. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8135. }
  8136. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8137. } else {
  8138. this._tileManager.update(extendedId, frameState);
  8139. }
  8140. } else if (childTile) {
  8141. this.updateTile(childTile, frameState);
  8142. }
  8143. }
  8144. return false;
  8145. }
  8146. async _loadTile(nodeId, tileset) {
  8147. const {
  8148. loader
  8149. } = tileset;
  8150. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8151. const options = { ...tileset.loadOptions,
  8152. i3s: { ...tileset.loadOptions.i3s,
  8153. isTileHeader: true,
  8154. loadContent: false
  8155. }
  8156. };
  8157. return await load(nodeUrl, loader, options);
  8158. }
  8159. _onTileLoad(header, tile, extendedId) {
  8160. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8161. tile.children.push(childTile);
  8162. const frameState = this._tileManager.find(childTile.id).frameState;
  8163. this.updateTile(childTile, frameState);
  8164. if (this._frameNumber === frameState.frameNumber) {
  8165. this.executeTraversal(childTile, frameState);
  8166. }
  8167. }
  8168. }
  8169. const DEFAULT_PROPS = {
  8170. description: '',
  8171. ellipsoid: Ellipsoid.WGS84,
  8172. modelMatrix: new Matrix4(),
  8173. throttleRequests: true,
  8174. maxRequests: 64,
  8175. maximumMemoryUsage: 32,
  8176. onTileLoad: () => {},
  8177. onTileUnload: () => {},
  8178. onTileError: () => {},
  8179. onTraversalComplete: selectedTiles => selectedTiles,
  8180. contentLoader: undefined,
  8181. viewDistanceScale: 1.0,
  8182. maximumScreenSpaceError: 8,
  8183. loadTiles: true,
  8184. updateTransforms: true,
  8185. viewportTraversersMap: null,
  8186. loadOptions: {
  8187. fetch: {}
  8188. },
  8189. attributions: [],
  8190. basePath: '',
  8191. i3s: {}
  8192. };
  8193. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8194. const TILES_IN_MEMORY = 'Tiles In Memory';
  8195. const TILES_IN_VIEW = 'Tiles In View';
  8196. const TILES_RENDERABLE = 'Tiles To Render';
  8197. const TILES_LOADED = 'Tiles Loaded';
  8198. const TILES_LOADING = 'Tiles Loading';
  8199. const TILES_UNLOADED = 'Tiles Unloaded';
  8200. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8201. const POINTS_COUNT = 'Points';
  8202. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8203. let tilesetSid = 0//add
  8204. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8205. constructor(json, options) {
  8206. super()
  8207. _defineProperty(this, "options", void 0);
  8208. _defineProperty(this, "loadOptions", void 0);
  8209. _defineProperty(this, "type", void 0);
  8210. _defineProperty(this, "tileset", void 0);
  8211. _defineProperty(this, "loader", void 0);
  8212. _defineProperty(this, "url", void 0);
  8213. _defineProperty(this, "basePath", void 0);
  8214. _defineProperty(this, "modelMatrix", void 0);
  8215. _defineProperty(this, "ellipsoid", void 0);
  8216. _defineProperty(this, "lodMetricType", void 0);
  8217. _defineProperty(this, "lodMetricValue", void 0);
  8218. _defineProperty(this, "refine", void 0);
  8219. _defineProperty(this, "root", void 0);
  8220. _defineProperty(this, "roots", void 0);
  8221. _defineProperty(this, "asset", void 0);
  8222. _defineProperty(this, "description", void 0);
  8223. _defineProperty(this, "properties", void 0);
  8224. _defineProperty(this, "extras", void 0);
  8225. _defineProperty(this, "attributions", void 0);
  8226. _defineProperty(this, "credits", void 0);
  8227. _defineProperty(this, "stats", void 0);
  8228. _defineProperty(this, "traverseCounter", void 0);
  8229. _defineProperty(this, "geometricError", void 0);
  8230. _defineProperty(this, "selectedTiles", void 0);
  8231. _defineProperty(this, "cartographicCenter", void 0);
  8232. _defineProperty(this, "cartesianCenter", void 0);
  8233. _defineProperty(this, "zoom", void 0);
  8234. _defineProperty(this, "boundingVolume", void 0);
  8235. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8236. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8237. _defineProperty(this, "_traverser", void 0);
  8238. _defineProperty(this, "_cache", void 0);
  8239. _defineProperty(this, "_requestScheduler", void 0);
  8240. _defineProperty(this, "_frameNumber", void 0);
  8241. _defineProperty(this, "_queryParamsString", void 0);
  8242. _defineProperty(this, "_queryParams", void 0);
  8243. _defineProperty(this, "_extensionsUsed", void 0);
  8244. _defineProperty(this, "_tiles", void 0);
  8245. _defineProperty(this, "_pendingCount", void 0);
  8246. _defineProperty(this, "lastUpdatedVieports", void 0);
  8247. _defineProperty(this, "_requestedTiles", void 0);
  8248. _defineProperty(this, "_emptyTiles", void 0);
  8249. _defineProperty(this, "frameStateData", void 0);
  8250. _defineProperty(this, "maximumMemoryUsage", void 0);
  8251. _defineProperty(this, "visible", true);//add
  8252. assert$7(json);
  8253. this.options = { ...DEFAULT_PROPS,
  8254. ...options
  8255. };
  8256. this.tileset = json;
  8257. this.loader = json.loader;
  8258. this.type = json.type;
  8259. this.url = json.url;
  8260. this.basePath = json.basePath || dirname(this.url);
  8261. this.modelMatrix = this.options.modelMatrix;
  8262. this.ellipsoid = this.options.ellipsoid;
  8263. this.lodMetricType = json.lodMetricType;
  8264. this.lodMetricValue = json.lodMetricValue;
  8265. this.refine = json.root.refine;
  8266. this.loadOptions = this.options.loadOptions || {};
  8267. this.root = null;
  8268. this.roots = {};
  8269. this.cartographicCenter = null;
  8270. this.cartesianCenter = null;
  8271. this.zoom = 1;
  8272. this.boundingVolume = null;
  8273. this.traverseCounter = 0;
  8274. this.geometricError = 0;
  8275. this._traverser = this._initializeTraverser();
  8276. this._cache = new TilesetCache();
  8277. this._requestScheduler = new RequestScheduler({
  8278. throttleRequests: this.options.throttleRequests,
  8279. maxRequests: this.options.maxRequests
  8280. });
  8281. this._frameNumber = 0;
  8282. this._pendingCount = 0;
  8283. this._tiles = {};
  8284. this.selectedTiles = [];
  8285. this._emptyTiles = [];
  8286. this._requestedTiles = [];
  8287. this.frameStateData = {};
  8288. this.lastUpdatedVieports = null;
  8289. this._queryParams = {};
  8290. this._queryParamsString = '';
  8291. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8292. this.gpuMemoryUsageInBytes = 0;
  8293. this.stats = new Stats({
  8294. id: this.url
  8295. });
  8296. this._initializeStats();
  8297. this._extensionsUsed = undefined;
  8298. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8299. this.extras = null;
  8300. this.asset = {};
  8301. this.credits = {};
  8302. this.description = this.options.description || '';
  8303. this._initializeTileSet(json);
  8304. }
  8305. destroy() {
  8306. this._destroy();
  8307. }
  8308. isLoaded() {
  8309. return this._pendingCount === 0 && this._frameNumber !== 0;
  8310. }
  8311. get tiles() {
  8312. return Object.values(this._tiles);
  8313. }
  8314. get frameNumber() {
  8315. return this._frameNumber;
  8316. }
  8317. get queryParams() {
  8318. if (!this._queryParamsString) {
  8319. this._queryParamsString = getQueryParamString(this._queryParams);
  8320. }
  8321. return this._queryParamsString;
  8322. }
  8323. setProps(props) {
  8324. this.options = { ...this.options,
  8325. ...props
  8326. };
  8327. }
  8328. setOptions(options) {
  8329. this.options = { ...this.options,
  8330. ...options
  8331. };
  8332. }
  8333. getTileUrl(tilePath) {
  8334. const isDataUrl = tilePath.startsWith('data:');
  8335. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8336. if (isDataUrl) {
  8337. return tilePath;
  8338. }
  8339. return "".concat(tilePath).concat(this.queryParams);
  8340. }
  8341. hasExtension(extensionName) {
  8342. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8343. }
  8344. update(viewports) {
  8345. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8346. return;
  8347. }
  8348. if (this.traverseCounter > 0) {
  8349. return;
  8350. }
  8351. if (!viewports && this.lastUpdatedVieports) {
  8352. viewports = this.lastUpdatedVieports;
  8353. } else {
  8354. this.lastUpdatedVieports = viewports;
  8355. }
  8356. if (!(viewports instanceof Array)) {
  8357. viewports = [viewports];
  8358. }
  8359. this._cache.reset();
  8360. this._frameNumber++;
  8361. this.traverseCounter = viewports.length;
  8362. const viewportsToTraverse = [];
  8363. for (const viewport of viewports) {
  8364. const id = viewport.id;
  8365. if (this._needTraverse(id)) {
  8366. viewportsToTraverse.push(id);
  8367. } else {
  8368. this.traverseCounter--;
  8369. }
  8370. }
  8371. for (const viewport of viewports) {
  8372. const id = viewport.id;
  8373. if (!this.roots[id]) {
  8374. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8375. }
  8376. if (!viewportsToTraverse.includes(id)) {
  8377. continue;
  8378. }
  8379. const frameState = getFrameState(viewport, this._frameNumber);
  8380. this._traverser.traverse(this.roots[id], frameState, this.options);
  8381. }
  8382. }
  8383. _needTraverse(viewportId) {
  8384. let traverserId = viewportId;
  8385. if (this.options.viewportTraversersMap) {
  8386. traverserId = this.options.viewportTraversersMap[viewportId];
  8387. }
  8388. if (traverserId !== viewportId) {
  8389. return false;
  8390. }
  8391. return true;
  8392. }
  8393. _onTraversalEnd(frameState) {
  8394. const id = frameState.viewport.id;
  8395. if (!this.frameStateData[id]) {
  8396. this.frameStateData[id] = {
  8397. selectedTiles: [],
  8398. _requestedTiles: [],
  8399. _emptyTiles: []
  8400. };
  8401. }
  8402. const currentFrameStateData = this.frameStateData[id];
  8403. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8404. currentFrameStateData.selectedTiles = selectedTiles;
  8405. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8406. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8407. this.traverseCounter--;
  8408. if (this.traverseCounter > 0) {
  8409. return;
  8410. }
  8411. this._updateTiles();
  8412. }
  8413. _updateTiles() {
  8414. this.selectedTiles = [];
  8415. this._requestedTiles = [];
  8416. this._emptyTiles = [];
  8417. for (const frameStateKey in this.frameStateData) {
  8418. const frameStateDataValue = this.frameStateData[frameStateKey];
  8419. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8420. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8421. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8422. }
  8423. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8424. for (const tile of this.selectedTiles) {
  8425. this._tiles[tile.id] = tile;
  8426. }
  8427. this._loadTiles();
  8428. this._unloadTiles();
  8429. this._updateStats();
  8430. }
  8431. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8432. if (oldSelectedTiles.length !== selectedTiles.length) {
  8433. return true;
  8434. }
  8435. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8436. const set2 = new Set(selectedTiles.map(t => t.id));
  8437. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8438. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8439. return changed;
  8440. }
  8441. _loadTiles() {
  8442. for (const tile of this._requestedTiles) {
  8443. if (tile.contentUnloaded) {
  8444. this._loadTile(tile);
  8445. }
  8446. }
  8447. }
  8448. _unloadTiles() {
  8449. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8450. }
  8451. _updateStats() {
  8452. let tilesRenderable = 0;
  8453. let pointsRenderable = 0;
  8454. for (const tile of this.selectedTiles) {
  8455. if (tile.contentAvailable && tile.content) {
  8456. tilesRenderable++;
  8457. if (tile.content.pointCount) {
  8458. pointsRenderable += tile.content.pointCount;
  8459. }
  8460. }
  8461. }
  8462. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8463. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8464. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8465. }
  8466. _initializeTileSet(tilesetJson) {
  8467. this.root = this._initializeTileHeaders(tilesetJson, null);
  8468. if (this.type === TILESET_TYPE.TILES3D) {
  8469. this._initializeCesiumTileset(tilesetJson);
  8470. }
  8471. if (this.type === TILESET_TYPE.I3S) {
  8472. this._initializeI3STileset();
  8473. }
  8474. this._calculateViewProps();
  8475. }
  8476. _calculateViewProps() {
  8477. const root = this.root;
  8478. assert$7(root);
  8479. const {
  8480. center
  8481. } = root.boundingVolume;
  8482. if (!center) {
  8483. console.warn('center was not pre-calculated for the root tile');
  8484. this.cartographicCenter = new Vector3();
  8485. this.zoom = 1;
  8486. return;
  8487. }
  8488. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8489. this.cartesianCenter = center;
  8490. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8491. }
  8492. _initializeStats() {
  8493. this.stats.get(TILES_TOTAL);
  8494. this.stats.get(TILES_LOADING);
  8495. this.stats.get(TILES_IN_MEMORY);
  8496. this.stats.get(TILES_IN_VIEW);
  8497. this.stats.get(TILES_RENDERABLE);
  8498. this.stats.get(TILES_LOADED);
  8499. this.stats.get(TILES_UNLOADED);
  8500. this.stats.get(TILES_LOAD_FAILED);
  8501. this.stats.get(POINTS_COUNT, 'memory');
  8502. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8503. }
  8504. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8505. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8506. if (parentTileHeader) {
  8507. parentTileHeader.children.push(rootTile);
  8508. rootTile.depth = parentTileHeader.depth + 1;
  8509. }
  8510. if (this.type === TILESET_TYPE.TILES3D) {
  8511. const stack = [];
  8512. stack.push(rootTile);
  8513. while (stack.length > 0) {
  8514. const tile = stack.pop();
  8515. this.stats.get(TILES_TOTAL).incrementCount();
  8516. const children = tile.header.children || [];
  8517. // !zeg改
  8518. if(tile.depth < this.options.maxDepth){
  8519. for (const childHeader of children) {
  8520. const childTile = new TileHeader(this, childHeader, tile);
  8521. tile.children.push(childTile);
  8522. childTile.depth = tile.depth + 1;
  8523. stack.push(childTile);
  8524. }
  8525. }
  8526. window.maxDepth = Math.max(window.maxDepth||0,tile.depth)
  8527. }
  8528. }
  8529. return rootTile;
  8530. }
  8531. _initializeTraverser() {
  8532. let TraverserClass;
  8533. const type = this.type;
  8534. switch (type) {
  8535. case TILESET_TYPE.TILES3D:
  8536. TraverserClass = Tileset3DTraverser;
  8537. break;
  8538. case TILESET_TYPE.I3S:
  8539. TraverserClass = I3STilesetTraverser;
  8540. break;
  8541. default:
  8542. TraverserClass = TilesetTraverser;
  8543. }
  8544. return new TraverserClass({
  8545. basePath: this.basePath,
  8546. onTraversalEnd: this._onTraversalEnd.bind(this)
  8547. });
  8548. }
  8549. _destroyTileHeaders(parentTile) {
  8550. this._destroySubtree(parentTile);
  8551. }
  8552. async _loadTile(tile) {
  8553. let loaded;
  8554. try {
  8555. this._onStartTileLoading();
  8556. loaded = await tile.loadContent();
  8557. } catch (error) {
  8558. this._onTileLoadError(tile, error);
  8559. } finally {
  8560. this._onEndTileLoading(tile);//
  8561. this._onTileLoad(tile, loaded);
  8562. }
  8563. }
  8564. _onTileLoadError(tile, error) {
  8565. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8566. const message = error.message || error.toString();
  8567. const url = tile.url;
  8568. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8569. this.options.onTileError(tile, message, url);
  8570. }
  8571. _onTileLoad(tile, loaded) {
  8572. if (!loaded) {
  8573. return;
  8574. }
  8575. if (tile && tile.content) {
  8576. calculateTransformProps(tile, tile.content);
  8577. }
  8578. this._addTileToCache(tile);
  8579. this.options.onTileLoad(tile);
  8580. }
  8581. _onStartTileLoading() {
  8582. this._pendingCount++;
  8583. this.stats.get(TILES_LOADING).incrementCount();
  8584. }
  8585. _onEndTileLoading(tile) {
  8586. this._pendingCount--;
  8587. this.stats.get(TILES_LOADING).decrementCount();
  8588. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8589. }
  8590. _addTileToCache(tile) {
  8591. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8592. }
  8593. _updateCacheStats(tile) {
  8594. this.stats.get(TILES_LOADED).incrementCount();
  8595. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8596. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8597. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8598. }
  8599. _unloadTile(tile) {
  8600. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8601. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8602. this.stats.get(TILES_UNLOADED).incrementCount();
  8603. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8604. this.options.onTileUnload(tile);
  8605. tile.unloadContent();
  8606. }
  8607. _destroy() {
  8608. const stack = [];
  8609. if (this.root) {
  8610. stack.push(this.root);
  8611. }
  8612. while (stack.length > 0) {
  8613. const tile = stack.pop();
  8614. for (const child of tile.children) {
  8615. stack.push(child);
  8616. }
  8617. this._destroyTile(tile);
  8618. }
  8619. this.root = null;
  8620. }
  8621. _destroySubtree(tile) {
  8622. const root = tile;
  8623. const stack = [];
  8624. stack.push(root);
  8625. while (stack.length > 0) {
  8626. tile = stack.pop();
  8627. for (const child of tile.children) {
  8628. stack.push(child);
  8629. }
  8630. if (tile !== root) {
  8631. this._destroyTile(tile);
  8632. }
  8633. }
  8634. root.children = [];
  8635. }
  8636. _destroyTile(tile) {
  8637. this._cache.unloadTile(this, tile);
  8638. this._unloadTile(tile);
  8639. tile.destroy();
  8640. }
  8641. _initializeCesiumTileset(tilesetJson) {
  8642. this.asset = tilesetJson.asset;
  8643. if (!this.asset) {
  8644. throw new Error('Tileset must have an asset property.');
  8645. }
  8646. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8647. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8648. }
  8649. if ('tilesetVersion' in this.asset) {
  8650. this._queryParams.v = this.asset.tilesetVersion;
  8651. }
  8652. this.credits = {
  8653. attributions: this.options.attributions || []
  8654. };
  8655. this.description = this.options.description || '';
  8656. this.properties = tilesetJson.properties;
  8657. this.geometricError = tilesetJson.geometricError;
  8658. this._extensionsUsed = tilesetJson.extensionsUsed;
  8659. this.extras = tilesetJson.extras;
  8660. }
  8661. _initializeI3STileset() {
  8662. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8663. this._queryParams.token = this.loadOptions.i3s.token;
  8664. }
  8665. }
  8666. }
  8667. function getQueryParamString(queryParams) {
  8668. const queryParamStrings = [];
  8669. for (const key of Object.keys(queryParams)) {
  8670. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8671. }
  8672. switch (queryParamStrings.length) {
  8673. case 0:
  8674. return '';
  8675. case 1:
  8676. return "?".concat(queryParamStrings[0]);
  8677. default:
  8678. return "?".concat(queryParamStrings.join('&'));
  8679. }
  8680. }
  8681. const VERSION$5 = "3.1.4" ;
  8682. const TILE3D_TYPE = {
  8683. COMPOSITE: 'cmpt',
  8684. POINT_CLOUD: 'pnts',
  8685. BATCHED_3D_MODEL: 'b3dm',
  8686. INSTANCED_3D_MODEL: 'i3dm',
  8687. GEOMETRY: 'geom',
  8688. VECTOR: 'vect',
  8689. GLTF: 'glTF'
  8690. };
  8691. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8692. assert$7(arrayBuffer instanceof ArrayBuffer);
  8693. const textDecoder = new TextDecoder('utf8');
  8694. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8695. const string = textDecoder.decode(typedArray);
  8696. return string;
  8697. }
  8698. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8699. const dataView = new DataView(arrayBuffer);
  8700. 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)));
  8701. }
  8702. const VERSION$4 = "3.1.4" ;
  8703. const DEFAULT_DRACO_OPTIONS = {
  8704. draco: {
  8705. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8706. libraryPath: 'libs/',
  8707. extraAttributes: {},
  8708. attributeNameEntry: undefined
  8709. }
  8710. };
  8711. const DracoLoader$1 = {
  8712. name: 'Draco',
  8713. id: 'draco',
  8714. module: 'draco',
  8715. shapes: ['mesh'],
  8716. version: VERSION$4,
  8717. worker: true,
  8718. extensions: ['drc'],
  8719. mimeTypes: ['application/octet-stream'],
  8720. binary: true,
  8721. tests: ['DRACO'],
  8722. options: DEFAULT_DRACO_OPTIONS
  8723. };
  8724. function getMeshBoundingBox(attributes) {
  8725. let minX = Infinity;
  8726. let minY = Infinity;
  8727. let minZ = Infinity;
  8728. let maxX = -Infinity;
  8729. let maxY = -Infinity;
  8730. let maxZ = -Infinity;
  8731. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8732. const len = positions && positions.length;
  8733. for (let i = 0; i < len; i += 3) {
  8734. const x = positions[i];
  8735. const y = positions[i + 1];
  8736. const z = positions[i + 2];
  8737. minX = x < minX ? x : minX;
  8738. minY = y < minY ? y : minY;
  8739. minZ = z < minZ ? z : minZ;
  8740. maxX = x > maxX ? x : maxX;
  8741. maxY = y > maxY ? y : maxY;
  8742. maxZ = z > maxZ ? z : maxZ;
  8743. }
  8744. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8745. }
  8746. function assert$3(condition, message) {
  8747. if (!condition) {
  8748. throw new Error(message || 'loader assertion failed.');
  8749. }
  8750. }
  8751. class Schema {
  8752. constructor(fields, metadata) {
  8753. _defineProperty(this, "fields", void 0);
  8754. _defineProperty(this, "metadata", void 0);
  8755. assert$3(Array.isArray(fields));
  8756. checkNames(fields);
  8757. this.fields = fields;
  8758. this.metadata = metadata || new Map();
  8759. }
  8760. compareTo(other) {
  8761. if (this.metadata !== other.metadata) {
  8762. return false;
  8763. }
  8764. if (this.fields.length !== other.fields.length) {
  8765. return false;
  8766. }
  8767. for (let i = 0; i < this.fields.length; ++i) {
  8768. if (!this.fields[i].compareTo(other.fields[i])) {
  8769. return false;
  8770. }
  8771. }
  8772. return true;
  8773. }
  8774. select(...columnNames) {
  8775. const nameMap = Object.create(null);
  8776. for (const name of columnNames) {
  8777. nameMap[name] = true;
  8778. }
  8779. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8780. return new Schema(selectedFields, this.metadata);
  8781. }
  8782. selectAt(...columnIndices) {
  8783. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8784. return new Schema(selectedFields, this.metadata);
  8785. }
  8786. assign(schemaOrFields) {
  8787. let fields;
  8788. let metadata = this.metadata;
  8789. if (schemaOrFields instanceof Schema) {
  8790. const otherSchema = schemaOrFields;
  8791. fields = otherSchema.fields;
  8792. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8793. } else {
  8794. fields = schemaOrFields;
  8795. }
  8796. const fieldMap = Object.create(null);
  8797. for (const field of this.fields) {
  8798. fieldMap[field.name] = field;
  8799. }
  8800. for (const field of fields) {
  8801. fieldMap[field.name] = field;
  8802. }
  8803. const mergedFields = Object.values(fieldMap);
  8804. return new Schema(mergedFields, metadata);
  8805. }
  8806. }
  8807. function checkNames(fields) {
  8808. const usedNames = {};
  8809. for (const field of fields) {
  8810. if (usedNames[field.name]) {
  8811. console.warn('Schema: duplicated field name', field.name, field);
  8812. }
  8813. usedNames[field.name] = true;
  8814. }
  8815. }
  8816. function mergeMaps(m1, m2) {
  8817. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8818. }
  8819. class Field {
  8820. constructor(name, type, nullable = false, metadata = new Map()) {
  8821. _defineProperty(this, "name", void 0);
  8822. _defineProperty(this, "type", void 0);
  8823. _defineProperty(this, "nullable", void 0);
  8824. _defineProperty(this, "metadata", void 0);
  8825. this.name = name;
  8826. this.type = type;
  8827. this.nullable = nullable;
  8828. this.metadata = metadata;
  8829. }
  8830. get typeId() {
  8831. return this.type && this.type.typeId;
  8832. }
  8833. clone() {
  8834. return new Field(this.name, this.type, this.nullable, this.metadata);
  8835. }
  8836. compareTo(other) {
  8837. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8838. }
  8839. toString() {
  8840. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8841. }
  8842. }
  8843. let Type;
  8844. (function (Type) {
  8845. Type[Type["NONE"] = 0] = "NONE";
  8846. Type[Type["Null"] = 1] = "Null";
  8847. Type[Type["Int"] = 2] = "Int";
  8848. Type[Type["Float"] = 3] = "Float";
  8849. Type[Type["Binary"] = 4] = "Binary";
  8850. Type[Type["Utf8"] = 5] = "Utf8";
  8851. Type[Type["Bool"] = 6] = "Bool";
  8852. Type[Type["Decimal"] = 7] = "Decimal";
  8853. Type[Type["Date"] = 8] = "Date";
  8854. Type[Type["Time"] = 9] = "Time";
  8855. Type[Type["Timestamp"] = 10] = "Timestamp";
  8856. Type[Type["Interval"] = 11] = "Interval";
  8857. Type[Type["List"] = 12] = "List";
  8858. Type[Type["Struct"] = 13] = "Struct";
  8859. Type[Type["Union"] = 14] = "Union";
  8860. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8861. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8862. Type[Type["Map"] = 17] = "Map";
  8863. Type[Type["Dictionary"] = -1] = "Dictionary";
  8864. Type[Type["Int8"] = -2] = "Int8";
  8865. Type[Type["Int16"] = -3] = "Int16";
  8866. Type[Type["Int32"] = -4] = "Int32";
  8867. Type[Type["Int64"] = -5] = "Int64";
  8868. Type[Type["Uint8"] = -6] = "Uint8";
  8869. Type[Type["Uint16"] = -7] = "Uint16";
  8870. Type[Type["Uint32"] = -8] = "Uint32";
  8871. Type[Type["Uint64"] = -9] = "Uint64";
  8872. Type[Type["Float16"] = -10] = "Float16";
  8873. Type[Type["Float32"] = -11] = "Float32";
  8874. Type[Type["Float64"] = -12] = "Float64";
  8875. Type[Type["DateDay"] = -13] = "DateDay";
  8876. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8877. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8878. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8879. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8880. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8881. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8882. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8883. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8884. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8885. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8886. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8887. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  8888. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  8889. })(Type || (Type = {}));
  8890. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  8891. class DataType {
  8892. static isNull(x) {
  8893. return x && x.typeId === Type.Null;
  8894. }
  8895. static isInt(x) {
  8896. return x && x.typeId === Type.Int;
  8897. }
  8898. static isFloat(x) {
  8899. return x && x.typeId === Type.Float;
  8900. }
  8901. static isBinary(x) {
  8902. return x && x.typeId === Type.Binary;
  8903. }
  8904. static isUtf8(x) {
  8905. return x && x.typeId === Type.Utf8;
  8906. }
  8907. static isBool(x) {
  8908. return x && x.typeId === Type.Bool;
  8909. }
  8910. static isDecimal(x) {
  8911. return x && x.typeId === Type.Decimal;
  8912. }
  8913. static isDate(x) {
  8914. return x && x.typeId === Type.Date;
  8915. }
  8916. static isTime(x) {
  8917. return x && x.typeId === Type.Time;
  8918. }
  8919. static isTimestamp(x) {
  8920. return x && x.typeId === Type.Timestamp;
  8921. }
  8922. static isInterval(x) {
  8923. return x && x.typeId === Type.Interval;
  8924. }
  8925. static isList(x) {
  8926. return x && x.typeId === Type.List;
  8927. }
  8928. static isStruct(x) {
  8929. return x && x.typeId === Type.Struct;
  8930. }
  8931. static isUnion(x) {
  8932. return x && x.typeId === Type.Union;
  8933. }
  8934. static isFixedSizeBinary(x) {
  8935. return x && x.typeId === Type.FixedSizeBinary;
  8936. }
  8937. static isFixedSizeList(x) {
  8938. return x && x.typeId === Type.FixedSizeList;
  8939. }
  8940. static isMap(x) {
  8941. return x && x.typeId === Type.Map;
  8942. }
  8943. static isDictionary(x) {
  8944. return x && x.typeId === Type.Dictionary;
  8945. }
  8946. get typeId() {
  8947. return Type.NONE;
  8948. }
  8949. compareTo(other) {
  8950. return this === other;
  8951. }
  8952. }
  8953. _Symbol$toStringTag = Symbol.toStringTag;
  8954. class Int extends DataType {
  8955. constructor(isSigned, bitWidth) {
  8956. super();
  8957. _defineProperty(this, "isSigned", void 0);
  8958. _defineProperty(this, "bitWidth", void 0);
  8959. this.isSigned = isSigned;
  8960. this.bitWidth = bitWidth;
  8961. }
  8962. get typeId() {
  8963. return Type.Int;
  8964. }
  8965. get [_Symbol$toStringTag]() {
  8966. return 'Int';
  8967. }
  8968. toString() {
  8969. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  8970. }
  8971. }
  8972. class Int8 extends Int {
  8973. constructor() {
  8974. super(true, 8);
  8975. }
  8976. }
  8977. class Int16 extends Int {
  8978. constructor() {
  8979. super(true, 16);
  8980. }
  8981. }
  8982. class Int32 extends Int {
  8983. constructor() {
  8984. super(true, 32);
  8985. }
  8986. }
  8987. class Uint8 extends Int {
  8988. constructor() {
  8989. super(false, 8);
  8990. }
  8991. }
  8992. class Uint16 extends Int {
  8993. constructor() {
  8994. super(false, 16);
  8995. }
  8996. }
  8997. class Uint32 extends Int {
  8998. constructor() {
  8999. super(false, 32);
  9000. }
  9001. }
  9002. const Precision = {
  9003. HALF: 16,
  9004. SINGLE: 32,
  9005. DOUBLE: 64
  9006. };
  9007. _Symbol$toStringTag2 = Symbol.toStringTag;
  9008. class Float extends DataType {
  9009. constructor(precision) {
  9010. super();
  9011. _defineProperty(this, "precision", void 0);
  9012. this.precision = precision;
  9013. }
  9014. get typeId() {
  9015. return Type.Float;
  9016. }
  9017. get [_Symbol$toStringTag2]() {
  9018. return 'Float';
  9019. }
  9020. toString() {
  9021. return "Float".concat(this.precision);
  9022. }
  9023. }
  9024. class Float32 extends Float {
  9025. constructor() {
  9026. super(Precision.SINGLE);
  9027. }
  9028. }
  9029. class Float64 extends Float {
  9030. constructor() {
  9031. super(Precision.DOUBLE);
  9032. }
  9033. }
  9034. _Symbol$toStringTag7 = Symbol.toStringTag;
  9035. class FixedSizeList extends DataType {
  9036. constructor(listSize, child) {
  9037. super();
  9038. _defineProperty(this, "listSize", void 0);
  9039. _defineProperty(this, "children", void 0);
  9040. this.listSize = listSize;
  9041. this.children = [child];
  9042. }
  9043. get typeId() {
  9044. return Type.FixedSizeList;
  9045. }
  9046. get valueType() {
  9047. return this.children[0].type;
  9048. }
  9049. get valueField() {
  9050. return this.children[0];
  9051. }
  9052. get [_Symbol$toStringTag7]() {
  9053. return 'FixedSizeList';
  9054. }
  9055. toString() {
  9056. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9057. }
  9058. }
  9059. function getArrowTypeFromTypedArray(array) {
  9060. switch (array.constructor) {
  9061. case Int8Array:
  9062. return new Int8();
  9063. case Uint8Array:
  9064. return new Uint8();
  9065. case Int16Array:
  9066. return new Int16();
  9067. case Uint16Array:
  9068. return new Uint16();
  9069. case Int32Array:
  9070. return new Int32();
  9071. case Uint32Array:
  9072. return new Uint32();
  9073. case Float32Array:
  9074. return new Float32();
  9075. case Float64Array:
  9076. return new Float64();
  9077. default:
  9078. throw new Error('array type not supported');
  9079. }
  9080. }
  9081. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9082. const type = getArrowTypeFromTypedArray(attribute.value);
  9083. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9084. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9085. return field;
  9086. }
  9087. function makeMeshAttributeMetadata(attribute) {
  9088. const result = new Map();
  9089. if ('byteOffset' in attribute) {
  9090. result.set('byteOffset', attribute.byteOffset.toString(10));
  9091. }
  9092. if ('byteStride' in attribute) {
  9093. result.set('byteStride', attribute.byteStride.toString(10));
  9094. }
  9095. if ('normalized' in attribute) {
  9096. result.set('normalized', attribute.normalized.toString());
  9097. }
  9098. return result;
  9099. }
  9100. function getDracoSchema(attributes, loaderData, indices) {
  9101. const metadataMap = makeMetadata(loaderData.metadata);
  9102. const fields = [];
  9103. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9104. for (const attributeName in attributes) {
  9105. const attribute = attributes[attributeName];
  9106. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9107. fields.push(field);
  9108. }
  9109. if (indices) {
  9110. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9111. fields.push(indicesField);
  9112. }
  9113. return new Schema(fields, metadataMap);
  9114. }
  9115. function transformAttributesLoaderData(loaderData) {
  9116. const result = {};
  9117. for (const key in loaderData) {
  9118. const dracoAttribute = loaderData[key];
  9119. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9120. }
  9121. return result;
  9122. }
  9123. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9124. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9125. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9126. return field;
  9127. }
  9128. function makeMetadata(metadata) {
  9129. const metadataMap = new Map();
  9130. for (const key in metadata) {
  9131. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9132. }
  9133. return metadataMap;
  9134. }
  9135. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9136. POSITION: 'POSITION',
  9137. NORMAL: 'NORMAL',
  9138. COLOR: 'COLOR_0',
  9139. TEX_COORD: 'TEXCOORD_0'
  9140. };
  9141. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9142. 1: Int8Array,
  9143. 2: Uint8Array,
  9144. 3: Int16Array,
  9145. 4: Uint16Array,
  9146. 5: Int32Array,
  9147. 6: Uint32Array,
  9148. 9: Float32Array
  9149. };
  9150. const INDEX_ITEM_SIZE = 4;
  9151. class DracoParser {
  9152. constructor(draco) {
  9153. _defineProperty(this, "draco", void 0);
  9154. _defineProperty(this, "decoder", void 0);
  9155. _defineProperty(this, "metadataQuerier", void 0);
  9156. this.draco = draco;
  9157. this.decoder = new this.draco.Decoder();
  9158. this.metadataQuerier = new this.draco.MetadataQuerier();
  9159. }
  9160. destroy() {
  9161. this.draco.destroy(this.decoder);
  9162. this.draco.destroy(this.metadataQuerier);
  9163. }
  9164. parseSync(arrayBuffer, options = {}) {
  9165. const buffer = new this.draco.DecoderBuffer();
  9166. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9167. this._disableAttributeTransforms(options);
  9168. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9169. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9170. try {
  9171. let dracoStatus;
  9172. switch (geometry_type) {
  9173. case this.draco.TRIANGULAR_MESH:
  9174. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9175. break;
  9176. case this.draco.POINT_CLOUD:
  9177. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9178. break;
  9179. default:
  9180. throw new Error('DRACO: Unknown geometry type.');
  9181. }
  9182. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9183. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9184. throw new Error(message);
  9185. }
  9186. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9187. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9188. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9189. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9190. const data = {
  9191. loader: 'draco',
  9192. loaderData,
  9193. header: {
  9194. vertexCount: dracoGeometry.num_points(),
  9195. boundingBox
  9196. },
  9197. ...geometry,
  9198. schema
  9199. };
  9200. return data;
  9201. } finally {
  9202. this.draco.destroy(buffer);
  9203. if (dracoGeometry) {
  9204. this.draco.destroy(dracoGeometry);
  9205. }
  9206. }
  9207. }
  9208. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9209. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9210. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9211. return {
  9212. geometry_type,
  9213. num_attributes: dracoGeometry.num_attributes(),
  9214. num_points: dracoGeometry.num_points(),
  9215. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9216. metadata,
  9217. attributes
  9218. };
  9219. }
  9220. _getDracoAttributes(dracoGeometry, options) {
  9221. const dracoAttributes = {};
  9222. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9223. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9224. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9225. dracoAttributes[dracoAttribute.unique_id()] = {
  9226. unique_id: dracoAttribute.unique_id(),
  9227. attribute_type: dracoAttribute.attribute_type(),
  9228. data_type: dracoAttribute.data_type(),
  9229. num_components: dracoAttribute.num_components(),
  9230. byte_offset: dracoAttribute.byte_offset(),
  9231. byte_stride: dracoAttribute.byte_stride(),
  9232. normalized: dracoAttribute.normalized(),
  9233. attribute_index: attributeId,
  9234. metadata
  9235. };
  9236. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9237. if (quantization) {
  9238. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9239. }
  9240. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9241. if (octahedron) {
  9242. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9243. }
  9244. }
  9245. return dracoAttributes;
  9246. }
  9247. _getMeshData(dracoGeometry, loaderData, options) {
  9248. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9249. const positionAttribute = attributes.POSITION;
  9250. if (!positionAttribute) {
  9251. throw new Error('DRACO: No position attribute found.');
  9252. }
  9253. if (dracoGeometry instanceof this.draco.Mesh) {
  9254. switch (options.topology) {
  9255. case 'triangle-strip':
  9256. return {
  9257. topology: 'triangle-strip',
  9258. mode: 4,
  9259. attributes,
  9260. indices: {
  9261. value: this._getTriangleStripIndices(dracoGeometry),
  9262. size: 1
  9263. }
  9264. };
  9265. case 'triangle-list':
  9266. default:
  9267. return {
  9268. topology: 'triangle-list',
  9269. mode: 5,
  9270. attributes,
  9271. indices: {
  9272. value: this._getTriangleListIndices(dracoGeometry),
  9273. size: 1
  9274. }
  9275. };
  9276. }
  9277. }
  9278. return {
  9279. topology: 'point-list',
  9280. mode: 0,
  9281. attributes
  9282. };
  9283. }
  9284. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9285. const attributes = {};
  9286. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9287. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9288. loaderAttribute.name = attributeName;
  9289. const {
  9290. value,
  9291. size
  9292. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9293. attributes[attributeName] = {
  9294. value,
  9295. size,
  9296. byteOffset: loaderAttribute.byte_offset,
  9297. byteStride: loaderAttribute.byte_stride,
  9298. normalized: loaderAttribute.normalized
  9299. };
  9300. }
  9301. return attributes;
  9302. }
  9303. _getTriangleListIndices(dracoGeometry) {
  9304. const numFaces = dracoGeometry.num_faces();
  9305. const numIndices = numFaces * 3;
  9306. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9307. const ptr = this.draco._malloc(byteLength);
  9308. try {
  9309. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9310. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9311. } finally {
  9312. this.draco._free(ptr);
  9313. }
  9314. }
  9315. _getTriangleStripIndices(dracoGeometry) {
  9316. const dracoArray = new this.draco.DracoInt32Array();
  9317. try {
  9318. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9319. return getUint32Array(dracoArray);
  9320. } finally {
  9321. this.draco.destroy(dracoArray);
  9322. }
  9323. }
  9324. _getAttributeValues(dracoGeometry, attribute) {
  9325. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9326. const numComponents = attribute.num_components;
  9327. const numPoints = dracoGeometry.num_points();
  9328. const numValues = numPoints * numComponents;
  9329. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9330. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9331. let value;
  9332. const ptr = this.draco._malloc(byteLength);
  9333. try {
  9334. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9335. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9336. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9337. } finally {
  9338. this.draco._free(ptr);
  9339. }
  9340. return {
  9341. value,
  9342. size: numComponents
  9343. };
  9344. }
  9345. _deduceAttributeName(attribute, options) {
  9346. const uniqueId = attribute.unique_id;
  9347. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9348. if (attributeUniqueId === uniqueId) {
  9349. return attributeName;
  9350. }
  9351. }
  9352. const thisAttributeType = attribute.attribute_type;
  9353. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9354. const attributeType = this.draco[dracoAttributeConstant];
  9355. if (attributeType === thisAttributeType) {
  9356. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9357. }
  9358. }
  9359. const entryName = options.attributeNameEntry || 'name';
  9360. if (attribute.metadata[entryName]) {
  9361. return attribute.metadata[entryName].string;
  9362. }
  9363. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9364. }
  9365. _getTopLevelMetadata(dracoGeometry) {
  9366. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9367. return this._getDracoMetadata(dracoMetadata);
  9368. }
  9369. _getAttributeMetadata(dracoGeometry, attributeId) {
  9370. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9371. return this._getDracoMetadata(dracoMetadata);
  9372. }
  9373. _getDracoMetadata(dracoMetadata) {
  9374. if (!dracoMetadata || !dracoMetadata.ptr) {
  9375. return {};
  9376. }
  9377. const result = {};
  9378. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9379. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9380. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9381. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9382. }
  9383. return result;
  9384. }
  9385. _getDracoMetadataField(dracoMetadata, entryName) {
  9386. const dracoArray = new this.draco.DracoInt32Array();
  9387. try {
  9388. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9389. const intArray = getInt32Array(dracoArray);
  9390. return {
  9391. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9392. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9393. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9394. intArray
  9395. };
  9396. } finally {
  9397. this.draco.destroy(dracoArray);
  9398. }
  9399. }
  9400. _disableAttributeTransforms(options) {
  9401. const {
  9402. quantizedAttributes = [],
  9403. octahedronAttributes = []
  9404. } = options;
  9405. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9406. for (const dracoAttributeName of skipAttributes) {
  9407. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9408. }
  9409. }
  9410. _getQuantizationTransform(dracoAttribute, options) {
  9411. const {
  9412. quantizedAttributes = []
  9413. } = options;
  9414. const attribute_type = dracoAttribute.attribute_type();
  9415. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9416. if (skip) {
  9417. const transform = new this.draco.AttributeQuantizationTransform();
  9418. try {
  9419. if (transform.InitFromAttribute(dracoAttribute)) {
  9420. return {
  9421. quantization_bits: transform.quantization_bits(),
  9422. range: transform.range(),
  9423. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9424. };
  9425. }
  9426. } finally {
  9427. this.draco.destroy(transform);
  9428. }
  9429. }
  9430. return null;
  9431. }
  9432. _getOctahedronTransform(dracoAttribute, options) {
  9433. const {
  9434. octahedronAttributes = []
  9435. } = options;
  9436. const attribute_type = dracoAttribute.attribute_type();
  9437. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9438. if (octahedron) {
  9439. const transform = new this.draco.AttributeQuantizationTransform();
  9440. try {
  9441. if (transform.InitFromAttribute(dracoAttribute)) {
  9442. return {
  9443. quantization_bits: transform.quantization_bits()
  9444. };
  9445. }
  9446. } finally {
  9447. this.draco.destroy(transform);
  9448. }
  9449. }
  9450. return null;
  9451. }
  9452. }
  9453. function getDracoDataType(draco, attributeType) {
  9454. switch (attributeType) {
  9455. case Float32Array:
  9456. return draco.DT_FLOAT32;
  9457. case Int8Array:
  9458. return draco.DT_INT8;
  9459. case Int16Array:
  9460. return draco.DT_INT16;
  9461. case Int32Array:
  9462. return draco.DT_INT32;
  9463. case Uint8Array:
  9464. return draco.DT_UINT8;
  9465. case Uint16Array:
  9466. return draco.DT_UINT16;
  9467. case Uint32Array:
  9468. return draco.DT_UINT32;
  9469. default:
  9470. return draco.DT_INVALID;
  9471. }
  9472. }
  9473. function getInt32Array(dracoArray) {
  9474. const numValues = dracoArray.size();
  9475. const intArray = new Int32Array(numValues);
  9476. for (let i = 0; i < numValues; i++) {
  9477. intArray[i] = dracoArray.GetValue(i);
  9478. }
  9479. return intArray;
  9480. }
  9481. function getUint32Array(dracoArray) {
  9482. const numValues = dracoArray.size();
  9483. const intArray = new Int32Array(numValues);
  9484. for (let i = 0; i < numValues; i++) {
  9485. intArray[i] = dracoArray.GetValue(i);
  9486. }
  9487. return intArray;
  9488. }
  9489. const DRACO_VERSION = '1.4.1';
  9490. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9491. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9492. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9493. let loadDecoderPromise;
  9494. async function loadDracoDecoderModule(options) {
  9495. const modules = options.modules || {};
  9496. if (modules.draco3d) {
  9497. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9498. return {
  9499. draco
  9500. };
  9501. });
  9502. } else {
  9503. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9504. }
  9505. return await loadDecoderPromise;
  9506. }
  9507. async function loadDracoDecoder(options) {
  9508. let DracoDecoderModule;
  9509. let wasmBinary;
  9510. switch (options.draco && options.draco.decoderType) {
  9511. case 'js':
  9512. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9513. break;
  9514. case 'wasm':
  9515. default:
  9516. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9517. }
  9518. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9519. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9520. }
  9521. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9522. const options = {};
  9523. if (wasmBinary) {
  9524. options.wasmBinary = wasmBinary;
  9525. }
  9526. return new Promise(resolve => {
  9527. DracoDecoderModule({ ...options,
  9528. onModuleLoaded: draco => resolve({
  9529. draco
  9530. })
  9531. });
  9532. });
  9533. }
  9534. const DracoLoader = { ...DracoLoader$1,
  9535. parse: parse$2
  9536. };
  9537. async function parse$2(arrayBuffer, options) {
  9538. const {
  9539. draco
  9540. } = await loadDracoDecoderModule(options);
  9541. const dracoParser = new DracoParser(draco);
  9542. try {
  9543. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9544. } finally {
  9545. dracoParser.destroy();
  9546. }
  9547. }
  9548. const GL_PRIMITIVE_MODE = {
  9549. POINTS: 0x0000,
  9550. LINES: 0x0001,
  9551. LINE_LOOP: 0x0002,
  9552. LINE_STRIP: 0x0003,
  9553. TRIANGLES: 0x0004,
  9554. TRIANGLE_STRIP: 0x0005,
  9555. TRIANGLE_FAN: 0x0006
  9556. };
  9557. const GL_TYPE = {
  9558. BYTE: 5120,
  9559. UNSIGNED_BYTE: 5121,
  9560. SHORT: 5122,
  9561. UNSIGNED_SHORT: 5123,
  9562. INT: 5124,
  9563. UNSIGNED_INT: 5125,
  9564. FLOAT: 5126,
  9565. DOUBLE: 5130
  9566. };
  9567. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9568. ...GL_TYPE
  9569. };
  9570. const GL_TYPE_TO_ARRAY_TYPE = {
  9571. [GL_TYPE.DOUBLE]: Float64Array,
  9572. [GL_TYPE.FLOAT]: Float32Array,
  9573. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9574. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9575. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9576. [GL_TYPE.BYTE]: Int8Array,
  9577. [GL_TYPE.SHORT]: Int16Array,
  9578. [GL_TYPE.INT]: Int32Array
  9579. };
  9580. const NAME_TO_GL_TYPE = {
  9581. DOUBLE: GL_TYPE.DOUBLE,
  9582. FLOAT: GL_TYPE.FLOAT,
  9583. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9584. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9585. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9586. BYTE: GL_TYPE.BYTE,
  9587. SHORT: GL_TYPE.SHORT,
  9588. INT: GL_TYPE.INT
  9589. };
  9590. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9591. class GLType {
  9592. static fromTypedArray(arrayOrType) {
  9593. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9594. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9595. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9596. if (ArrayType === arrayOrType) {
  9597. return glType;
  9598. }
  9599. }
  9600. throw new Error(ERR_TYPE_CONVERSION);
  9601. }
  9602. static fromName(name) {
  9603. const glType = NAME_TO_GL_TYPE[name];
  9604. if (!glType) {
  9605. throw new Error(ERR_TYPE_CONVERSION);
  9606. }
  9607. return glType;
  9608. }
  9609. static getArrayType(glType) {
  9610. switch (glType) {
  9611. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9612. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9613. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9614. return Uint16Array;
  9615. default:
  9616. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9617. if (!ArrayType) {
  9618. throw new Error(ERR_TYPE_CONVERSION);
  9619. }
  9620. return ArrayType;
  9621. }
  9622. }
  9623. static getByteSize(glType) {
  9624. const ArrayType = GLType.getArrayType(glType);
  9625. return ArrayType.BYTES_PER_ELEMENT;
  9626. }
  9627. static validate(glType) {
  9628. return Boolean(GLType.getArrayType(glType));
  9629. }
  9630. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9631. if (length === undefined) {
  9632. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9633. }
  9634. const ArrayType = GLType.getArrayType(glType);
  9635. return new ArrayType(buffer, byteOffset, length);
  9636. }
  9637. }
  9638. function assert$2(condition, message) {
  9639. if (!condition) {
  9640. throw new Error("math.gl assertion failed. ".concat(message));
  9641. }
  9642. }
  9643. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9644. const r5 = rgb565 >> 11 & 31;
  9645. const g6 = rgb565 >> 5 & 63;
  9646. const b5 = rgb565 & 31;
  9647. target[0] = r5 << 3;
  9648. target[1] = g6 << 2;
  9649. target[2] = b5 << 3;
  9650. return target;
  9651. }
  9652. new Vector2();
  9653. new Vector3();
  9654. new Vector2();
  9655. new Vector2();
  9656. function fromSNorm(value, rangeMaximum = 255) {
  9657. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9658. }
  9659. function signNotZero(value) {
  9660. return value < 0.0 ? -1.0 : 1.0;
  9661. }
  9662. function octDecodeInRange(x, y, rangeMax, result) {
  9663. assert$2(result);
  9664. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9665. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9666. }
  9667. result.x = fromSNorm(x, rangeMax);
  9668. result.y = fromSNorm(y, rangeMax);
  9669. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9670. if (result.z < 0.0) {
  9671. const oldVX = result.x;
  9672. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9673. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9674. }
  9675. return result.normalize();
  9676. }
  9677. function octDecode(x, y, result) {
  9678. return octDecodeInRange(x, y, 255, result);
  9679. }
  9680. class Tile3DFeatureTable {
  9681. constructor(featureTableJson, featureTableBinary) {
  9682. _defineProperty(this, "json", void 0);
  9683. _defineProperty(this, "buffer", void 0);
  9684. _defineProperty(this, "featuresLength", 0);
  9685. _defineProperty(this, "_cachedTypedArrays", {});
  9686. this.json = featureTableJson;
  9687. this.buffer = featureTableBinary;
  9688. }
  9689. getExtension(extensionName) {
  9690. return this.json.extensions && this.json.extensions[extensionName];
  9691. }
  9692. hasProperty(propertyName) {
  9693. return Boolean(this.json[propertyName]);
  9694. }
  9695. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9696. const jsonValue = this.json[propertyName];
  9697. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9698. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9699. }
  9700. return jsonValue;
  9701. }
  9702. getPropertyArray(propertyName, componentType, componentLength) {
  9703. const jsonValue = this.json[propertyName];
  9704. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9705. if ('componentType' in jsonValue) {
  9706. componentType = GLType.fromName(jsonValue.componentType);
  9707. }
  9708. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9709. }
  9710. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9711. }
  9712. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9713. const jsonValue = this.json[propertyName];
  9714. if (!jsonValue) {
  9715. return jsonValue;
  9716. }
  9717. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9718. if (componentLength === 1) {
  9719. return typedArray[featureId];
  9720. }
  9721. for (let i = 0; i < componentLength; ++i) {
  9722. result[i] = typedArray[componentLength * featureId + i];
  9723. }
  9724. return result;
  9725. }
  9726. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9727. const cachedTypedArrays = this._cachedTypedArrays;
  9728. let typedArray = cachedTypedArrays[propertyName];
  9729. if (!typedArray) {
  9730. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9731. cachedTypedArrays[propertyName] = typedArray;
  9732. }
  9733. return typedArray;
  9734. }
  9735. _getTypedArrayFromArray(propertyName, componentType, array) {
  9736. const cachedTypedArrays = this._cachedTypedArrays;
  9737. let typedArray = cachedTypedArrays[propertyName];
  9738. if (!typedArray) {
  9739. typedArray = GLType.createTypedArray(componentType, array);
  9740. cachedTypedArrays[propertyName] = typedArray;
  9741. }
  9742. return typedArray;
  9743. }
  9744. }
  9745. const COMPONENTS_PER_ATTRIBUTE = {
  9746. SCALAR: 1,
  9747. VEC2: 2,
  9748. VEC3: 3,
  9749. VEC4: 4,
  9750. MAT2: 4,
  9751. MAT3: 9,
  9752. MAT4: 16
  9753. };
  9754. const UNPACKER = {
  9755. SCALAR: (values, i) => values[i],
  9756. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9757. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9758. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9759. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9760. 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]],
  9761. 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]]
  9762. };
  9763. const PACKER = {
  9764. SCALAR: (x, values, i) => {
  9765. values[i] = x;
  9766. },
  9767. VEC2: (x, values, i) => {
  9768. values[2 * i + 0] = x[0];
  9769. values[2 * i + 1] = x[1];
  9770. },
  9771. VEC3: (x, values, i) => {
  9772. values[3 * i + 0] = x[0];
  9773. values[3 * i + 1] = x[1];
  9774. values[3 * i + 2] = x[2];
  9775. },
  9776. VEC4: (x, values, i) => {
  9777. values[4 * i + 0] = x[0];
  9778. values[4 * i + 1] = x[1];
  9779. values[4 * i + 2] = x[2];
  9780. values[4 * i + 3] = x[3];
  9781. },
  9782. MAT2: (x, values, i) => {
  9783. values[4 * i + 0] = x[0];
  9784. values[4 * i + 1] = x[1];
  9785. values[4 * i + 2] = x[2];
  9786. values[4 * i + 3] = x[3];
  9787. },
  9788. MAT3: (x, values, i) => {
  9789. values[9 * i + 0] = x[0];
  9790. values[9 * i + 1] = x[1];
  9791. values[9 * i + 2] = x[2];
  9792. values[9 * i + 3] = x[3];
  9793. values[9 * i + 4] = x[4];
  9794. values[9 * i + 5] = x[5];
  9795. values[9 * i + 6] = x[6];
  9796. values[9 * i + 7] = x[7];
  9797. values[9 * i + 8] = x[8];
  9798. values[9 * i + 9] = x[9];
  9799. },
  9800. MAT4: (x, values, i) => {
  9801. values[16 * i + 0] = x[0];
  9802. values[16 * i + 1] = x[1];
  9803. values[16 * i + 2] = x[2];
  9804. values[16 * i + 3] = x[3];
  9805. values[16 * i + 4] = x[4];
  9806. values[16 * i + 5] = x[5];
  9807. values[16 * i + 6] = x[6];
  9808. values[16 * i + 7] = x[7];
  9809. values[16 * i + 8] = x[8];
  9810. values[16 * i + 9] = x[9];
  9811. values[16 * i + 10] = x[10];
  9812. values[16 * i + 11] = x[11];
  9813. values[16 * i + 12] = x[12];
  9814. values[16 * i + 13] = x[13];
  9815. values[16 * i + 14] = x[14];
  9816. values[16 * i + 15] = x[15];
  9817. }
  9818. };
  9819. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9820. const {
  9821. componentType
  9822. } = tile3DAccessor;
  9823. assert$7(tile3DAccessor.componentType);
  9824. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9825. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9826. const unpacker = UNPACKER[tile3DAccessor.type];
  9827. const packer = PACKER[tile3DAccessor.type];
  9828. byteOffset += tile3DAccessor.byteOffset;
  9829. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9830. return {
  9831. values,
  9832. type,
  9833. size,
  9834. unpacker,
  9835. packer
  9836. };
  9837. }
  9838. const defined$1 = x => x !== undefined;
  9839. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9840. if (!jsonHeader) {
  9841. return null;
  9842. }
  9843. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9844. const legacyHierarchy = jsonHeader.HIERARCHY;
  9845. if (legacyHierarchy) {
  9846. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9847. jsonHeader.extensions = jsonHeader.extensions || {};
  9848. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9849. hierarchy = legacyHierarchy;
  9850. }
  9851. if (!hierarchy) {
  9852. return null;
  9853. }
  9854. return initializeHierarchyValues(hierarchy, binaryBody);
  9855. }
  9856. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9857. let i;
  9858. let classId;
  9859. let binaryAccessor;
  9860. const instancesLength = hierarchyJson.instancesLength;
  9861. const classes = hierarchyJson.classes;
  9862. let classIds = hierarchyJson.classIds;
  9863. let parentCounts = hierarchyJson.parentCounts;
  9864. let parentIds = hierarchyJson.parentIds;
  9865. let parentIdsLength = instancesLength;
  9866. if (defined$1(classIds.byteOffset)) {
  9867. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9868. classIds.type = AttributeType.SCALAR;
  9869. binaryAccessor = getBinaryAccessor(classIds);
  9870. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9871. }
  9872. let parentIndexes;
  9873. if (defined$1(parentCounts)) {
  9874. if (defined$1(parentCounts.byteOffset)) {
  9875. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9876. parentCounts.type = AttributeType.SCALAR;
  9877. binaryAccessor = getBinaryAccessor(parentCounts);
  9878. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9879. }
  9880. parentIndexes = new Uint16Array(instancesLength);
  9881. parentIdsLength = 0;
  9882. for (i = 0; i < instancesLength; ++i) {
  9883. parentIndexes[i] = parentIdsLength;
  9884. parentIdsLength += parentCounts[i];
  9885. }
  9886. }
  9887. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  9888. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  9889. parentIds.type = AttributeType.SCALAR;
  9890. binaryAccessor = getBinaryAccessor(parentIds);
  9891. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  9892. }
  9893. const classesLength = classes.length;
  9894. for (i = 0; i < classesLength; ++i) {
  9895. const classInstancesLength = classes[i].length;
  9896. const properties = classes[i].instances;
  9897. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  9898. classes[i].instances = combine(binaryProperties, properties);
  9899. }
  9900. const classCounts = new Array(classesLength).fill(0);
  9901. const classIndexes = new Uint16Array(instancesLength);
  9902. for (i = 0; i < instancesLength; ++i) {
  9903. classId = classIds[i];
  9904. classIndexes[i] = classCounts[classId];
  9905. ++classCounts[classId];
  9906. }
  9907. const hierarchy = {
  9908. classes,
  9909. classIds,
  9910. classIndexes,
  9911. parentCounts,
  9912. parentIndexes,
  9913. parentIds
  9914. };
  9915. validateHierarchy(hierarchy);
  9916. return hierarchy;
  9917. }
  9918. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  9919. if (!hierarchy) {
  9920. return;
  9921. }
  9922. const parentCounts = hierarchy.parentCounts;
  9923. const parentIds = hierarchy.parentIds;
  9924. if (parentIds) {
  9925. return endConditionCallback(hierarchy, instanceIndex);
  9926. }
  9927. if (parentCounts > 0) {
  9928. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  9929. }
  9930. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  9931. }
  9932. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  9933. const classIds = hierarchy.classIds;
  9934. const parentCounts = hierarchy.parentCounts;
  9935. const parentIds = hierarchy.parentIds;
  9936. const parentIndexes = hierarchy.parentIndexes;
  9937. const instancesLength = classIds.length;
  9938. const visited = scratchVisited;
  9939. visited.length = Math.max(visited.length, instancesLength);
  9940. const visitedMarker = ++marker;
  9941. const stack = scratchStack;
  9942. stack.length = 0;
  9943. stack.push(instanceIndex);
  9944. while (stack.length > 0) {
  9945. instanceIndex = stack.pop();
  9946. if (visited[instanceIndex] === visitedMarker) {
  9947. continue;
  9948. }
  9949. visited[instanceIndex] = visitedMarker;
  9950. const result = endConditionCallback(hierarchy, instanceIndex);
  9951. if (defined$1(result)) {
  9952. return result;
  9953. }
  9954. const parentCount = parentCounts[instanceIndex];
  9955. const parentIndex = parentIndexes[instanceIndex];
  9956. for (let i = 0; i < parentCount; ++i) {
  9957. const parentId = parentIds[parentIndex + i];
  9958. if (parentId !== instanceIndex) {
  9959. stack.push(parentId);
  9960. }
  9961. }
  9962. }
  9963. return null;
  9964. }
  9965. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  9966. let hasParent = true;
  9967. while (hasParent) {
  9968. const result = endConditionCallback(hierarchy, instanceIndex);
  9969. if (defined$1(result)) {
  9970. return result;
  9971. }
  9972. const parentId = hierarchy.parentIds[instanceIndex];
  9973. hasParent = parentId !== instanceIndex;
  9974. instanceIndex = parentId;
  9975. }
  9976. throw new Error('traverseHierarchySingleParent');
  9977. }
  9978. function validateHierarchy(hierarchy) {
  9979. const classIds = hierarchy.classIds;
  9980. const instancesLength = classIds.length;
  9981. for (let i = 0; i < instancesLength; ++i) {
  9982. validateInstance(hierarchy, i, stack);
  9983. }
  9984. }
  9985. function validateInstance(hierarchy, instanceIndex, stack) {
  9986. const parentCounts = hierarchy.parentCounts;
  9987. const parentIds = hierarchy.parentIds;
  9988. const parentIndexes = hierarchy.parentIndexes;
  9989. const classIds = hierarchy.classIds;
  9990. const instancesLength = classIds.length;
  9991. if (!defined$1(parentIds)) {
  9992. return;
  9993. }
  9994. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  9995. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  9996. stack.push(instanceIndex);
  9997. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  9998. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  9999. for (let i = 0; i < parentCount; ++i) {
  10000. const parentId = parentIds[parentIndex + i];
  10001. if (parentId !== instanceIndex) {
  10002. validateInstance(hierarchy, parentId, stack);
  10003. }
  10004. }
  10005. stack.pop(instanceIndex);
  10006. }
  10007. function defined(x) {
  10008. return x !== undefined && x !== null;
  10009. }
  10010. const clone = (x, y) => x;
  10011. const IGNORED_PROPERTY_FIELDS = {
  10012. HIERARCHY: true,
  10013. extensions: true,
  10014. extras: true
  10015. };
  10016. class Tile3DBatchTableParser {
  10017. constructor(json, binary, featureCount, options = {}) {
  10018. var _this$json;
  10019. _defineProperty(this, "json", void 0);
  10020. _defineProperty(this, "binary", void 0);
  10021. _defineProperty(this, "featureCount", void 0);
  10022. _defineProperty(this, "_extensions", void 0);
  10023. _defineProperty(this, "_properties", void 0);
  10024. _defineProperty(this, "_binaryProperties", void 0);
  10025. _defineProperty(this, "_hierarchy", void 0);
  10026. assert$7(featureCount >= 0);
  10027. this.json = json || {};
  10028. this.binary = binary;
  10029. this.featureCount = featureCount;
  10030. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10031. this._properties = {};
  10032. for (const propertyName in this.json) {
  10033. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10034. this._properties[propertyName] = this.json[propertyName];
  10035. }
  10036. }
  10037. this._binaryProperties = this._initializeBinaryProperties();
  10038. if (options['3DTILES_batch_table_hierarchy']) {
  10039. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10040. }
  10041. }
  10042. getExtension(extensionName) {
  10043. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10044. }
  10045. memorySizeInBytes() {
  10046. return 0;
  10047. }
  10048. isClass(batchId, className) {
  10049. this._checkBatchId(batchId);
  10050. assert$7(typeof className === 'string', className);
  10051. if (this._hierarchy) {
  10052. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10053. const classId = hierarchy.classIds[instanceIndex];
  10054. const instanceClass = hierarchy.classes[classId];
  10055. return instanceClass.name === className;
  10056. });
  10057. return defined(result);
  10058. }
  10059. return false;
  10060. }
  10061. isExactClass(batchId, className) {
  10062. assert$7(typeof className === 'string', className);
  10063. return this.getExactClassName(batchId) === className;
  10064. }
  10065. getExactClassName(batchId) {
  10066. this._checkBatchId(batchId);
  10067. if (this._hierarchy) {
  10068. const classId = this._hierarchy.classIds[batchId];
  10069. const instanceClass = this._hierarchy.classes[classId];
  10070. return instanceClass.name;
  10071. }
  10072. return undefined;
  10073. }
  10074. hasProperty(batchId, name) {
  10075. this._checkBatchId(batchId);
  10076. assert$7(typeof name === 'string', name);
  10077. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10078. }
  10079. getPropertyNames(batchId, results) {
  10080. this._checkBatchId(batchId);
  10081. results = defined(results) ? results : [];
  10082. results.length = 0;
  10083. const propertyNames = Object.keys(this._properties);
  10084. results.push(...propertyNames);
  10085. if (this._hierarchy) {
  10086. this._getPropertyNamesInHierarchy(batchId, results);
  10087. }
  10088. return results;
  10089. }
  10090. getProperty(batchId, name) {
  10091. this._checkBatchId(batchId);
  10092. assert$7(typeof name === 'string', name);
  10093. if (this._binaryProperties) {
  10094. const binaryProperty = this._binaryProperties[name];
  10095. if (defined(binaryProperty)) {
  10096. return this._getBinaryProperty(binaryProperty, batchId);
  10097. }
  10098. }
  10099. const propertyValues = this._properties[name];
  10100. if (defined(propertyValues)) {
  10101. return clone(propertyValues[batchId]);
  10102. }
  10103. if (this._hierarchy) {
  10104. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10105. if (defined(hierarchyProperty)) {
  10106. return hierarchyProperty;
  10107. }
  10108. }
  10109. return undefined;
  10110. }
  10111. setProperty(batchId, name, value) {
  10112. const featureCount = this.featureCount;
  10113. this._checkBatchId(batchId);
  10114. assert$7(typeof name === 'string', name);
  10115. if (this._binaryProperties) {
  10116. const binaryProperty = this._binaryProperties[name];
  10117. if (binaryProperty) {
  10118. this._setBinaryProperty(binaryProperty, batchId, value);
  10119. return;
  10120. }
  10121. }
  10122. if (this._hierarchy) {
  10123. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10124. return;
  10125. }
  10126. }
  10127. let propertyValues = this._properties[name];
  10128. if (!defined(propertyValues)) {
  10129. this._properties[name] = new Array(featureCount);
  10130. propertyValues = this._properties[name];
  10131. }
  10132. propertyValues[batchId] = clone(value);
  10133. }
  10134. _checkBatchId(batchId) {
  10135. const valid = batchId >= 0 && batchId < this.featureCount;
  10136. if (!valid) {
  10137. throw new Error('batchId not in range [0, featureCount - 1].');
  10138. }
  10139. }
  10140. _getBinaryProperty(binaryProperty, index) {
  10141. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10142. }
  10143. _setBinaryProperty(binaryProperty, index, value) {
  10144. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10145. }
  10146. _initializeBinaryProperties() {
  10147. let binaryProperties = null;
  10148. for (const name in this._properties) {
  10149. const property = this._properties[name];
  10150. const binaryProperty = this._initializeBinaryProperty(name, property);
  10151. if (binaryProperty) {
  10152. binaryProperties = binaryProperties || {};
  10153. binaryProperties[name] = binaryProperty;
  10154. }
  10155. }
  10156. return binaryProperties;
  10157. }
  10158. _initializeBinaryProperty(name, property) {
  10159. if ('byteOffset' in property) {
  10160. const tile3DAccessor = property;
  10161. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10162. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10163. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10164. return {
  10165. typedArray: accessor.values,
  10166. componentCount: accessor.size,
  10167. unpack: accessor.unpacker,
  10168. pack: accessor.packer
  10169. };
  10170. }
  10171. return null;
  10172. }
  10173. _hasPropertyInHierarchy(batchId, name) {
  10174. if (!this._hierarchy) {
  10175. return false;
  10176. }
  10177. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10178. const classId = hierarchy.classIds[instanceIndex];
  10179. const instances = hierarchy.classes[classId].instances;
  10180. return defined(instances[name]);
  10181. });
  10182. return defined(result);
  10183. }
  10184. _getPropertyNamesInHierarchy(batchId, results) {
  10185. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10186. const classId = hierarchy.classIds[instanceIndex];
  10187. const instances = hierarchy.classes[classId].instances;
  10188. for (const name in instances) {
  10189. if (instances.hasOwnProperty(name)) {
  10190. if (results.indexOf(name) === -1) {
  10191. results.push(name);
  10192. }
  10193. }
  10194. }
  10195. });
  10196. }
  10197. _getHierarchyProperty(batchId, name) {
  10198. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10199. const classId = hierarchy.classIds[instanceIndex];
  10200. const instanceClass = hierarchy.classes[classId];
  10201. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10202. const propertyValues = instanceClass.instances[name];
  10203. if (defined(propertyValues)) {
  10204. if (defined(propertyValues.typedArray)) {
  10205. return this._getBinaryProperty(propertyValues, indexInClass);
  10206. }
  10207. return clone(propertyValues[indexInClass]);
  10208. }
  10209. return null;
  10210. });
  10211. }
  10212. _setHierarchyProperty(batchTable, batchId, name, value) {
  10213. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10214. const classId = hierarchy.classIds[instanceIndex];
  10215. const instanceClass = hierarchy.classes[classId];
  10216. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10217. const propertyValues = instanceClass.instances[name];
  10218. if (defined(propertyValues)) {
  10219. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10220. if (defined(propertyValues.typedArray)) {
  10221. this._setBinaryProperty(propertyValues, indexInClass, value);
  10222. } else {
  10223. propertyValues[indexInClass] = clone(value);
  10224. }
  10225. return true;
  10226. }
  10227. return false;
  10228. });
  10229. return defined(result);
  10230. }
  10231. }
  10232. const SIZEOF_UINT32$1 = 4;
  10233. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10234. const view = new DataView(arrayBuffer);
  10235. tile.magic = view.getUint32(byteOffset, true);
  10236. byteOffset += SIZEOF_UINT32$1;
  10237. tile.version = view.getUint32(byteOffset, true);
  10238. byteOffset += SIZEOF_UINT32$1;
  10239. tile.byteLength = view.getUint32(byteOffset, true);
  10240. byteOffset += SIZEOF_UINT32$1;
  10241. if (tile.version !== 1) {
  10242. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10243. }
  10244. return byteOffset;
  10245. }
  10246. const SIZEOF_UINT32 = 4;
  10247. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10248. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10249. const view = new DataView(arrayBuffer);
  10250. let batchLength;
  10251. tile.header = tile.header || {};
  10252. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10253. byteOffset += SIZEOF_UINT32;
  10254. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10255. byteOffset += SIZEOF_UINT32;
  10256. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10257. byteOffset += SIZEOF_UINT32;
  10258. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10259. byteOffset += SIZEOF_UINT32;
  10260. if (batchTableJsonByteLength >= 570425344) {
  10261. byteOffset -= SIZEOF_UINT32 * 2;
  10262. batchLength = featureTableJsonByteLength;
  10263. batchTableJsonByteLength = featureTableBinaryByteLength;
  10264. batchTableBinaryByteLength = 0;
  10265. featureTableJsonByteLength = 0;
  10266. featureTableBinaryByteLength = 0;
  10267. console.warn(DEPRECATION_WARNING);
  10268. } else if (batchTableBinaryByteLength >= 570425344) {
  10269. byteOffset -= SIZEOF_UINT32;
  10270. batchLength = batchTableJsonByteLength;
  10271. batchTableJsonByteLength = featureTableJsonByteLength;
  10272. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10273. featureTableJsonByteLength = 0;
  10274. featureTableBinaryByteLength = 0;
  10275. console.warn(DEPRECATION_WARNING);
  10276. }
  10277. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10278. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10279. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10280. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10281. tile.header.batchLength = batchLength;
  10282. return byteOffset;
  10283. }
  10284. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10285. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10286. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10287. return byteOffset;
  10288. }
  10289. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10290. const {
  10291. featureTableJsonByteLength,
  10292. featureTableBinaryByteLength,
  10293. batchLength
  10294. } = tile.header;
  10295. tile.featureTableJson = {
  10296. BATCH_LENGTH: batchLength || 0
  10297. };
  10298. if (featureTableJsonByteLength > 0) {
  10299. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10300. tile.featureTableJson = JSON.parse(featureTableString);
  10301. }
  10302. byteOffset += featureTableJsonByteLength;
  10303. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10304. byteOffset += featureTableBinaryByteLength;
  10305. return byteOffset;
  10306. }
  10307. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10308. const {
  10309. batchTableJsonByteLength,
  10310. batchTableBinaryByteLength
  10311. } = tile.header;
  10312. if (batchTableJsonByteLength > 0) {
  10313. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10314. tile.batchTableJson = JSON.parse(batchTableString);
  10315. byteOffset += batchTableJsonByteLength;
  10316. if (batchTableBinaryByteLength > 0) {
  10317. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10318. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10319. byteOffset += batchTableBinaryByteLength;
  10320. }
  10321. }
  10322. return byteOffset;
  10323. }
  10324. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10325. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10326. return null;
  10327. }
  10328. const {
  10329. batchIds,
  10330. isRGB565,
  10331. pointCount
  10332. } = tile;
  10333. if (batchIds && batchTable) {
  10334. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10335. for (let i = 0; i < pointCount; i++) {
  10336. const batchId = batchIds[i];
  10337. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10338. const color = dimensions.map(d => d * 255);
  10339. colorArray[i * 3] = color[0];
  10340. colorArray[i * 3 + 1] = color[1];
  10341. colorArray[i * 3 + 2] = color[2];
  10342. }
  10343. return {
  10344. type: GL$1.UNSIGNED_BYTE,
  10345. value: colorArray,
  10346. size: 3,
  10347. normalized: true
  10348. };
  10349. }
  10350. if (isRGB565) {
  10351. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10352. for (let i = 0; i < pointCount; i++) {
  10353. const color = decodeRGB565(colors[i]);
  10354. colorArray[i * 3] = color[0];
  10355. colorArray[i * 3 + 1] = color[1];
  10356. colorArray[i * 3 + 2] = color[2];
  10357. }
  10358. return {
  10359. type: GL$1.UNSIGNED_BYTE,
  10360. value: colorArray,
  10361. size: 3,
  10362. normalized: true
  10363. };
  10364. }
  10365. if (colors && colors.length === pointCount * 3) {
  10366. return {
  10367. type: GL$1.UNSIGNED_BYTE,
  10368. value: colors,
  10369. size: 3,
  10370. normalized: true
  10371. };
  10372. }
  10373. return {
  10374. type: GL$1.UNSIGNED_BYTE,
  10375. value: colors,
  10376. size: 4,
  10377. normalized: true
  10378. };
  10379. }
  10380. const scratchNormal = new Vector3();
  10381. function normalize3DTileNormalAttribute(tile, normals) {
  10382. if (!normals) {
  10383. return null;
  10384. }
  10385. if (tile.isOctEncoded16P) {
  10386. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10387. for (let i = 0; i < tile.pointsLength; i++) {
  10388. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10389. scratchNormal.toArray(decodedArray, i * 3);
  10390. }
  10391. return {
  10392. type: GL$1.FLOAT,
  10393. size: 2,
  10394. value: decodedArray
  10395. };
  10396. }
  10397. return {
  10398. type: GL$1.FLOAT,
  10399. size: 2,
  10400. value: normals
  10401. };
  10402. }
  10403. function normalize3DTilePositionAttribute(tile, positions, options) {
  10404. if (!tile.isQuantized) {
  10405. return positions;
  10406. }
  10407. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10408. tile.isQuantized = false;
  10409. return decodeQuantizedPositions(tile, positions);
  10410. }
  10411. return {
  10412. type: GL$1.UNSIGNED_SHORT,
  10413. value: positions,
  10414. size: 3,
  10415. normalized: true
  10416. };
  10417. }
  10418. function decodeQuantizedPositions(tile, positions) {
  10419. const scratchPosition = new Vector3();
  10420. const decodedArray = new Float32Array(tile.pointCount * 3);
  10421. for (let i = 0; i < tile.pointCount; i++) {
  10422. 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);
  10423. }
  10424. return decodedArray;
  10425. }
  10426. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10427. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10428. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10429. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10430. initializeTile(tile);
  10431. const {
  10432. featureTable,
  10433. batchTable
  10434. } = parsePointCloudTables(tile);
  10435. await parseDraco(tile, featureTable, batchTable, options, context);
  10436. parsePositions(tile, featureTable, options);
  10437. parseColors(tile, featureTable, batchTable);
  10438. parseNormals(tile, featureTable);
  10439. return byteOffset;
  10440. }
  10441. function initializeTile(tile) {
  10442. tile.attributes = {
  10443. positions: null,
  10444. colors: null,
  10445. normals: null,
  10446. batchIds: null
  10447. };
  10448. tile.isQuantized = false;
  10449. tile.isTranslucent = false;
  10450. tile.isRGB565 = false;
  10451. tile.isOctEncoded16P = false;
  10452. }
  10453. function parsePointCloudTables(tile) {
  10454. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10455. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10456. if (!Number.isFinite(pointsLength)) {
  10457. throw new Error('POINTS_LENGTH must be defined');
  10458. }
  10459. featureTable.featuresLength = pointsLength;
  10460. tile.featuresLength = pointsLength;
  10461. tile.pointsLength = pointsLength;
  10462. tile.pointCount = pointsLength;
  10463. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10464. const batchTable = parseBatchIds(tile, featureTable);
  10465. return {
  10466. featureTable,
  10467. batchTable
  10468. };
  10469. }
  10470. function parsePositions(tile, featureTable, options) {
  10471. if (!tile.attributes.positions) {
  10472. if (featureTable.hasProperty('POSITION')) {
  10473. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10474. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10475. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10476. tile.isQuantized = true;
  10477. tile.quantizedRange = (1 << 16) - 1;
  10478. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10479. if (!tile.quantizedVolumeScale) {
  10480. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10481. }
  10482. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10483. if (!tile.quantizedVolumeOffset) {
  10484. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10485. }
  10486. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10487. }
  10488. }
  10489. if (!tile.attributes.positions) {
  10490. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10491. }
  10492. }
  10493. function parseColors(tile, featureTable, batchTable) {
  10494. if (!tile.attributes.colors) {
  10495. let colors = null;
  10496. if (featureTable.hasProperty('RGBA')) {
  10497. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10498. tile.isTranslucent = true;
  10499. } else if (featureTable.hasProperty('RGB')) {
  10500. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10501. } else if (featureTable.hasProperty('RGB565')) {
  10502. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10503. tile.isRGB565 = true;
  10504. }
  10505. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10506. }
  10507. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10508. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10509. }
  10510. }
  10511. function parseNormals(tile, featureTable) {
  10512. if (!tile.attributes.normals) {
  10513. let normals = null;
  10514. if (featureTable.hasProperty('NORMAL')) {
  10515. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10516. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10517. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10518. tile.isOctEncoded16P = true;
  10519. }
  10520. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10521. }
  10522. }
  10523. function parseBatchIds(tile, featureTable) {
  10524. let batchTable = null;
  10525. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10526. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10527. if (tile.batchIds) {
  10528. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10529. if (!batchFeatureLength) {
  10530. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10531. }
  10532. const {
  10533. batchTableJson,
  10534. batchTableBinary
  10535. } = tile;
  10536. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10537. }
  10538. }
  10539. return batchTable;
  10540. }
  10541. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10542. let dracoBuffer;
  10543. let dracoFeatureTableProperties;
  10544. let dracoBatchTableProperties;
  10545. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10546. if (batchTableDraco) {
  10547. dracoBatchTableProperties = batchTableDraco.properties;
  10548. }
  10549. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10550. if (featureTableDraco) {
  10551. dracoFeatureTableProperties = featureTableDraco.properties;
  10552. const dracoByteOffset = featureTableDraco.byteOffset;
  10553. const dracoByteLength = featureTableDraco.byteLength;
  10554. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10555. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10556. }
  10557. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10558. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10559. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10560. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10561. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10562. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10563. }
  10564. if (!dracoBuffer) {
  10565. return true;
  10566. }
  10567. const dracoData = {
  10568. buffer: dracoBuffer,
  10569. properties: { ...dracoFeatureTableProperties,
  10570. ...dracoBatchTableProperties
  10571. },
  10572. featureTableProperties: dracoFeatureTableProperties,
  10573. batchTableProperties: dracoBatchTableProperties,
  10574. dequantizeInShader: false
  10575. };
  10576. return await loadDraco(tile, dracoData, options, context);
  10577. }
  10578. async function loadDraco(tile, dracoData, options, context) {
  10579. const {
  10580. parse
  10581. } = context;
  10582. const dracoOptions = { ...options,
  10583. draco: { ...options.draco,
  10584. extraAttributes: dracoData.batchTableProperties || {}
  10585. }
  10586. };
  10587. delete dracoOptions['3d-tiles'];
  10588. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10589. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10590. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10591. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10592. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10593. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10594. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10595. if (isQuantizedDraco) {
  10596. const quantization = data.POSITION.data.quantization;
  10597. const range = quantization.range;
  10598. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10599. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10600. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10601. tile.isQuantizedDraco = true;
  10602. }
  10603. if (isOctEncodedDraco) {
  10604. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10605. tile.isOctEncodedDraco = true;
  10606. }
  10607. const batchTableAttributes = {};
  10608. if (dracoData.batchTableProperties) {
  10609. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10610. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10611. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10612. }
  10613. }
  10614. }
  10615. tile.attributes = {
  10616. positions: decodedPositions,
  10617. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10618. normals: decodedNormals,
  10619. batchIds: decodedBatchIds,
  10620. ...batchTableAttributes
  10621. };
  10622. }
  10623. const VERSION$3 = "3.1.4" ;
  10624. const VERSION$2 = "3.1.4" ;
  10625. const VERSION$1 = "3.1.4" ;
  10626. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10627. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10628. let loadBasisTranscoderPromise;
  10629. async function loadBasisTrascoderModule(options) {
  10630. const modules = options.modules || {};
  10631. if (modules.basis) {
  10632. return modules.basis;
  10633. }
  10634. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10635. return await loadBasisTranscoderPromise;
  10636. }
  10637. async function loadBasisTrascoder(options) {
  10638. let BASIS = null;
  10639. let wasmBinary = null;
  10640. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10641. BASIS = BASIS || globalThis.BASIS;
  10642. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10643. }
  10644. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10645. const options = {};
  10646. if (wasmBinary) {
  10647. options.wasmBinary = wasmBinary;
  10648. }
  10649. return new Promise(resolve => {
  10650. BasisModule(options).then(module => {
  10651. const {
  10652. BasisFile,
  10653. initializeBasis
  10654. } = module;
  10655. initializeBasis();
  10656. resolve({
  10657. BasisFile
  10658. });
  10659. });
  10660. });
  10661. }
  10662. let loadBasisEncoderPromise;
  10663. async function loadBasisEncoderModule(options) {
  10664. const modules = options.modules || {};
  10665. if (modules.basisEncoder) {
  10666. return modules.basisEncoder;
  10667. }
  10668. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10669. return await loadBasisEncoderPromise;
  10670. }
  10671. async function loadBasisEncoder(options) {
  10672. let BASIS_ENCODER = null;
  10673. let wasmBinary = null;
  10674. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10675. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10676. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10677. }
  10678. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10679. const options = {};
  10680. if (wasmBinary) {
  10681. options.wasmBinary = wasmBinary;
  10682. }
  10683. return new Promise(resolve => {
  10684. BasisEncoderModule(options).then(module => {
  10685. const {
  10686. BasisFile,
  10687. KTX2File,
  10688. initializeBasis,
  10689. BasisEncoder
  10690. } = module;
  10691. initializeBasis();
  10692. resolve({
  10693. BasisFile,
  10694. KTX2File,
  10695. BasisEncoder
  10696. });
  10697. });
  10698. });
  10699. }
  10700. const GL_EXTENSIONS_CONSTANTS = {
  10701. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10702. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10703. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10704. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10705. COMPRESSED_R11_EAC: 0x9270,
  10706. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10707. COMPRESSED_RG11_EAC: 0x9272,
  10708. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10709. COMPRESSED_RGB8_ETC2: 0x9274,
  10710. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10711. COMPRESSED_SRGB8_ETC2: 0x9276,
  10712. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10713. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10714. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10715. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10716. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10717. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10718. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10719. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10720. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10721. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10722. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10723. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10724. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10725. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10726. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10727. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10728. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10729. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10730. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10731. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10732. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10733. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10734. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10735. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10736. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10737. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10738. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10739. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10740. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10741. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10742. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10743. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10744. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10745. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10746. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10747. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10748. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10749. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10750. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10751. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10752. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10753. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10754. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10755. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10756. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10757. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10758. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10759. };
  10760. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10761. const WEBGL_EXTENSIONS = {
  10762. WEBGL_compressed_texture_s3tc: 'dxt',
  10763. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10764. WEBGL_compressed_texture_etc1: 'etc1',
  10765. WEBGL_compressed_texture_etc: 'etc2',
  10766. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10767. WEBGL_compressed_texture_atc: 'atc',
  10768. WEBGL_compressed_texture_astc: 'astc',
  10769. EXT_texture_compression_rgtc: 'rgtc'
  10770. };
  10771. let formats = null;
  10772. function getSupportedGPUTextureFormats(gl) {
  10773. if (!formats) {
  10774. gl = gl || getWebGLContext() || undefined;
  10775. formats = new Set();
  10776. for (const prefix of BROWSER_PREFIXES) {
  10777. for (const extension in WEBGL_EXTENSIONS) {
  10778. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10779. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10780. formats.add(gpuTextureFormat);
  10781. }
  10782. }
  10783. }
  10784. }
  10785. return formats;
  10786. }
  10787. function getWebGLContext() {
  10788. try {
  10789. const canvas = document.createElement('canvas');
  10790. return canvas.getContext('webgl');
  10791. } catch (error) {
  10792. return null;
  10793. }
  10794. }
  10795. 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={}));
  10796. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10797. function isKTX(data) {
  10798. const id = new Uint8Array(data);
  10799. 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];
  10800. return !notKTX;
  10801. }
  10802. const OutputFormat = {
  10803. etc1: {
  10804. basisFormat: 0,
  10805. compressed: true,
  10806. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10807. },
  10808. etc2: {
  10809. basisFormat: 1,
  10810. compressed: true
  10811. },
  10812. bc1: {
  10813. basisFormat: 2,
  10814. compressed: true,
  10815. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10816. },
  10817. bc3: {
  10818. basisFormat: 3,
  10819. compressed: true,
  10820. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10821. },
  10822. bc4: {
  10823. basisFormat: 4,
  10824. compressed: true
  10825. },
  10826. bc5: {
  10827. basisFormat: 5,
  10828. compressed: true
  10829. },
  10830. 'bc7-m6-opaque-only': {
  10831. basisFormat: 6,
  10832. compressed: true
  10833. },
  10834. 'bc7-m5': {
  10835. basisFormat: 7,
  10836. compressed: true
  10837. },
  10838. 'pvrtc1-4-rgb': {
  10839. basisFormat: 8,
  10840. compressed: true,
  10841. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10842. },
  10843. 'pvrtc1-4-rgba': {
  10844. basisFormat: 9,
  10845. compressed: true,
  10846. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10847. },
  10848. 'astc-4x4': {
  10849. basisFormat: 10,
  10850. compressed: true,
  10851. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10852. },
  10853. 'atc-rgb': {
  10854. basisFormat: 11,
  10855. compressed: true
  10856. },
  10857. 'atc-rgba-interpolated-alpha': {
  10858. basisFormat: 12,
  10859. compressed: true
  10860. },
  10861. rgba32: {
  10862. basisFormat: 13,
  10863. compressed: false
  10864. },
  10865. rgb565: {
  10866. basisFormat: 14,
  10867. compressed: false
  10868. },
  10869. bgr565: {
  10870. basisFormat: 15,
  10871. compressed: false
  10872. },
  10873. rgba4444: {
  10874. basisFormat: 16,
  10875. compressed: false
  10876. }
  10877. };
  10878. async function parseBasis(data, options) {
  10879. if (options.basis.containerFormat === 'auto') {
  10880. if (isKTX(data)) {
  10881. const fileConstructors = await loadBasisEncoderModule(options);
  10882. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10883. }
  10884. const {
  10885. BasisFile
  10886. } = await loadBasisTrascoderModule(options);
  10887. return parseBasisFile(BasisFile, data, options);
  10888. }
  10889. switch (options.basis.module) {
  10890. case 'encoder':
  10891. const fileConstructors = await loadBasisEncoderModule(options);
  10892. switch (options.basis.containerFormat) {
  10893. case 'ktx2':
  10894. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10895. case 'basis':
  10896. default:
  10897. return parseBasisFile(fileConstructors.BasisFile, data, options);
  10898. }
  10899. case 'transcoder':
  10900. default:
  10901. const {
  10902. BasisFile
  10903. } = await loadBasisTrascoderModule(options);
  10904. return parseBasisFile(BasisFile, data, options);
  10905. }
  10906. }
  10907. function parseBasisFile(BasisFile, data, options) {
  10908. const basisFile = new BasisFile(new Uint8Array(data));
  10909. try {
  10910. if (!basisFile.startTranscoding()) {
  10911. return null;
  10912. }
  10913. const imageCount = basisFile.getNumImages();
  10914. const images = [];
  10915. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  10916. const levelsCount = basisFile.getNumLevels(imageIndex);
  10917. const levels = [];
  10918. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10919. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  10920. }
  10921. images.push(levels);
  10922. }
  10923. return images;
  10924. } finally {
  10925. basisFile.close();
  10926. basisFile.delete();
  10927. }
  10928. }
  10929. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  10930. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  10931. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  10932. const hasAlpha = basisFile.getHasAlpha();
  10933. const {
  10934. compressed,
  10935. format,
  10936. basisFormat
  10937. } = getBasisOptions(options, hasAlpha);
  10938. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  10939. const decodedData = new Uint8Array(decodedSize);
  10940. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  10941. return null;
  10942. }
  10943. return {
  10944. width,
  10945. height,
  10946. data: decodedData,
  10947. compressed,
  10948. hasAlpha,
  10949. format
  10950. };
  10951. }
  10952. function parseKTX2File(KTX2File, data, options) {
  10953. const ktx2File = new KTX2File(new Uint8Array(data));
  10954. try {
  10955. if (!ktx2File.startTranscoding()) {
  10956. return null;
  10957. }
  10958. const levelsCount = ktx2File.getLevels();
  10959. const levels = [];
  10960. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  10961. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  10962. break;
  10963. }
  10964. return levels;
  10965. } finally {
  10966. ktx2File.close();
  10967. ktx2File.delete();
  10968. }
  10969. }
  10970. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  10971. const {
  10972. alphaFlag,
  10973. height,
  10974. width
  10975. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  10976. const {
  10977. compressed,
  10978. format,
  10979. basisFormat
  10980. } = getBasisOptions(options, alphaFlag);
  10981. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  10982. const decodedData = new Uint8Array(decodedSize);
  10983. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  10984. return null;
  10985. }
  10986. return {
  10987. width,
  10988. height,
  10989. data: decodedData,
  10990. compressed,
  10991. alphaFlag,
  10992. format
  10993. };
  10994. }
  10995. function getBasisOptions(options, hasAlpha) {
  10996. let format = options && options.basis && options.basis.format;
  10997. if (format === 'auto') {
  10998. format = selectSupportedBasisFormat();
  10999. }
  11000. if (typeof format === 'object') {
  11001. format = hasAlpha ? format.alpha : format.noAlpha;
  11002. }
  11003. format = format.toLowerCase();
  11004. return OutputFormat[format];
  11005. }
  11006. function selectSupportedBasisFormat() {
  11007. const supportedFormats = getSupportedGPUTextureFormats();
  11008. if (supportedFormats.has('astc')) {
  11009. return 'astc-4x4';
  11010. } else if (supportedFormats.has('dxt')) {
  11011. return {
  11012. alpha: 'bc3',
  11013. noAlpha: 'bc1'
  11014. };
  11015. } else if (supportedFormats.has('pvrtc')) {
  11016. return {
  11017. alpha: 'pvrtc1-4-rgba',
  11018. noAlpha: 'pvrtc1-4-rgb'
  11019. };
  11020. } else if (supportedFormats.has('etc1')) {
  11021. return 'etc1';
  11022. } else if (supportedFormats.has('etc2')) {
  11023. return 'etc2';
  11024. }
  11025. return 'rgb565';
  11026. }
  11027. const BasisWorkerLoader = {
  11028. name: 'Basis',
  11029. id: 'basis',
  11030. module: 'textures',
  11031. version: VERSION$2,
  11032. worker: true,
  11033. extensions: ['basis', 'ktx2'],
  11034. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11035. tests: ['sB'],
  11036. binary: true,
  11037. options: {
  11038. basis: {
  11039. format: 'auto',
  11040. libraryPath: 'libs/',
  11041. containerFormat: 'auto',
  11042. module: 'transcoder'
  11043. }
  11044. }
  11045. };
  11046. const BasisLoader = { ...BasisWorkerLoader,
  11047. parse: parseBasis
  11048. };
  11049. const VERSION = "3.1.4" ;
  11050. const {
  11051. _parseImageNode
  11052. } = globalThis;
  11053. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11054. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11055. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11056. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11057. function isImageTypeSupported(type) {
  11058. switch (type) {
  11059. case 'auto':
  11060. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11061. case 'imagebitmap':
  11062. return IMAGE_BITMAP_SUPPORTED;
  11063. case 'image':
  11064. return IMAGE_SUPPORTED;
  11065. case 'data':
  11066. return DATA_SUPPORTED;
  11067. default:
  11068. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11069. }
  11070. }
  11071. function getDefaultImageType() {
  11072. if (IMAGE_BITMAP_SUPPORTED) {
  11073. return 'imagebitmap';
  11074. }
  11075. if (IMAGE_SUPPORTED) {
  11076. return 'image';
  11077. }
  11078. if (DATA_SUPPORTED) {
  11079. return 'data';
  11080. }
  11081. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11082. }
  11083. function getImageType(image) {
  11084. const format = getImageTypeOrNull(image);
  11085. if (!format) {
  11086. throw new Error('Not an image');
  11087. }
  11088. return format;
  11089. }
  11090. function getImageData(image) {
  11091. switch (getImageType(image)) {
  11092. case 'data':
  11093. return image;
  11094. case 'image':
  11095. case 'imagebitmap':
  11096. const canvas = document.createElement('canvas');
  11097. const context = canvas.getContext('2d');
  11098. if (!context) {
  11099. throw new Error('getImageData');
  11100. }
  11101. canvas.width = image.width;
  11102. canvas.height = image.height;
  11103. context.drawImage(image, 0, 0);
  11104. return context.getImageData(0, 0, image.width, image.height);
  11105. default:
  11106. throw new Error('getImageData');
  11107. }
  11108. }
  11109. function getImageTypeOrNull(image) {
  11110. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11111. return 'imagebitmap';
  11112. }
  11113. if (typeof Image !== 'undefined' && image instanceof Image) {
  11114. return 'image';
  11115. }
  11116. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11117. return 'data';
  11118. }
  11119. return null;
  11120. }
  11121. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11122. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11123. function isSVG(url) {
  11124. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11125. }
  11126. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11127. if (isSVG(url)) {
  11128. const textDecoder = new TextDecoder();
  11129. let xmlText = textDecoder.decode(arrayBuffer);
  11130. try {
  11131. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11132. xmlText = unescape(encodeURIComponent(xmlText));
  11133. }
  11134. } catch (error) {
  11135. throw new Error(error.message);
  11136. }
  11137. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11138. return src;
  11139. }
  11140. return getBlob(arrayBuffer, url);
  11141. }
  11142. function getBlob(arrayBuffer, url) {
  11143. if (isSVG(url)) {
  11144. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11145. }
  11146. return new Blob([new Uint8Array(arrayBuffer)]);
  11147. }
  11148. async function parseToImage(arrayBuffer, options, url) {
  11149. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11150. const URL = self.URL || self.webkitURL;
  11151. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11152. try {
  11153. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11154. } finally {
  11155. if (objectUrl) {
  11156. URL.revokeObjectURL(objectUrl);
  11157. }
  11158. }
  11159. }
  11160. async function loadToImage(url, options) {
  11161. const image = new Image();
  11162. image.src = url;
  11163. if (options.image && options.image.decode && image.decode) {
  11164. await image.decode();
  11165. return image;
  11166. }
  11167. return await new Promise((resolve, reject) => {
  11168. try {
  11169. image.onload = () => resolve(image);
  11170. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11171. } catch (error) {
  11172. reject(error);
  11173. }
  11174. });
  11175. }
  11176. const EMPTY_OBJECT = {};
  11177. let imagebitmapOptionsSupported = true;
  11178. async function parseToImageBitmap(arrayBuffer, options, url) {
  11179. let blob;
  11180. if (isSVG(url)) {
  11181. const image = await parseToImage(arrayBuffer, options, url);
  11182. blob = image;
  11183. } else {
  11184. blob = getBlob(arrayBuffer, url);
  11185. }
  11186. const imagebitmapOptions = options && options.imagebitmap;
  11187. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11188. }
  11189. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11190. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11191. imagebitmapOptions = null;
  11192. }
  11193. if (imagebitmapOptions) {
  11194. try {
  11195. return await createImageBitmap(blob, imagebitmapOptions);
  11196. } catch (error) {
  11197. console.warn(error);
  11198. imagebitmapOptionsSupported = false;
  11199. }
  11200. }
  11201. return await createImageBitmap(blob);
  11202. }
  11203. function isEmptyObject(object) {
  11204. for (const key in object || EMPTY_OBJECT) {
  11205. return false;
  11206. }
  11207. return true;
  11208. }
  11209. const BIG_ENDIAN = false;
  11210. const LITTLE_ENDIAN = true;
  11211. function getBinaryImageMetadata(binaryData) {
  11212. const dataView = toDataView(binaryData);
  11213. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11214. }
  11215. function getPngMetadata(binaryData) {
  11216. const dataView = toDataView(binaryData);
  11217. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11218. if (!isPng) {
  11219. return null;
  11220. }
  11221. return {
  11222. mimeType: 'image/png',
  11223. width: dataView.getUint32(16, BIG_ENDIAN),
  11224. height: dataView.getUint32(20, BIG_ENDIAN)
  11225. };
  11226. }
  11227. function getGifMetadata(binaryData) {
  11228. const dataView = toDataView(binaryData);
  11229. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11230. if (!isGif) {
  11231. return null;
  11232. }
  11233. return {
  11234. mimeType: 'image/gif',
  11235. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11236. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11237. };
  11238. }
  11239. function getBmpMetadata(binaryData) {
  11240. const dataView = toDataView(binaryData);
  11241. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11242. if (!isBmp) {
  11243. return null;
  11244. }
  11245. return {
  11246. mimeType: 'image/bmp',
  11247. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11248. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11249. };
  11250. }
  11251. function getJpegMetadata(binaryData) {
  11252. const dataView = toDataView(binaryData);
  11253. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11254. if (!isJpeg) {
  11255. return null;
  11256. }
  11257. const {
  11258. tableMarkers,
  11259. sofMarkers
  11260. } = getJpegMarkers();
  11261. let i = 2;
  11262. while (i + 9 < dataView.byteLength) {
  11263. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11264. if (sofMarkers.has(marker)) {
  11265. return {
  11266. mimeType: 'image/jpeg',
  11267. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11268. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11269. };
  11270. }
  11271. if (!tableMarkers.has(marker)) {
  11272. return null;
  11273. }
  11274. i += 2;
  11275. i += dataView.getUint16(i, BIG_ENDIAN);
  11276. }
  11277. return null;
  11278. }
  11279. function getJpegMarkers() {
  11280. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11281. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11282. tableMarkers.add(i);
  11283. }
  11284. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11285. return {
  11286. tableMarkers,
  11287. sofMarkers
  11288. };
  11289. }
  11290. function toDataView(data) {
  11291. if (data instanceof DataView) {
  11292. return data;
  11293. }
  11294. if (ArrayBuffer.isView(data)) {
  11295. return new DataView(data.buffer);
  11296. }
  11297. if (data instanceof ArrayBuffer) {
  11298. return new DataView(data);
  11299. }
  11300. throw new Error('toDataView');
  11301. }
  11302. async function parseToNodeImage(arrayBuffer, options) {
  11303. const {
  11304. mimeType
  11305. } = getBinaryImageMetadata(arrayBuffer) || {};
  11306. const _parseImageNode = globalThis._parseImageNode;
  11307. assert$7(_parseImageNode);
  11308. return await _parseImageNode(arrayBuffer, mimeType);
  11309. }
  11310. async function parseImage(arrayBuffer, options, context) {
  11311. options = options || {};
  11312. const imageOptions = options.image || {};
  11313. const imageType = imageOptions.type || 'auto';
  11314. const {
  11315. url
  11316. } = context || {};
  11317. const loadType = getLoadableImageType(imageType);
  11318. let image;
  11319. switch (loadType) {
  11320. case 'imagebitmap':
  11321. image = await parseToImageBitmap(arrayBuffer, options, url);
  11322. break;
  11323. case 'image':
  11324. image = await parseToImage(arrayBuffer, options, url);
  11325. break;
  11326. case 'data':
  11327. image = await parseToNodeImage(arrayBuffer);
  11328. break;
  11329. default:
  11330. assert$7(false);
  11331. }
  11332. if (imageType === 'data') {
  11333. image = getImageData(image);
  11334. }
  11335. return image;
  11336. }
  11337. function getLoadableImageType(type) {
  11338. switch (type) {
  11339. case 'auto':
  11340. case 'data':
  11341. return getDefaultImageType();
  11342. default:
  11343. isImageTypeSupported(type);
  11344. return type;
  11345. }
  11346. }
  11347. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11348. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11349. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11350. image: {
  11351. type: 'auto',
  11352. decode: true
  11353. }
  11354. };
  11355. const ImageLoader = {
  11356. id: 'image',
  11357. module: 'images',
  11358. name: 'Images',
  11359. version: VERSION,
  11360. mimeTypes: MIME_TYPES,
  11361. extensions: EXTENSIONS$1,
  11362. parse: parseImage,
  11363. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11364. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11365. };
  11366. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11367. const mimeTypeSupported = {};
  11368. function _isImageFormatSupported(mimeType) {
  11369. if (mimeTypeSupported[mimeType] === undefined) {
  11370. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11371. }
  11372. return mimeTypeSupported[mimeType];
  11373. }
  11374. function checkFormatSupport(mimeType) {
  11375. switch (mimeType) {
  11376. case 'image/webp':
  11377. return checkWebPSupport();
  11378. case 'image/svg':
  11379. return isBrowser$2;
  11380. default:
  11381. if (!isBrowser$2) {
  11382. const {
  11383. _parseImageNode
  11384. } = globalThis;
  11385. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11386. }
  11387. return true;
  11388. }
  11389. }
  11390. function checkWebPSupport() {
  11391. if (!isBrowser$2) {
  11392. return false;
  11393. }
  11394. try {
  11395. const element = document.createElement('canvas');
  11396. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11397. } catch {
  11398. return false;
  11399. }
  11400. }
  11401. function assert$1(condition, message) {
  11402. if (!condition) {
  11403. throw new Error(message || 'assert failed: gltf');
  11404. }
  11405. }
  11406. function resolveUrl(url, options) {
  11407. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11408. if (absolute) {
  11409. return url;
  11410. }
  11411. const baseUrl = options.baseUri || options.uri;
  11412. if (!baseUrl) {
  11413. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11414. }
  11415. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11416. }
  11417. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11418. const bufferView = json.bufferViews[bufferViewIndex];
  11419. assert$1(bufferView);
  11420. const bufferIndex = bufferView.buffer;
  11421. const binChunk = buffers[bufferIndex];
  11422. assert$1(binChunk);
  11423. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11424. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11425. }
  11426. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11427. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11428. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11429. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11430. SCALAR: 1,
  11431. VEC2: 2,
  11432. VEC3: 3,
  11433. VEC4: 4,
  11434. MAT2: 4,
  11435. MAT3: 9,
  11436. MAT4: 16
  11437. };
  11438. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11439. 5120: 1,
  11440. 5121: 1,
  11441. 5122: 2,
  11442. 5123: 2,
  11443. 5125: 4,
  11444. 5126: 4
  11445. };
  11446. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11447. 5120: Int8Array,
  11448. 5121: Uint8Array,
  11449. 5122: Int16Array,
  11450. 5123: Uint16Array,
  11451. 5125: Uint32Array,
  11452. 5126: Float32Array
  11453. };
  11454. function getAccessorTypeFromSize(size) {
  11455. const type = TYPES[size - 1];
  11456. return type || TYPES[0];
  11457. }
  11458. function getComponentTypeFromArray(typedArray) {
  11459. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11460. if (!componentType) {
  11461. throw new Error('Illegal typed array');
  11462. }
  11463. return componentType;
  11464. }
  11465. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11466. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11467. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11468. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11469. const length = accessor.count * components;
  11470. const byteLength = accessor.count * components * bytesPerComponent;
  11471. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11472. return {
  11473. ArrayType,
  11474. length,
  11475. byteLength
  11476. };
  11477. }
  11478. const DEFAULT_GLTF_JSON = {
  11479. asset: {
  11480. version: '2.0',
  11481. generator: 'loaders.gl'
  11482. },
  11483. buffers: []
  11484. };
  11485. class GLTFScenegraph {
  11486. constructor(gltf) {
  11487. _defineProperty(this, "gltf", void 0);
  11488. _defineProperty(this, "sourceBuffers", void 0);
  11489. _defineProperty(this, "byteLength", void 0);
  11490. this.gltf = gltf || {
  11491. json: { ...DEFAULT_GLTF_JSON
  11492. },
  11493. buffers: []
  11494. };
  11495. this.sourceBuffers = [];
  11496. this.byteLength = 0;
  11497. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11498. this.byteLength = this.gltf.buffers[0].byteLength;
  11499. this.sourceBuffers = [this.gltf.buffers[0]];
  11500. }
  11501. }
  11502. get json() {
  11503. return this.gltf.json;
  11504. }
  11505. getApplicationData(key) {
  11506. const data = this.json[key];
  11507. return data;
  11508. }
  11509. getExtraData(key) {
  11510. const extras = this.json.extras || {};
  11511. return extras[key];
  11512. }
  11513. getExtension(extensionName) {
  11514. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11515. const extensions = this.json.extensions || {};
  11516. return isExtension ? extensions[extensionName] || true : null;
  11517. }
  11518. getRequiredExtension(extensionName) {
  11519. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11520. return isRequired ? this.getExtension(extensionName) : null;
  11521. }
  11522. getRequiredExtensions() {
  11523. return this.json.extensionsRequired || [];
  11524. }
  11525. getUsedExtensions() {
  11526. return this.json.extensionsUsed || [];
  11527. }
  11528. getObjectExtension(object, extensionName) {
  11529. const extensions = object.extensions || {};
  11530. return extensions[extensionName];
  11531. }
  11532. getScene(index) {
  11533. return this.getObject('scenes', index);
  11534. }
  11535. getNode(index) {
  11536. return this.getObject('nodes', index);
  11537. }
  11538. getSkin(index) {
  11539. return this.getObject('skins', index);
  11540. }
  11541. getMesh(index) {
  11542. return this.getObject('meshes', index);
  11543. }
  11544. getMaterial(index) {
  11545. return this.getObject('materials', index);
  11546. }
  11547. getAccessor(index) {
  11548. return this.getObject('accessors', index);
  11549. }
  11550. getTexture(index) {
  11551. return this.getObject('textures', index);
  11552. }
  11553. getSampler(index) {
  11554. return this.getObject('samplers', index);
  11555. }
  11556. getImage(index) {
  11557. return this.getObject('images', index);
  11558. }
  11559. getBufferView(index) {
  11560. return this.getObject('bufferViews', index);
  11561. }
  11562. getBuffer(index) {
  11563. return this.getObject('buffers', index);
  11564. }
  11565. getObject(array, index) {
  11566. if (typeof index === 'object') {
  11567. return index;
  11568. }
  11569. const object = this.json[array] && this.json[array][index];
  11570. if (!object) {
  11571. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11572. }
  11573. return object;
  11574. }
  11575. getTypedArrayForBufferView(bufferView) {
  11576. bufferView = this.getBufferView(bufferView);
  11577. const bufferIndex = bufferView.buffer;
  11578. const binChunk = this.gltf.buffers[bufferIndex];
  11579. assert$1(binChunk);
  11580. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11581. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11582. }
  11583. getTypedArrayForAccessor(accessor) {
  11584. accessor = this.getAccessor(accessor);
  11585. const bufferView = this.getBufferView(accessor.bufferView);
  11586. const buffer = this.getBuffer(bufferView.buffer);
  11587. const arrayBuffer = buffer.data;
  11588. const {
  11589. ArrayType,
  11590. length
  11591. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11592. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11593. return new ArrayType(arrayBuffer, byteOffset, length);
  11594. }
  11595. getTypedArrayForImageData(image) {
  11596. image = this.getAccessor(image);
  11597. const bufferView = this.getBufferView(image.bufferView);
  11598. const buffer = this.getBuffer(bufferView.buffer);
  11599. const arrayBuffer = buffer.data;
  11600. const byteOffset = bufferView.byteOffset || 0;
  11601. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11602. }
  11603. addApplicationData(key, data) {
  11604. this.json[key] = data;
  11605. return this;
  11606. }
  11607. addExtraData(key, data) {
  11608. this.json.extras = this.json.extras || {};
  11609. this.json.extras[key] = data;
  11610. return this;
  11611. }
  11612. addObjectExtension(object, extensionName, data) {
  11613. object.extensions = object.extensions || {};
  11614. object.extensions[extensionName] = data;
  11615. this.registerUsedExtension(extensionName);
  11616. return this;
  11617. }
  11618. setObjectExtension(object, extensionName, data) {
  11619. const extensions = object.extensions || {};
  11620. extensions[extensionName] = data;
  11621. }
  11622. removeObjectExtension(object, extensionName) {
  11623. const extensions = object.extensions || {};
  11624. const extension = extensions[extensionName];
  11625. delete extensions[extensionName];
  11626. return extension;
  11627. }
  11628. addExtension(extensionName, extensionData = {}) {
  11629. assert$1(extensionData);
  11630. this.json.extensions = this.json.extensions || {};
  11631. this.json.extensions[extensionName] = extensionData;
  11632. this.registerUsedExtension(extensionName);
  11633. return extensionData;
  11634. }
  11635. addRequiredExtension(extensionName, extensionData = {}) {
  11636. assert$1(extensionData);
  11637. this.addExtension(extensionName, extensionData);
  11638. this.registerRequiredExtension(extensionName);
  11639. return extensionData;
  11640. }
  11641. registerUsedExtension(extensionName) {
  11642. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11643. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11644. this.json.extensionsUsed.push(extensionName);
  11645. }
  11646. }
  11647. registerRequiredExtension(extensionName) {
  11648. this.registerUsedExtension(extensionName);
  11649. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11650. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11651. this.json.extensionsRequired.push(extensionName);
  11652. }
  11653. }
  11654. removeExtension(extensionName) {
  11655. if (this.json.extensionsRequired) {
  11656. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11657. }
  11658. if (this.json.extensionsUsed) {
  11659. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11660. }
  11661. if (this.json.extensions) {
  11662. delete this.json.extensions[extensionName];
  11663. }
  11664. }
  11665. setDefaultScene(sceneIndex) {
  11666. this.json.scene = sceneIndex;
  11667. }
  11668. addScene(scene) {
  11669. const {
  11670. nodeIndices
  11671. } = scene;
  11672. this.json.scenes = this.json.scenes || [];
  11673. this.json.scenes.push({
  11674. nodes: nodeIndices
  11675. });
  11676. return this.json.scenes.length - 1;
  11677. }
  11678. addNode(node) {
  11679. const {
  11680. meshIndex,
  11681. matrix
  11682. } = node;
  11683. this.json.nodes = this.json.nodes || [];
  11684. const nodeData = {
  11685. mesh: meshIndex
  11686. };
  11687. if (matrix) {
  11688. nodeData.matrix = matrix;
  11689. }
  11690. this.json.nodes.push(nodeData);
  11691. return this.json.nodes.length - 1;
  11692. }
  11693. addMesh(mesh) {
  11694. const {
  11695. attributes,
  11696. indices,
  11697. material,
  11698. mode = 4
  11699. } = mesh;
  11700. const accessors = this._addAttributes(attributes);
  11701. const glTFMesh = {
  11702. primitives: [{
  11703. attributes: accessors,
  11704. mode
  11705. }]
  11706. };
  11707. if (indices) {
  11708. const indicesAccessor = this._addIndices(indices);
  11709. glTFMesh.primitives[0].indices = indicesAccessor;
  11710. }
  11711. if (Number.isFinite(material)) {
  11712. glTFMesh.primitives[0].material = material;
  11713. }
  11714. this.json.meshes = this.json.meshes || [];
  11715. this.json.meshes.push(glTFMesh);
  11716. return this.json.meshes.length - 1;
  11717. }
  11718. addPointCloud(attributes) {
  11719. const accessorIndices = this._addAttributes(attributes);
  11720. const glTFMesh = {
  11721. primitives: [{
  11722. attributes: accessorIndices,
  11723. mode: 0
  11724. }]
  11725. };
  11726. this.json.meshes = this.json.meshes || [];
  11727. this.json.meshes.push(glTFMesh);
  11728. return this.json.meshes.length - 1;
  11729. }
  11730. addImage(imageData, mimeTypeOpt) {
  11731. const metadata = getBinaryImageMetadata(imageData);
  11732. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11733. const bufferViewIndex = this.addBufferView(imageData);
  11734. const glTFImage = {
  11735. bufferView: bufferViewIndex,
  11736. mimeType
  11737. };
  11738. this.json.images = this.json.images || [];
  11739. this.json.images.push(glTFImage);
  11740. return this.json.images.length - 1;
  11741. }
  11742. addBufferView(buffer) {
  11743. const byteLength = buffer.byteLength;
  11744. assert$1(Number.isFinite(byteLength));
  11745. this.sourceBuffers = this.sourceBuffers || [];
  11746. this.sourceBuffers.push(buffer);
  11747. const glTFBufferView = {
  11748. buffer: 0,
  11749. byteOffset: this.byteLength,
  11750. byteLength
  11751. };
  11752. this.byteLength += padToNBytes(byteLength, 4);
  11753. this.json.bufferViews = this.json.bufferViews || [];
  11754. this.json.bufferViews.push(glTFBufferView);
  11755. return this.json.bufferViews.length - 1;
  11756. }
  11757. addAccessor(bufferViewIndex, accessor) {
  11758. const glTFAccessor = {
  11759. bufferView: bufferViewIndex,
  11760. type: getAccessorTypeFromSize(accessor.size),
  11761. componentType: accessor.componentType,
  11762. count: accessor.count,
  11763. max: accessor.max,
  11764. min: accessor.min
  11765. };
  11766. this.json.accessors = this.json.accessors || [];
  11767. this.json.accessors.push(glTFAccessor);
  11768. return this.json.accessors.length - 1;
  11769. }
  11770. addBinaryBuffer(sourceBuffer, accessor = {
  11771. size: 3
  11772. }) {
  11773. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11774. let minMax = {
  11775. min: accessor.min,
  11776. max: accessor.max
  11777. };
  11778. if (!minMax.min || !minMax.max) {
  11779. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11780. }
  11781. const accessorDefaults = {
  11782. size: accessor.size,
  11783. componentType: getComponentTypeFromArray(sourceBuffer),
  11784. count: Math.round(sourceBuffer.length / accessor.size),
  11785. min: minMax.min,
  11786. max: minMax.max
  11787. };
  11788. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11789. }
  11790. addTexture(texture) {
  11791. const {
  11792. imageIndex
  11793. } = texture;
  11794. const glTFTexture = {
  11795. source: imageIndex
  11796. };
  11797. this.json.textures = this.json.textures || [];
  11798. this.json.textures.push(glTFTexture);
  11799. return this.json.textures.length - 1;
  11800. }
  11801. addMaterial(pbrMaterialInfo) {
  11802. this.json.materials = this.json.materials || [];
  11803. this.json.materials.push(pbrMaterialInfo);
  11804. return this.json.materials.length - 1;
  11805. }
  11806. createBinaryChunk() {
  11807. var _this$json, _this$json$buffers;
  11808. this.gltf.buffers = [];
  11809. const totalByteLength = this.byteLength;
  11810. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11811. const targetArray = new Uint8Array(arrayBuffer);
  11812. let dstByteOffset = 0;
  11813. for (const sourceBuffer of this.sourceBuffers || []) {
  11814. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11815. }
  11816. 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]) {
  11817. this.json.buffers[0].byteLength = totalByteLength;
  11818. } else {
  11819. this.json.buffers = [{
  11820. byteLength: totalByteLength
  11821. }];
  11822. }
  11823. this.gltf.binary = arrayBuffer;
  11824. this.sourceBuffers = [arrayBuffer];
  11825. }
  11826. _removeStringFromArray(array, string) {
  11827. let found = true;
  11828. while (found) {
  11829. const index = array.indexOf(string);
  11830. if (index > -1) {
  11831. array.splice(index, 1);
  11832. } else {
  11833. found = false;
  11834. }
  11835. }
  11836. }
  11837. _addAttributes(attributes = {}) {
  11838. const result = {};
  11839. for (const attributeKey in attributes) {
  11840. const attributeData = attributes[attributeKey];
  11841. const attrName = this._getGltfAttributeName(attributeKey);
  11842. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11843. result[attrName] = accessor;
  11844. }
  11845. return result;
  11846. }
  11847. _addIndices(indices) {
  11848. return this.addBinaryBuffer(indices, {
  11849. size: 1
  11850. });
  11851. }
  11852. _getGltfAttributeName(attributeName) {
  11853. switch (attributeName.toLowerCase()) {
  11854. case 'position':
  11855. case 'positions':
  11856. case 'vertices':
  11857. return 'POSITION';
  11858. case 'normal':
  11859. case 'normals':
  11860. return 'NORMAL';
  11861. case 'color':
  11862. case 'colors':
  11863. return 'COLOR_0';
  11864. case 'texcoord':
  11865. case 'texcoords':
  11866. return 'TEXCOORD_0';
  11867. default:
  11868. return attributeName;
  11869. }
  11870. }
  11871. _getAccessorMinMax(buffer, size) {
  11872. const result = {
  11873. min: null,
  11874. max: null
  11875. };
  11876. if (buffer.length < size) {
  11877. return result;
  11878. }
  11879. result.min = [];
  11880. result.max = [];
  11881. const initValues = buffer.subarray(0, size);
  11882. for (const value of initValues) {
  11883. result.min.push(value);
  11884. result.max.push(value);
  11885. }
  11886. for (let index = size; index < buffer.length; index += size) {
  11887. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  11888. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  11889. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  11890. }
  11891. }
  11892. return result;
  11893. }
  11894. }
  11895. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  11896. 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';
  11897. 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';
  11898. 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]);
  11899. 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]);
  11900. const FILTERS = {
  11901. 0: '',
  11902. 1: 'meshopt_decodeFilterOct',
  11903. 2: 'meshopt_decodeFilterQuat',
  11904. 3: 'meshopt_decodeFilterExp',
  11905. NONE: '',
  11906. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  11907. QUATERNION: 'meshopt_decodeFilterQuat',
  11908. EXPONENTIAL: 'meshopt_decodeFilterExp'
  11909. };
  11910. const DECODERS = {
  11911. 0: 'meshopt_decodeVertexBuffer',
  11912. 1: 'meshopt_decodeIndexBuffer',
  11913. 2: 'meshopt_decodeIndexSequence',
  11914. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  11915. TRIANGLES: 'meshopt_decodeIndexBuffer',
  11916. INDICES: 'meshopt_decodeIndexSequence'
  11917. };
  11918. function isMeshoptSupported() {
  11919. return isWebAssemblySupported;
  11920. }
  11921. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  11922. const instance = await loadWasmInstance();
  11923. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  11924. }
  11925. let wasmPromise;
  11926. async function loadWasmInstance() {
  11927. if (!wasmPromise) {
  11928. wasmPromise = loadWasmModule();
  11929. }
  11930. return wasmPromise;
  11931. }
  11932. async function loadWasmModule() {
  11933. let wasm = wasm_base;
  11934. if (WebAssembly.validate(detector)) {
  11935. wasm = wasm_simd;
  11936. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  11937. }
  11938. const result = await WebAssembly.instantiate(unpack(wasm), {});
  11939. await result.instance.exports.__wasm_call_ctors();
  11940. return result.instance;
  11941. }
  11942. function unpack(data) {
  11943. const result = new Uint8Array(data.length);
  11944. for (let i = 0; i < data.length; ++i) {
  11945. const ch = data.charCodeAt(i);
  11946. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  11947. }
  11948. let write = 0;
  11949. for (let i = 0; i < data.length; ++i) {
  11950. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  11951. }
  11952. return result.buffer.slice(0, write);
  11953. }
  11954. function decode$5(instance, fun, target, count, size, source, filter) {
  11955. const sbrk = instance.exports.sbrk;
  11956. const count4 = count + 3 & ~3;
  11957. const tp = sbrk(count4 * size);
  11958. const sp = sbrk(source.length);
  11959. const heap = new Uint8Array(instance.exports.memory.buffer);
  11960. heap.set(source, sp);
  11961. const res = fun(tp, count, size, sp, source.length);
  11962. if (res === 0 && filter) {
  11963. filter(tp, count4, size);
  11964. }
  11965. target.set(heap.subarray(tp, tp + count * size));
  11966. sbrk(tp - sbrk(0));
  11967. if (res !== 0) {
  11968. throw new Error("Malformed buffer data: ".concat(res));
  11969. }
  11970. }
  11971. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  11972. const name$6 = EXT_MESHOPT_COMPRESSION;
  11973. function preprocess$4(gltfData) {
  11974. const scenegraph = new GLTFScenegraph(gltfData);
  11975. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  11976. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  11977. }
  11978. }
  11979. async function decode$4(gltfData, options) {
  11980. var _options$gltf;
  11981. const scenegraph = new GLTFScenegraph(gltfData);
  11982. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  11983. return;
  11984. }
  11985. const promises = [];
  11986. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  11987. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  11988. }
  11989. await Promise.all(promises);
  11990. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  11991. }
  11992. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  11993. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  11994. if (meshoptExtension) {
  11995. const buffer = bufferView.buffer;
  11996. const {
  11997. byteOffset = 0,
  11998. byteLength = 0,
  11999. byteStride,
  12000. count,
  12001. mode,
  12002. filter = 'NONE'
  12003. } = meshoptExtension;
  12004. const source = new Uint8Array(buffer, byteOffset, byteLength);
  12005. const result = new ArrayBuffer(count * byteStride);
  12006. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  12007. return result;
  12008. }
  12009. return null;
  12010. }
  12011. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12012. __proto__: null,
  12013. name: name$6,
  12014. preprocess: preprocess$4,
  12015. decode: decode$4
  12016. });
  12017. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12018. const name$5 = EXT_TEXTURE_WEBP;
  12019. function preprocess$3(gltfData, options) {
  12020. const scenegraph = new GLTFScenegraph(gltfData);
  12021. if (!_isImageFormatSupported('image/webp')) {
  12022. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12023. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12024. }
  12025. return;
  12026. }
  12027. const {
  12028. json
  12029. } = scenegraph;
  12030. for (const texture of json.textures || []) {
  12031. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12032. if (extension) {
  12033. texture.source = extension.source;
  12034. }
  12035. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12036. }
  12037. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12038. }
  12039. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12040. __proto__: null,
  12041. name: name$5,
  12042. preprocess: preprocess$3
  12043. });
  12044. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12045. const name$4 = KHR_TEXTURE_BASISU;
  12046. function preprocess$2(gltfData, options) {
  12047. const scene = new GLTFScenegraph(gltfData);
  12048. const {
  12049. json
  12050. } = scene;
  12051. for (const texture of json.textures || []) {
  12052. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12053. if (extension) {
  12054. texture.source = extension.source;
  12055. }
  12056. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12057. }
  12058. scene.removeExtension(KHR_TEXTURE_BASISU);
  12059. }
  12060. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12061. __proto__: null,
  12062. name: name$4,
  12063. preprocess: preprocess$2
  12064. });
  12065. function getGLTFAccessors(attributes) {
  12066. const accessors = {};
  12067. for (const name in attributes) {
  12068. const attribute = attributes[name];
  12069. if (name !== 'indices') {
  12070. const glTFAccessor = getGLTFAccessor(attribute);
  12071. accessors[name] = glTFAccessor;
  12072. }
  12073. }
  12074. return accessors;
  12075. }
  12076. function getGLTFAccessor(attribute) {
  12077. const {
  12078. buffer,
  12079. size,
  12080. count
  12081. } = getAccessorData(attribute);
  12082. const glTFAccessor = {
  12083. value: buffer,
  12084. size,
  12085. byteOffset: 0,
  12086. count,
  12087. type: getAccessorTypeFromSize(size),
  12088. componentType: getComponentTypeFromArray(buffer)
  12089. };
  12090. return glTFAccessor;
  12091. }
  12092. function getAccessorData(attribute) {
  12093. let buffer = attribute;
  12094. let size = 1;
  12095. let count = 0;
  12096. if (attribute && attribute.value) {
  12097. buffer = attribute.value;
  12098. size = attribute.size || 1;
  12099. }
  12100. if (buffer) {
  12101. if (!ArrayBuffer.isView(buffer)) {
  12102. buffer = toTypedArray(buffer, Float32Array);
  12103. }
  12104. count = buffer.length / size;
  12105. }
  12106. return {
  12107. buffer,
  12108. size,
  12109. count
  12110. };
  12111. }
  12112. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12113. if (!array) {
  12114. return null;
  12115. }
  12116. if (Array.isArray(array)) {
  12117. return new ArrayType(array);
  12118. }
  12119. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12120. return new ArrayType(array);
  12121. }
  12122. return array;
  12123. }
  12124. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12125. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12126. function preprocess$1(gltfData, options, context) {
  12127. const scenegraph = new GLTFScenegraph(gltfData);
  12128. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12129. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12130. }
  12131. }
  12132. async function decode$3(gltfData, options, context) {
  12133. var _options$gltf;
  12134. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12135. return;
  12136. }
  12137. const scenegraph = new GLTFScenegraph(gltfData);
  12138. const promises = [];
  12139. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12140. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12141. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12142. }
  12143. }
  12144. await Promise.all(promises);
  12145. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12146. }
  12147. function encode$3(gltfData, options = {}) {
  12148. const scenegraph = new GLTFScenegraph(gltfData);
  12149. for (const mesh of scenegraph.json.meshes || []) {
  12150. compressMesh(mesh);
  12151. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12152. }
  12153. }
  12154. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12155. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12156. if (!dracoExtension) {
  12157. return;
  12158. }
  12159. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12160. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12161. const {
  12162. parse
  12163. } = context;
  12164. const dracoOptions = { ...options
  12165. };
  12166. delete dracoOptions['3d-tiles'];
  12167. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12168. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12169. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12170. if (attributeName in primitive.attributes) {
  12171. const accessorIndex = primitive.attributes[attributeName];
  12172. const accessor = scenegraph.getAccessor(accessorIndex);
  12173. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12174. decodedAttribute.min = accessor.min;
  12175. decodedAttribute.max = accessor.max;
  12176. }
  12177. }
  12178. }
  12179. primitive.attributes = decodedAttributes;
  12180. if (decodedData.indices) {
  12181. primitive.indices = getGLTFAccessor(decodedData.indices);
  12182. }
  12183. checkPrimitive(primitive);
  12184. }
  12185. function compressMesh(attributes, indices, mode = 4, options, context) {
  12186. var _context$parseSync;
  12187. if (!options.DracoWriter) {
  12188. throw new Error('options.gltf.DracoWriter not provided');
  12189. }
  12190. const compressedData = options.DracoWriter.encodeSync({
  12191. attributes
  12192. });
  12193. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12194. attributes
  12195. });
  12196. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12197. const bufferViewIndex = options.addBufferView(compressedData);
  12198. const glTFMesh = {
  12199. primitives: [{
  12200. attributes: fauxAccessors,
  12201. mode,
  12202. extensions: {
  12203. [KHR_DRACO_MESH_COMPRESSION]: {
  12204. bufferView: bufferViewIndex,
  12205. attributes: fauxAccessors
  12206. }
  12207. }
  12208. }]
  12209. };
  12210. return glTFMesh;
  12211. }
  12212. function checkPrimitive(primitive) {
  12213. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12214. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12215. }
  12216. }
  12217. function* makeMeshPrimitiveIterator(scenegraph) {
  12218. for (const mesh of scenegraph.json.meshes || []) {
  12219. for (const primitive of mesh.primitives) {
  12220. yield primitive;
  12221. }
  12222. }
  12223. }
  12224. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12225. __proto__: null,
  12226. name: name$3,
  12227. preprocess: preprocess$1,
  12228. decode: decode$3,
  12229. encode: encode$3
  12230. });
  12231. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12232. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12233. async function decode$2(gltfData) {
  12234. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12235. const {
  12236. json
  12237. } = gltfScenegraph;
  12238. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12239. if (extension) {
  12240. gltfScenegraph.json.lights = extension.lights;
  12241. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12242. }
  12243. for (const node of json.nodes || []) {
  12244. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12245. if (nodeExtension) {
  12246. node.light = nodeExtension.light;
  12247. }
  12248. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12249. }
  12250. }
  12251. async function encode$2(gltfData) {
  12252. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12253. const {
  12254. json
  12255. } = gltfScenegraph;
  12256. if (json.lights) {
  12257. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12258. assert$1(!extension.lights);
  12259. extension.lights = json.lights;
  12260. delete json.lights;
  12261. }
  12262. if (gltfScenegraph.json.lights) {
  12263. for (const light of gltfScenegraph.json.lights) {
  12264. const node = light.node;
  12265. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12266. }
  12267. delete gltfScenegraph.json.lights;
  12268. }
  12269. }
  12270. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12271. __proto__: null,
  12272. name: name$2,
  12273. decode: decode$2,
  12274. encode: encode$2
  12275. });
  12276. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12277. const name$1 = KHR_MATERIALS_UNLIT;
  12278. async function decode$1(gltfData) {
  12279. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12280. const {
  12281. json
  12282. } = gltfScenegraph;
  12283. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12284. for (const material of json.materials || []) {
  12285. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12286. if (extension) {
  12287. material.unlit = true;
  12288. }
  12289. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12290. }
  12291. }
  12292. function encode$1(gltfData) {
  12293. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12294. const {
  12295. json
  12296. } = gltfScenegraph;
  12297. if (gltfScenegraph.materials) {
  12298. for (const material of json.materials || []) {
  12299. if (material.unlit) {
  12300. delete material.unlit;
  12301. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12302. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12303. }
  12304. }
  12305. }
  12306. }
  12307. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12308. __proto__: null,
  12309. name: name$1,
  12310. decode: decode$1,
  12311. encode: encode$1
  12312. });
  12313. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12314. const name = KHR_TECHNIQUES_WEBGL;
  12315. async function decode(gltfData) {
  12316. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12317. const {
  12318. json
  12319. } = gltfScenegraph;
  12320. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12321. if (extension) {
  12322. const techniques = resolveTechniques(extension, gltfScenegraph);
  12323. for (const material of json.materials || []) {
  12324. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12325. if (materialExtension) {
  12326. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12327. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12328. }
  12329. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12330. }
  12331. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12332. }
  12333. }
  12334. async function encode(gltfData, options) {}
  12335. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12336. const {
  12337. programs = [],
  12338. shaders = [],
  12339. techniques = []
  12340. } = techniquesExtension;
  12341. const textDecoder = new TextDecoder();
  12342. shaders.forEach(shader => {
  12343. if (Number.isFinite(shader.bufferView)) {
  12344. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12345. } else {
  12346. throw new Error('KHR_techniques_webgl: no shader code');
  12347. }
  12348. });
  12349. programs.forEach(program => {
  12350. program.fragmentShader = shaders[program.fragmentShader];
  12351. program.vertexShader = shaders[program.vertexShader];
  12352. });
  12353. techniques.forEach(technique => {
  12354. technique.program = programs[technique.program];
  12355. });
  12356. return techniques;
  12357. }
  12358. function resolveValues(technique, gltfScenegraph) {
  12359. const values = Object.assign({}, technique.values);
  12360. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12361. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12362. values[uniform] = technique.uniforms[uniform].value;
  12363. }
  12364. });
  12365. Object.keys(values).forEach(uniform => {
  12366. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12367. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12368. }
  12369. });
  12370. return values;
  12371. }
  12372. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12373. __proto__: null,
  12374. name: name,
  12375. decode: decode,
  12376. encode: encode
  12377. });
  12378. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12379. function preprocessExtensions(gltf, options = {}, context) {
  12380. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12381. for (const extension of extensions) {
  12382. var _extension$preprocess;
  12383. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12384. }
  12385. }
  12386. async function decodeExtensions(gltf, options = {}, context) {
  12387. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12388. for (const extension of extensions) {
  12389. var _extension$decode;
  12390. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12391. }
  12392. }
  12393. function useExtension(extensionName, options) {
  12394. var _options$gltf;
  12395. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12396. const exclude = extensionName in excludes && !excludes[extensionName];
  12397. return !exclude;
  12398. }
  12399. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12400. function preprocess(gltfData) {
  12401. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12402. const {
  12403. json
  12404. } = gltfScenegraph;
  12405. for (const image of json.images || []) {
  12406. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12407. if (extension) {
  12408. Object.assign(image, extension);
  12409. }
  12410. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12411. }
  12412. if (json.buffers && json.buffers[0]) {
  12413. delete json.buffers[0].uri;
  12414. }
  12415. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12416. }
  12417. const GLTF_ARRAYS = {
  12418. accessors: 'accessor',
  12419. animations: 'animation',
  12420. buffers: 'buffer',
  12421. bufferViews: 'bufferView',
  12422. images: 'image',
  12423. materials: 'material',
  12424. meshes: 'mesh',
  12425. nodes: 'node',
  12426. samplers: 'sampler',
  12427. scenes: 'scene',
  12428. skins: 'skin',
  12429. textures: 'texture'
  12430. };
  12431. const GLTF_KEYS = {
  12432. accessor: 'accessors',
  12433. animations: 'animation',
  12434. buffer: 'buffers',
  12435. bufferView: 'bufferViews',
  12436. image: 'images',
  12437. material: 'materials',
  12438. mesh: 'meshes',
  12439. node: 'nodes',
  12440. sampler: 'samplers',
  12441. scene: 'scenes',
  12442. skin: 'skins',
  12443. texture: 'textures'
  12444. };
  12445. class GLTFV1Normalizer {
  12446. constructor() {
  12447. _defineProperty(this, "idToIndexMap", {
  12448. animations: {},
  12449. accessors: {},
  12450. buffers: {},
  12451. bufferViews: {},
  12452. images: {},
  12453. materials: {},
  12454. meshes: {},
  12455. nodes: {},
  12456. samplers: {},
  12457. scenes: {},
  12458. skins: {},
  12459. textures: {}
  12460. });
  12461. _defineProperty(this, "json", void 0);
  12462. }
  12463. normalize(gltf, options) {
  12464. this.json = gltf.json;
  12465. const json = gltf.json;
  12466. switch (json.asset && json.asset.version) {
  12467. case '2.0':
  12468. return;
  12469. case undefined:
  12470. case '1.0':
  12471. break;
  12472. default:
  12473. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12474. return;
  12475. }
  12476. if (!options.normalize) {
  12477. throw new Error('glTF v1 is not supported.');
  12478. }
  12479. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12480. this._addAsset(json);
  12481. this._convertTopLevelObjectsToArrays(json);
  12482. preprocess(gltf);
  12483. this._convertObjectIdsToArrayIndices(json);
  12484. this._updateObjects(json);
  12485. this._updateMaterial(json);
  12486. }
  12487. _addAsset(json) {
  12488. json.asset = json.asset || {};
  12489. json.asset.version = '2.0';
  12490. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12491. }
  12492. _convertTopLevelObjectsToArrays(json) {
  12493. for (const arrayName in GLTF_ARRAYS) {
  12494. this._convertTopLevelObjectToArray(json, arrayName);
  12495. }
  12496. }
  12497. _convertTopLevelObjectToArray(json, mapName) {
  12498. const objectMap = json[mapName];
  12499. if (!objectMap || Array.isArray(objectMap)) {
  12500. return;
  12501. }
  12502. json[mapName] = [];
  12503. for (const id in objectMap) {
  12504. const object = objectMap[id];
  12505. object.id = object.id || id;
  12506. const index = json[mapName].length;
  12507. json[mapName].push(object);
  12508. this.idToIndexMap[mapName][id] = index;
  12509. }
  12510. }
  12511. _convertObjectIdsToArrayIndices(json) {
  12512. for (const arrayName in GLTF_ARRAYS) {
  12513. this._convertIdsToIndices(json, arrayName);
  12514. }
  12515. if ('scene' in json) {
  12516. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12517. }
  12518. for (const texture of json.textures) {
  12519. this._convertTextureIds(texture);
  12520. }
  12521. for (const mesh of json.meshes) {
  12522. this._convertMeshIds(mesh);
  12523. }
  12524. for (const node of json.nodes) {
  12525. this._convertNodeIds(node);
  12526. }
  12527. for (const node of json.scenes) {
  12528. this._convertSceneIds(node);
  12529. }
  12530. }
  12531. _convertTextureIds(texture) {
  12532. if (texture.source) {
  12533. texture.source = this._convertIdToIndex(texture.source, 'image');
  12534. }
  12535. }
  12536. _convertMeshIds(mesh) {
  12537. for (const primitive of mesh.primitives) {
  12538. const {
  12539. attributes,
  12540. indices,
  12541. material
  12542. } = primitive;
  12543. for (const attributeName in attributes) {
  12544. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12545. }
  12546. if (indices) {
  12547. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12548. }
  12549. if (material) {
  12550. primitive.material = this._convertIdToIndex(material, 'material');
  12551. }
  12552. }
  12553. }
  12554. _convertNodeIds(node) {
  12555. if (node.children) {
  12556. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12557. }
  12558. if (node.meshes) {
  12559. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12560. }
  12561. }
  12562. _convertSceneIds(scene) {
  12563. if (scene.nodes) {
  12564. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12565. }
  12566. }
  12567. _convertIdsToIndices(json, topLevelArrayName) {
  12568. if (!json[topLevelArrayName]) {
  12569. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12570. json[topLevelArrayName] = [];
  12571. }
  12572. for (const object of json[topLevelArrayName]) {
  12573. for (const key in object) {
  12574. const id = object[key];
  12575. const index = this._convertIdToIndex(id, key);
  12576. object[key] = index;
  12577. }
  12578. }
  12579. }
  12580. _convertIdToIndex(id, key) {
  12581. const arrayName = GLTF_KEYS[key];
  12582. if (arrayName in this.idToIndexMap) {
  12583. const index = this.idToIndexMap[arrayName][id];
  12584. if (!Number.isFinite(index)) {
  12585. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12586. }
  12587. return index;
  12588. }
  12589. return id;
  12590. }
  12591. _updateObjects(json) {
  12592. for (const buffer of this.json.buffers) {
  12593. delete buffer.type;
  12594. }
  12595. }
  12596. _updateMaterial(json) {
  12597. for (const material of json.materials) {
  12598. material.pbrMetallicRoughness = {
  12599. baseColorFactor: [1, 1, 1, 1],
  12600. metallicFactor: 1,
  12601. roughnessFactor: 1
  12602. };
  12603. const textureId = material.values && material.values.tex;
  12604. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12605. if (textureIndex !== -1) {
  12606. material.pbrMetallicRoughness.baseColorTexture = {
  12607. index: textureIndex
  12608. };
  12609. }
  12610. }
  12611. }
  12612. }
  12613. function normalizeGLTFV1(gltf, options = {}) {
  12614. return new GLTFV1Normalizer().normalize(gltf, options);
  12615. }
  12616. const COMPONENTS = {
  12617. SCALAR: 1,
  12618. VEC2: 2,
  12619. VEC3: 3,
  12620. VEC4: 4,
  12621. MAT2: 4,
  12622. MAT3: 9,
  12623. MAT4: 16
  12624. };
  12625. const BYTES = {
  12626. 5120: 1,
  12627. 5121: 1,
  12628. 5122: 2,
  12629. 5123: 2,
  12630. 5125: 4,
  12631. 5126: 4
  12632. };
  12633. const GL_SAMPLER = {
  12634. TEXTURE_MAG_FILTER: 0x2800,
  12635. TEXTURE_MIN_FILTER: 0x2801,
  12636. TEXTURE_WRAP_S: 0x2802,
  12637. TEXTURE_WRAP_T: 0x2803,
  12638. REPEAT: 0x2901,
  12639. LINEAR: 0x2601,
  12640. NEAREST_MIPMAP_LINEAR: 0x2702
  12641. };
  12642. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12643. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12644. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12645. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12646. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12647. };
  12648. const DEFAULT_SAMPLER = {
  12649. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12650. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12651. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12652. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12653. };
  12654. function getBytesFromComponentType(componentType) {
  12655. return BYTES[componentType];
  12656. }
  12657. function getSizeFromAccessorType(type) {
  12658. return COMPONENTS[type];
  12659. }
  12660. class GLTFPostProcessor {
  12661. constructor() {
  12662. _defineProperty(this, "baseUri", '');
  12663. _defineProperty(this, "json", {});
  12664. _defineProperty(this, "buffers", []);
  12665. _defineProperty(this, "images", []);
  12666. }
  12667. postProcess(gltf, options = {}) {
  12668. const {
  12669. json,
  12670. buffers = [],
  12671. images = [],
  12672. baseUri = ''
  12673. } = gltf;
  12674. assert$1(json);
  12675. this.baseUri = baseUri;
  12676. this.json = json;
  12677. this.buffers = buffers;
  12678. this.images = images;
  12679. this._resolveTree(this.json, options);
  12680. return this.json;
  12681. }
  12682. _resolveTree(json, options = {}) {
  12683. if (json.bufferViews) {
  12684. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12685. }
  12686. if (json.images) {
  12687. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12688. }
  12689. if (json.samplers) {
  12690. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12691. }
  12692. if (json.textures) {
  12693. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12694. }
  12695. if (json.accessors) {
  12696. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12697. }
  12698. if (json.materials) {
  12699. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12700. }
  12701. if (json.meshes) {
  12702. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12703. }
  12704. if (json.nodes) {
  12705. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12706. }
  12707. if (json.skins) {
  12708. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12709. }
  12710. if (json.scenes) {
  12711. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12712. }
  12713. if (json.scene !== undefined) {
  12714. json.scene = json.scenes[this.json.scene];
  12715. }
  12716. }
  12717. getScene(index) {
  12718. return this._get('scenes', index);
  12719. }
  12720. getNode(index) {
  12721. return this._get('nodes', index);
  12722. }
  12723. getSkin(index) {
  12724. return this._get('skins', index);
  12725. }
  12726. getMesh(index) {
  12727. return this._get('meshes', index);
  12728. }
  12729. getMaterial(index) {
  12730. return this._get('materials', index);
  12731. }
  12732. getAccessor(index) {
  12733. return this._get('accessors', index);
  12734. }
  12735. getCamera(index) {
  12736. return null;
  12737. }
  12738. getTexture(index) {
  12739. return this._get('textures', index);
  12740. }
  12741. getSampler(index) {
  12742. return this._get('samplers', index);
  12743. }
  12744. getImage(index) {
  12745. return this._get('images', index);
  12746. }
  12747. getBufferView(index) {
  12748. return this._get('bufferViews', index);
  12749. }
  12750. getBuffer(index) {
  12751. return this._get('buffers', index);
  12752. }
  12753. _get(array, index) {
  12754. if (typeof index === 'object') {
  12755. return index;
  12756. }
  12757. const object = this.json[array] && this.json[array][index];
  12758. if (!object) {
  12759. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12760. }
  12761. return object;
  12762. }
  12763. _resolveScene(scene, index) {
  12764. scene.id = scene.id || "scene-".concat(index);
  12765. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12766. return scene;
  12767. }
  12768. _resolveNode(node, index) {
  12769. node.id = node.id || "node-".concat(index);
  12770. if (node.children) {
  12771. node.children = node.children.map(child => this.getNode(child));
  12772. }
  12773. if (node.mesh !== undefined) {
  12774. node.mesh = this.getMesh(node.mesh);
  12775. } else if (node.meshes !== undefined && node.meshes.length) {
  12776. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12777. const mesh = this.getMesh(meshIndex);
  12778. accum.id = mesh.id;
  12779. accum.primitives = accum.primitives.concat(mesh.primitives);
  12780. return accum;
  12781. }, {
  12782. primitives: []
  12783. });
  12784. }
  12785. if (node.camera !== undefined) {
  12786. node.camera = this.getCamera(node.camera);
  12787. }
  12788. if (node.skin !== undefined) {
  12789. node.skin = this.getSkin(node.skin);
  12790. }
  12791. return node;
  12792. }
  12793. _resolveSkin(skin, index) {
  12794. skin.id = skin.id || "skin-".concat(index);
  12795. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12796. return skin;
  12797. }
  12798. _resolveMesh(mesh, index) {
  12799. mesh.id = mesh.id || "mesh-".concat(index);
  12800. if (mesh.primitives) {
  12801. mesh.primitives = mesh.primitives.map(primitive => {
  12802. primitive = { ...primitive
  12803. };
  12804. const attributes = primitive.attributes;
  12805. primitive.attributes = {};
  12806. for (const attribute in attributes) {
  12807. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12808. }
  12809. if (primitive.indices !== undefined) {
  12810. primitive.indices = this.getAccessor(primitive.indices);
  12811. }
  12812. if (primitive.material !== undefined) {
  12813. primitive.material = this.getMaterial(primitive.material);
  12814. }
  12815. return primitive;
  12816. });
  12817. }
  12818. return mesh;
  12819. }
  12820. _resolveMaterial(material, index) {
  12821. material.id = material.id || "material-".concat(index);
  12822. if (material.normalTexture) {
  12823. material.normalTexture = { ...material.normalTexture
  12824. };
  12825. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12826. }
  12827. if (material.occlusionTexture) {
  12828. material.occlustionTexture = { ...material.occlustionTexture
  12829. };
  12830. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12831. }
  12832. if (material.emissiveTexture) {
  12833. material.emmisiveTexture = { ...material.emmisiveTexture
  12834. };
  12835. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12836. }
  12837. if (!material.emissiveFactor) {
  12838. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12839. }
  12840. if (material.pbrMetallicRoughness) {
  12841. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12842. };
  12843. const mr = material.pbrMetallicRoughness;
  12844. if (mr.baseColorTexture) {
  12845. mr.baseColorTexture = { ...mr.baseColorTexture
  12846. };
  12847. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12848. }
  12849. if (mr.metallicRoughnessTexture) {
  12850. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12851. };
  12852. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12853. }
  12854. }
  12855. return material;
  12856. }
  12857. _resolveAccessor(accessor, index) {
  12858. accessor.id = accessor.id || "accessor-".concat(index);
  12859. if (accessor.bufferView !== undefined) {
  12860. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12861. }
  12862. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12863. accessor.components = getSizeFromAccessorType(accessor.type);
  12864. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12865. if (accessor.bufferView) {
  12866. const buffer = accessor.bufferView.buffer;
  12867. const {
  12868. ArrayType,
  12869. byteLength
  12870. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12871. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12872. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12873. if (accessor.bufferView.byteStride) {
  12874. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12875. }
  12876. accessor.value = new ArrayType(cutBuffer);
  12877. }
  12878. return accessor;
  12879. }
  12880. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12881. const result = new Uint8Array(count * bytesPerElement);
  12882. for (let i = 0; i < count; i++) {
  12883. const elementOffset = byteOffset + i * byteStride;
  12884. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12885. }
  12886. return result.buffer;
  12887. }
  12888. _resolveTexture(texture, index) {
  12889. texture.id = texture.id || "texture-".concat(index);
  12890. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  12891. texture.source = this.getImage(texture.source);
  12892. return texture;
  12893. }
  12894. _resolveSampler(sampler, index) {
  12895. sampler.id = sampler.id || "sampler-".concat(index);
  12896. sampler.parameters = {};
  12897. for (const key in sampler) {
  12898. const glEnum = this._enumSamplerParameter(key);
  12899. if (glEnum !== undefined) {
  12900. sampler.parameters[glEnum] = sampler[key];
  12901. }
  12902. }
  12903. return sampler;
  12904. }
  12905. _enumSamplerParameter(key) {
  12906. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  12907. }
  12908. _resolveImage(image, index) {
  12909. image.id = image.id || "image-".concat(index);
  12910. if (image.bufferView !== undefined) {
  12911. image.bufferView = this.getBufferView(image.bufferView);
  12912. }
  12913. const preloadedImage = this.images[index];
  12914. if (preloadedImage) {
  12915. image.image = preloadedImage;
  12916. }
  12917. return image;
  12918. }
  12919. _resolveBufferView(bufferView, index) {
  12920. const bufferIndex = bufferView.buffer;
  12921. const result = {
  12922. id: "bufferView-".concat(index),
  12923. ...bufferView,
  12924. buffer: this.buffers[bufferIndex]
  12925. };
  12926. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  12927. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  12928. if ('byteOffset' in bufferView) {
  12929. byteOffset += bufferView.byteOffset;
  12930. }
  12931. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  12932. return result;
  12933. }
  12934. _resolveCamera(camera, index) {
  12935. camera.id = camera.id || "camera-".concat(index);
  12936. if (camera.perspective) ;
  12937. if (camera.orthographic) ;
  12938. return camera;
  12939. }
  12940. }
  12941. function postProcessGLTF(gltf, options) {
  12942. return new GLTFPostProcessor().postProcess(gltf, options);
  12943. }
  12944. const MAGIC_glTF = 0x676c5446;
  12945. const GLB_FILE_HEADER_SIZE = 12;
  12946. const GLB_CHUNK_HEADER_SIZE = 8;
  12947. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  12948. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  12949. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  12950. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  12951. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  12952. const LE = true;
  12953. function getMagicString(dataView, byteOffset = 0) {
  12954. 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)));
  12955. }
  12956. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  12957. const dataView = new DataView(arrayBuffer);
  12958. const {
  12959. magic = MAGIC_glTF
  12960. } = options;
  12961. const magic1 = dataView.getUint32(byteOffset, false);
  12962. return magic1 === magic || magic1 === MAGIC_glTF;
  12963. }
  12964. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  12965. const dataView = new DataView(arrayBuffer);
  12966. const type = getMagicString(dataView, byteOffset + 0);
  12967. const version = dataView.getUint32(byteOffset + 4, LE);
  12968. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  12969. Object.assign(glb, {
  12970. header: {
  12971. byteOffset,
  12972. byteLength,
  12973. hasBinChunk: false
  12974. },
  12975. type,
  12976. version,
  12977. json: {},
  12978. binChunks: []
  12979. });
  12980. byteOffset += GLB_FILE_HEADER_SIZE;
  12981. switch (glb.version) {
  12982. case 1:
  12983. return parseGLBV1(glb, dataView, byteOffset);
  12984. case 2:
  12985. return parseGLBV2(glb, dataView, byteOffset, options = {});
  12986. default:
  12987. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  12988. }
  12989. }
  12990. function parseGLBV1(glb, dataView, byteOffset) {
  12991. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  12992. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  12993. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  12994. byteOffset += GLB_CHUNK_HEADER_SIZE;
  12995. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  12996. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  12997. byteOffset += contentLength;
  12998. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  12999. return byteOffset;
  13000. }
  13001. function parseGLBV2(glb, dataView, byteOffset, options) {
  13002. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13003. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13004. return byteOffset + glb.header.byteLength;
  13005. }
  13006. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13007. while (byteOffset + 8 <= glb.header.byteLength) {
  13008. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13009. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13010. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13011. switch (chunkFormat) {
  13012. case GLB_CHUNK_TYPE_JSON:
  13013. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13014. break;
  13015. case GLB_CHUNK_TYPE_BIN:
  13016. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13017. break;
  13018. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13019. if (!options.strict) {
  13020. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13021. }
  13022. break;
  13023. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13024. if (!options.strict) {
  13025. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13026. }
  13027. break;
  13028. }
  13029. byteOffset += padToNBytes(chunkLength, 4);
  13030. }
  13031. return byteOffset;
  13032. }
  13033. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13034. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13035. const textDecoder = new TextDecoder('utf8');
  13036. const jsonText = textDecoder.decode(jsonChunk);
  13037. glb.json = JSON.parse(jsonText);
  13038. return padToNBytes(chunkLength, 4);
  13039. }
  13040. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13041. glb.header.hasBinChunk = true;
  13042. glb.binChunks.push({
  13043. byteOffset,
  13044. byteLength: chunkLength,
  13045. arrayBuffer: dataView.buffer
  13046. });
  13047. return padToNBytes(chunkLength, 4);
  13048. }
  13049. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13050. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13051. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13052. normalizeGLTFV1(gltf, {
  13053. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13054. });
  13055. preprocessExtensions(gltf, options, context);
  13056. const promises = [];
  13057. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13058. await loadBuffers(gltf, options, context);
  13059. }
  13060. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13061. const promise = loadImages(gltf, options, context);
  13062. promises.push(promise);
  13063. }
  13064. const promise = decodeExtensions(gltf, options, context);
  13065. promises.push(promise);
  13066. await Promise.all(promises);
  13067. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13068. }
  13069. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13070. if (options.uri) {
  13071. gltf.baseUri = options.uri;
  13072. }
  13073. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13074. const textDecoder = new TextDecoder();
  13075. data = textDecoder.decode(data);
  13076. }
  13077. if (typeof data === 'string') {
  13078. gltf.json = parseJSON(data);
  13079. } else if (data instanceof ArrayBuffer) {
  13080. const glb = {};
  13081. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13082. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13083. gltf._glb = glb;
  13084. gltf.json = glb.json;
  13085. } else {
  13086. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13087. }
  13088. const buffers = gltf.json.buffers || [];
  13089. gltf.buffers = new Array(buffers.length).fill(null);
  13090. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13091. const {
  13092. binChunks
  13093. } = gltf._glb;
  13094. gltf.buffers[0] = {
  13095. arrayBuffer: binChunks[0].arrayBuffer,
  13096. byteOffset: binChunks[0].byteOffset,
  13097. byteLength: binChunks[0].byteLength
  13098. };
  13099. }
  13100. const images = gltf.json.images || [];
  13101. gltf.images = new Array(images.length).fill({});
  13102. }
  13103. async function loadBuffers(gltf, options, context) {
  13104. const buffers = gltf.json.buffers || [];
  13105. for (let i = 0; i < buffers.length; ++i) {
  13106. const buffer = buffers[i];
  13107. if (buffer.uri) {
  13108. var _context$fetch, _response$arrayBuffer;
  13109. const {
  13110. fetch
  13111. } = context;
  13112. assert$1(fetch);
  13113. const uri = resolveUrl(buffer.uri, options);
  13114. 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));
  13115. 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));
  13116. gltf.buffers[i] = {
  13117. arrayBuffer,
  13118. byteOffset: 0,
  13119. byteLength: arrayBuffer.byteLength
  13120. };
  13121. delete buffer.uri;
  13122. }
  13123. }
  13124. }
  13125. async function loadImages(gltf, options, context) {
  13126. const imageIndices = getReferencesImageIndices(gltf);
  13127. const images = gltf.json.images || [];
  13128. const promises = [];
  13129. for (const imageIndex of imageIndices) {
  13130. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13131. }
  13132. return await Promise.all(promises);
  13133. }
  13134. function getReferencesImageIndices(gltf) {
  13135. const imageIndices = new Set();
  13136. const textures = gltf.json.textures || [];
  13137. for (const texture of textures) {
  13138. if (texture.source !== undefined) {
  13139. imageIndices.add(texture.source);
  13140. }
  13141. }
  13142. return Array.from(imageIndices).sort();
  13143. }
  13144. async function loadImage(gltf, image, index, options, context) {
  13145. const {
  13146. fetch,
  13147. parse
  13148. } = context;
  13149. let arrayBuffer;
  13150. if (image.uri) {
  13151. const uri = resolveUrl(image.uri, options);
  13152. const response = await fetch(uri);
  13153. arrayBuffer = await response.arrayBuffer();
  13154. }
  13155. if (Number.isFinite(image.bufferView)) {
  13156. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13157. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13158. }
  13159. assert$1(arrayBuffer, 'glTF image has no data');
  13160. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13161. mimeType: image.mimeType,
  13162. basis: options.basis || {
  13163. format: selectSupportedBasisFormat()
  13164. }
  13165. }, context);
  13166. if (parsedImage && parsedImage[0]) {
  13167. parsedImage = {
  13168. compressed: true,
  13169. mipmaps: false,
  13170. width: parsedImage[0].width,
  13171. height: parsedImage[0].height,
  13172. data: parsedImage
  13173. };
  13174. }
  13175. gltf.images = gltf.images || [];
  13176. gltf.images[index] = parsedImage;
  13177. }
  13178. const GLTFLoader = {
  13179. name: 'glTF',
  13180. id: 'gltf',
  13181. module: 'gltf',
  13182. version: VERSION$3,
  13183. extensions: ['gltf', 'glb'],
  13184. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13185. text: true,
  13186. binary: true,
  13187. tests: ['glTF'],
  13188. parse: parse$1,
  13189. options: {
  13190. gltf: {
  13191. normalize: true,
  13192. loadBuffers: true,
  13193. loadImages: true,
  13194. decompressMeshes: true,
  13195. postProcess: true
  13196. },
  13197. log: console
  13198. },
  13199. deprecatedOptions: {
  13200. fetchImages: 'gltf.loadImages',
  13201. createImages: 'gltf.loadImages',
  13202. decompress: 'gltf.decompressMeshes',
  13203. postProcess: 'gltf.postProcess',
  13204. gltf: {
  13205. decompress: 'gltf.decompressMeshes'
  13206. }
  13207. }
  13208. };
  13209. async function parse$1(arrayBuffer, options = {}, context) {
  13210. options = { ...GLTFLoader.options,
  13211. ...options
  13212. };
  13213. options.gltf = { ...GLTFLoader.options.gltf,
  13214. ...options.gltf
  13215. };
  13216. const {
  13217. byteOffset = 0
  13218. } = options;
  13219. const gltf = {};
  13220. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13221. }
  13222. const GLTF_FORMAT = {
  13223. URI: 0,
  13224. EMBEDDED: 1
  13225. };
  13226. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13227. tile.rotateYtoZ = true;
  13228. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13229. if (gltfByteLength === 0) {
  13230. throw new Error('glTF byte length must be greater than 0.');
  13231. }
  13232. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13233. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13234. tile.gltfByteOffset = 0;
  13235. tile.gltfByteLength = gltfByteLength;
  13236. if (byteOffset % 4 === 0) ; else {
  13237. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13238. }
  13239. return tile.byteOffset + tile.byteLength;
  13240. }
  13241. async function extractGLTF(tile, gltfFormat, options, context) {
  13242. const tile3DOptions = options['3d-tiles'] || {};
  13243. extractGLTFBufferOrURL(tile, gltfFormat);
  13244. if (tile3DOptions.loadGLTF) {
  13245. const {
  13246. parse,
  13247. fetch
  13248. } = context;
  13249. if (tile.gltfUrl) {
  13250. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13251. tile.gltfByteOffset = 0;
  13252. }
  13253. if (tile.gltfArrayBuffer) {
  13254. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13255. delete tile.gltfArrayBuffer;
  13256. delete tile.gltfByteOffset;
  13257. delete tile.gltfByteLength;
  13258. }
  13259. }
  13260. }
  13261. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13262. switch (gltfFormat) {
  13263. case GLTF_FORMAT.URI:
  13264. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13265. const textDecoder = new TextDecoder();
  13266. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13267. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13268. delete tile.gltfArrayBuffer;
  13269. delete tile.gltfByteOffset;
  13270. delete tile.gltfByteLength;
  13271. break;
  13272. case GLTF_FORMAT.EMBEDDED:
  13273. break;
  13274. default:
  13275. throw new Error('b3dm: Illegal glTF format field');
  13276. }
  13277. }
  13278. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13279. var _tile$gltf;
  13280. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13281. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13282. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13283. if (extensions && extensions.CESIUM_RTC) {
  13284. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13285. }
  13286. return byteOffset;
  13287. }
  13288. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13289. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13290. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13291. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13292. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13293. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13294. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13295. return byteOffset;
  13296. }
  13297. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13298. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13299. await extractGLTF(tile, tile.gltfFormat, options, context);
  13300. return byteOffset;
  13301. }
  13302. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13303. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13304. if (tile.version !== 1) {
  13305. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13306. }
  13307. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13308. const view = new DataView(arrayBuffer);
  13309. tile.gltfFormat = view.getUint32(byteOffset, true);
  13310. byteOffset += 4;
  13311. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13312. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13313. if (tile.featureTableJsonByteLength === 0) {
  13314. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13315. }
  13316. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13317. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13318. featureTable.featuresLength = instancesLength;
  13319. if (!Number.isFinite(instancesLength)) {
  13320. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13321. }
  13322. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13323. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13324. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13325. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13326. return byteOffset;
  13327. }
  13328. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13329. const collectionOptions = {
  13330. instances: new Array(instancesLength),
  13331. batchTable: tile._batchTable,
  13332. cull: false,
  13333. url: undefined,
  13334. gltf: undefined,
  13335. basePath: undefined,
  13336. incrementallyLoadTextures: false,
  13337. forwardAxis: [1, 0, 0]
  13338. };
  13339. const instances = collectionOptions.instances;
  13340. const instancePosition = new Vector3();
  13341. new Vector3();
  13342. new Vector3();
  13343. new Vector3();
  13344. const instanceRotation = new Matrix3();
  13345. const instanceQuaternion = new Quaternion();
  13346. const instanceScale = new Vector3();
  13347. const instanceTranslationRotationScale = {};
  13348. const instanceTransform = new Matrix4();
  13349. const scratch1 = [];
  13350. const scratch2 = [];
  13351. const scratchVector1 = new Vector3();
  13352. const scratchVector2 = new Vector3();
  13353. for (let i = 0; i < instancesLength; i++) {
  13354. let position;
  13355. if (featureTable.hasProperty('POSITION')) {
  13356. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13357. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13358. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13359. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13360. if (!quantizedVolumeOffset) {
  13361. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13362. }
  13363. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13364. if (!quantizedVolumeScale) {
  13365. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13366. }
  13367. const MAX_UNSIGNED_SHORT = 65535.0;
  13368. for (let j = 0; j < 3; j++) {
  13369. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13370. }
  13371. }
  13372. if (!position) {
  13373. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13374. }
  13375. instancePosition.copy(position);
  13376. instanceTranslationRotationScale.translation = instancePosition;
  13377. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13378. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13379. if (tile.normalUp) {
  13380. if (!tile.normalRight) {
  13381. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13382. }
  13383. tile.hasCustomOrientation = true;
  13384. } else {
  13385. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13386. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13387. if (tile.octNormalUp) {
  13388. if (!tile.octNormalRight) {
  13389. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13390. }
  13391. throw new Error('i3dm: oct-encoded orientation not implemented');
  13392. } else if (tile.eastNorthUp) {
  13393. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13394. instanceTransform.getRotationMatrix3(instanceRotation);
  13395. } else {
  13396. instanceRotation.identity();
  13397. }
  13398. }
  13399. instanceQuaternion.fromMatrix3(instanceRotation);
  13400. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13401. instanceScale.set(1.0, 1.0, 1.0);
  13402. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13403. if (Number.isFinite(scale)) {
  13404. instanceScale.multiplyByScalar(scale);
  13405. }
  13406. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13407. if (nonUniformScale) {
  13408. instanceScale.scale(nonUniformScale);
  13409. }
  13410. instanceTranslationRotationScale.scale = instanceScale;
  13411. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13412. if (batchId === undefined) {
  13413. batchId = i;
  13414. }
  13415. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13416. instanceTransform.identity();
  13417. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13418. instanceTransform.multiplyRight(rotationMatrix);
  13419. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13420. const modelMatrix = instanceTransform.clone();
  13421. instances[i] = {
  13422. modelMatrix,
  13423. batchId
  13424. };
  13425. }
  13426. tile.instances = instances;
  13427. }
  13428. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13429. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13430. const view = new DataView(arrayBuffer);
  13431. tile.tilesLength = view.getUint32(byteOffset, true);
  13432. byteOffset += 4;
  13433. tile.tiles = [];
  13434. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13435. const subtile = {};
  13436. tile.tiles.push(subtile);
  13437. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13438. }
  13439. return byteOffset;
  13440. }
  13441. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13442. tile.rotateYtoZ = true;
  13443. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13444. const {
  13445. parse
  13446. } = context;
  13447. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13448. }
  13449. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13450. tile.byteOffset = byteOffset;
  13451. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13452. switch (tile.type) {
  13453. case TILE3D_TYPE.COMPOSITE:
  13454. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13455. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13456. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13457. case TILE3D_TYPE.GLTF:
  13458. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13459. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13460. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13461. case TILE3D_TYPE.POINT_CLOUD:
  13462. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13463. default:
  13464. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13465. }
  13466. }
  13467. const SUBTREE_FILE_MAGIC = 0x74627573;
  13468. const SUBTREE_FILE_VERSION = 1;
  13469. async function parse3DTilesSubtree(data) {
  13470. const magic = new Uint32Array(data.slice(0, 4));
  13471. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13472. throw new Error('Wrong subtree file magic number');
  13473. }
  13474. const version = new Uint32Array(data.slice(4, 8));
  13475. if (version[0] !== SUBTREE_FILE_VERSION) {
  13476. throw new Error('Wrong subtree file verson, must be 1');
  13477. }
  13478. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13479. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13480. const textDecoder = new TextDecoder('utf8');
  13481. const string = textDecoder.decode(stringAttribute);
  13482. const subtree = JSON.parse(string);
  13483. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13484. let internalBinaryBuffer = new ArrayBuffer(0);
  13485. if (binaryByteLength) {
  13486. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13487. }
  13488. if ('bufferView' in subtree.tileAvailability) {
  13489. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13490. }
  13491. if ('bufferView' in subtree.contentAvailability) {
  13492. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13493. }
  13494. if ('bufferView' in subtree.childSubtreeAvailability) {
  13495. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13496. }
  13497. return subtree;
  13498. }
  13499. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13500. const bufferViewIndex = subtree[name].bufferView;
  13501. const bufferView = subtree.bufferViews[bufferViewIndex];
  13502. const buffer = subtree.buffers[bufferView.buffer];
  13503. if (buffer.uri) {
  13504. const response = await fetchFile(buffer.uri);
  13505. const data = await response.arrayBuffer();
  13506. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13507. }
  13508. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13509. }
  13510. function parseUint64Value(buffer) {
  13511. const dataView = new DataView(buffer);
  13512. const left = dataView.getUint32(0, true);
  13513. const right = dataView.getUint32(4, true);
  13514. return left + 2 ** 32 * right;
  13515. }
  13516. const Tile3DSubtreeLoader = {
  13517. id: '3d-tiles-subtree',
  13518. name: '3D Tiles Subtree',
  13519. module: '3d-tiles',
  13520. version: VERSION$5,
  13521. extensions: ['subtree'],
  13522. mimeTypes: ['application/octet-stream'],
  13523. tests: ['subtree'],
  13524. parse: parse3DTilesSubtree,
  13525. options: {}
  13526. };
  13527. const QUADTREE_DEVISION_COUNT = 4;
  13528. const OCTREE_DEVISION_COUNT = 8;
  13529. const SUBDIVISION_COUNT_MAP = {
  13530. QUADTREE: QUADTREE_DEVISION_COUNT,
  13531. OCTREE: OCTREE_DEVISION_COUNT
  13532. };
  13533. async function parseImplicitTiles(subtree, options, parentData = {
  13534. mortonIndex: 0,
  13535. x: 0,
  13536. y: 0,
  13537. z: 0
  13538. }, childIndex = 0, level = 0, globalData = {
  13539. level: 0,
  13540. mortonIndex: 0,
  13541. x: 0,
  13542. y: 0,
  13543. z: 0
  13544. }) {
  13545. const {
  13546. subdivisionScheme,
  13547. subtreeLevels,
  13548. maximumLevel,
  13549. contentUrlTemplate,
  13550. subtreesUriTemplate,
  13551. basePath
  13552. } = options;
  13553. const tile = {
  13554. children: [],
  13555. lodMetricValue: 0,
  13556. contentUrl: ''
  13557. };
  13558. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13559. const childX = childIndex & 0b01;
  13560. const childY = childIndex >> 1 & 0b01;
  13561. const childZ = childIndex >> 2 & 0b01;
  13562. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13563. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13564. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13565. let childTileX = concatBits(parentData.x, childX);
  13566. let childTileY = concatBits(parentData.y, childY);
  13567. let childTileZ = concatBits(parentData.z, childZ);
  13568. let isChildSubtreeAvailable = false;
  13569. if (level + 1 > subtreeLevels) {
  13570. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13571. }
  13572. const x = concatBits(globalData.x, childTileX);
  13573. const y = concatBits(globalData.y, childTileY);
  13574. const z = concatBits(globalData.z, childTileZ);
  13575. const lev = level + globalData.level;
  13576. if (isChildSubtreeAvailable) {
  13577. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13578. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13579. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13580. subtree = childSubtree;
  13581. globalData.mortonIndex = childTileMortonIndex;
  13582. globalData.x = childTileX;
  13583. globalData.y = childTileY;
  13584. globalData.z = childTileZ;
  13585. globalData.level = level;
  13586. childTileMortonIndex = 0;
  13587. tileAvailabilityIndex = 0;
  13588. childTileX = 0;
  13589. childTileY = 0;
  13590. childTileZ = 0;
  13591. level = 0;
  13592. }
  13593. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13594. if (!isTileAvailable || level > maximumLevel) {
  13595. return tile;
  13596. }
  13597. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13598. if (isContentAvailable) {
  13599. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13600. }
  13601. const childTileLevel = level + 1;
  13602. const pData = {
  13603. mortonIndex: childTileMortonIndex,
  13604. x: childTileX,
  13605. y: childTileY,
  13606. z: childTileZ
  13607. };
  13608. for (let index = 0; index < childrenPerTile; index++) {
  13609. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13610. if (currentTile.contentUrl || currentTile.children.length) {
  13611. const globalLevel = lev + 1;
  13612. const childCoordinates = {
  13613. childTileX,
  13614. childTileY,
  13615. childTileZ
  13616. };
  13617. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13618. tile.children.push(formattedTile);
  13619. }
  13620. }
  13621. return tile;
  13622. }
  13623. function getAvailabilityResult(availabilityData, index) {
  13624. if ('constant' in availabilityData) {
  13625. return Boolean(availabilityData.constant);
  13626. }
  13627. if (availabilityData.explicitBitstream) {
  13628. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13629. }
  13630. return false;
  13631. }
  13632. function formatTileData(tile, level, childCoordinates, options) {
  13633. const {
  13634. basePath,
  13635. refine,
  13636. getRefine,
  13637. lodMetricType,
  13638. getTileType,
  13639. rootLodMetricValue,
  13640. rootBoundingVolume
  13641. } = options;
  13642. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13643. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13644. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13645. return {
  13646. children: tile.children,
  13647. contentUrl: tile.contentUrl,
  13648. content: {
  13649. uri
  13650. },
  13651. id: tile.contentUrl,
  13652. refine: getRefine(refine),
  13653. type: getTileType(tile),
  13654. lodMetricType,
  13655. lodMetricValue,
  13656. boundingVolume
  13657. };
  13658. }
  13659. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13660. if (rootBoundingVolume.region) {
  13661. const {
  13662. childTileX,
  13663. childTileY,
  13664. childTileZ
  13665. } = childCoordinates;
  13666. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13667. const boundingVolumesCount = 2 ** level;
  13668. const sizeX = (east - west) / boundingVolumesCount;
  13669. const sizeY = (north - south) / boundingVolumesCount;
  13670. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13671. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13672. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13673. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13674. return {
  13675. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13676. };
  13677. }
  13678. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13679. return null;
  13680. }
  13681. function concatBits(first, second) {
  13682. return parseInt(first.toString(2) + second.toString(2), 2);
  13683. }
  13684. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13685. const mapUrl = generateMapUrl({
  13686. level,
  13687. x,
  13688. y,
  13689. z
  13690. });
  13691. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13692. }
  13693. function generateMapUrl(items) {
  13694. const mapUrl = {};
  13695. for (const key in items) {
  13696. mapUrl["{".concat(key, "}")] = items[key];
  13697. }
  13698. return mapUrl;
  13699. }
  13700. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13701. const byteIndex = Math.floor(availabilityIndex / 8);
  13702. const bitIndex = availabilityIndex % 8;
  13703. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13704. return bitValue === 1;
  13705. }
  13706. function getTileType(tile) {
  13707. if (!tile.contentUrl) {
  13708. return TILE_TYPE.EMPTY;
  13709. }
  13710. const contentUrl = tile.contentUrl;
  13711. const fileExtension = contentUrl.split('.').pop();
  13712. switch (fileExtension) {
  13713. case 'pnts':
  13714. return TILE_TYPE.POINTCLOUD;
  13715. case 'i3dm':
  13716. case 'b3dm':
  13717. case 'glb':
  13718. case 'gltf':
  13719. return TILE_TYPE.SCENEGRAPH;
  13720. default:
  13721. return fileExtension;
  13722. }
  13723. }
  13724. function getRefine(refine) {
  13725. switch (refine) {
  13726. case 'REPLACE':
  13727. case 'replace':
  13728. return TILE_REFINEMENT.REPLACE;
  13729. case 'ADD':
  13730. case 'add':
  13731. return TILE_REFINEMENT.ADD;
  13732. default:
  13733. return refine;
  13734. }
  13735. }
  13736. function normalizeTileData(tile, options) {
  13737. if (!tile) {
  13738. return null;
  13739. }
  13740. if (tile.content) {
  13741. const contentUri = tile.content.uri || tile.content.url;
  13742. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13743. }
  13744. tile.id = tile.contentUrl;
  13745. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13746. tile.lodMetricValue = tile.geometricError;
  13747. tile.transformMatrix = tile.transform;
  13748. tile.type = getTileType(tile);
  13749. tile.refine = getRefine(tile.refine);
  13750. return tile;
  13751. }
  13752. function normalizeTileHeaders(tileset) {
  13753. const basePath = tileset.basePath;
  13754. const root = normalizeTileData(tileset.root, tileset);
  13755. const stack = [];
  13756. stack.push(root);
  13757. while (stack.length > 0) {
  13758. const tile = stack.pop() || {};
  13759. const children = tile.children || [];
  13760. for (const childHeader of children) {
  13761. normalizeTileData(childHeader, {
  13762. basePath
  13763. });
  13764. stack.push(childHeader);
  13765. }
  13766. }
  13767. return root;
  13768. }
  13769. async function normalizeImplicitTileHeaders(tileset) {
  13770. if (!tileset.root) {
  13771. return null;
  13772. }
  13773. const basePath = tileset.basePath;
  13774. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13775. const {
  13776. subdivisionScheme,
  13777. maximumLevel,
  13778. subtreeLevels,
  13779. subtrees: {
  13780. uri: subtreesUriTemplate
  13781. }
  13782. } = implicitTilingExtension;
  13783. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13784. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13785. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13786. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13787. const refine = tileset.root.refine;
  13788. const rootLodMetricValue = tileset.root.geometricError;
  13789. const rootBoundingVolume = tileset.root.boundingVolume;
  13790. const options = {
  13791. contentUrlTemplate,
  13792. subtreesUriTemplate,
  13793. subdivisionScheme,
  13794. subtreeLevels,
  13795. maximumLevel,
  13796. refine,
  13797. basePath,
  13798. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13799. rootLodMetricValue,
  13800. rootBoundingVolume,
  13801. getTileType,
  13802. getRefine
  13803. };
  13804. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13805. }
  13806. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13807. if (!tile) {
  13808. return null;
  13809. }
  13810. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13811. tile.lodMetricValue = tile.geometricError;
  13812. tile.transformMatrix = tile.transform;
  13813. const {
  13814. children,
  13815. contentUrl
  13816. } = await parseImplicitTiles(rootSubtree, options);
  13817. if (contentUrl) {
  13818. tile.contentUrl = contentUrl;
  13819. tile.content = {
  13820. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13821. };
  13822. }
  13823. tile.refine = getRefine(tile.refine);
  13824. tile.type = getTileType(tile);
  13825. tile.children = children;
  13826. tile.id = tile.contentUrl;
  13827. return tile;
  13828. }
  13829. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13830. const Tiles3DLoader = {
  13831. id: '3d-tiles',
  13832. name: '3D Tiles',
  13833. module: '3d-tiles',
  13834. version: VERSION$5,
  13835. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13836. mimeTypes: ['application/octet-stream'],
  13837. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13838. parse,
  13839. options: {
  13840. '3d-tiles': {
  13841. loadGLTF: true,
  13842. decodeQuantizedPositions: false,
  13843. isTileset: 'auto',
  13844. assetGltfUpAxis: null
  13845. }
  13846. }
  13847. };
  13848. function getBaseUri(tileset) {
  13849. return dirname(tileset.url);
  13850. }
  13851. async function parseTile(arrayBuffer, options, context) {
  13852. const tile = {
  13853. content: {
  13854. featureIds: null
  13855. }
  13856. };
  13857. const byteOffset = 0;
  13858. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13859. return tile.content;
  13860. }
  13861. async function parseTileset(data, options, context) {
  13862. var _tilesetJson$root;
  13863. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13864. tilesetJson.loader = options.loader || Tiles3DLoader;
  13865. tilesetJson.url = context.url;
  13866. tilesetJson.basePath = getBaseUri(tilesetJson);
  13867. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13868. tilesetJson.type = TILESET_TYPE.TILES3D;
  13869. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13870. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13871. return tilesetJson;
  13872. }
  13873. async function parse(data, options, context) {
  13874. const loaderOptions = options['3d-tiles'] || {};
  13875. let isTileset;
  13876. if (loaderOptions.isTileset === 'auto') {
  13877. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13878. } else {
  13879. isTileset = loaderOptions.isTileset;
  13880. }
  13881. if (isTileset) {
  13882. data = await parseTileset(data, options, context);
  13883. } else {
  13884. data = await parseTile(data, options, context);
  13885. }
  13886. return data;
  13887. }
  13888. function hasImplicitTilingExtension(tilesetJson) {
  13889. var _tilesetJson$extensio, _tilesetJson$extensio2;
  13890. 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));
  13891. }
  13892. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  13893. async function getIonTilesetMetadata(accessToken, assetId) {
  13894. if (!assetId) {
  13895. const assets = await getIonAssets(accessToken);
  13896. for (const item of assets.items) {
  13897. if (item.type === '3DTILES') {
  13898. assetId = item.id;
  13899. }
  13900. }
  13901. }
  13902. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  13903. const {
  13904. type,
  13905. url
  13906. } = ionAssetMetadata;
  13907. assert$7(type === '3DTILES' && url);
  13908. ionAssetMetadata.headers = {
  13909. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  13910. };
  13911. return ionAssetMetadata;
  13912. }
  13913. async function getIonAssets(accessToken) {
  13914. assert$7(accessToken);
  13915. const url = CESIUM_ION_URL;
  13916. const headers = {
  13917. Authorization: "Bearer ".concat(accessToken)
  13918. };
  13919. const response = await fetchFile(url, {
  13920. fetch: {
  13921. headers
  13922. }
  13923. });
  13924. if (!response.ok) {
  13925. throw new Error(response.statusText);
  13926. }
  13927. return await response.json();
  13928. }
  13929. async function getIonAssetMetadata(accessToken, assetId) {
  13930. assert$7(accessToken, assetId);
  13931. const headers = {
  13932. Authorization: "Bearer ".concat(accessToken)
  13933. };
  13934. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  13935. let response = await fetchFile("".concat(url), {
  13936. fetch: {
  13937. headers
  13938. }
  13939. });
  13940. if (!response.ok) {
  13941. throw new Error(response.statusText);
  13942. }
  13943. let metadata = await response.json();
  13944. response = await fetchFile("".concat(url, "/endpoint"), {
  13945. fetch: {
  13946. headers
  13947. }
  13948. });
  13949. if (!response.ok) {
  13950. throw new Error(response.statusText);
  13951. }
  13952. const tilesetInfo = await response.json();
  13953. metadata = { ...metadata,
  13954. ...tilesetInfo
  13955. };
  13956. return metadata;
  13957. }
  13958. async function preload(url, options = {}) {
  13959. options = options['cesium-ion'] || {};
  13960. const {
  13961. accessToken
  13962. } = options;
  13963. let assetId = options.assetId;
  13964. if (!Number.isFinite(assetId)) {
  13965. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  13966. assetId = matched && matched[1];
  13967. }
  13968. return getIonTilesetMetadata(accessToken, assetId);
  13969. }
  13970. const CesiumIonLoader = { ...Tiles3DLoader,
  13971. id: 'cesium-ion',
  13972. name: 'Cesium Ion',
  13973. preload,
  13974. parse: async (data, options, context) => {
  13975. options = { ...options
  13976. };
  13977. options['3d-tiles'] = options['cesium-ion'];
  13978. options.loader = CesiumIonLoader;
  13979. return Tiles3DLoader.parse(data, options, context);
  13980. },
  13981. options: {
  13982. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  13983. accessToken: null
  13984. }
  13985. }
  13986. };
  13987. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  13988. function generateGradientTexture(gradient) {
  13989. const size = 64;
  13990. // create canvas
  13991. const canvas = document.createElement('canvas');
  13992. canvas.width = size;
  13993. canvas.height = size;
  13994. // get context
  13995. const context = canvas.getContext('2d');
  13996. // draw gradient
  13997. context.rect(0, 0, size, size);
  13998. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  13999. for (let i = 0; i < gradient.length; i++) {
  14000. const step = gradient[i];
  14001. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14002. }
  14003. context.fillStyle = ctxGradient;
  14004. context.fill();
  14005. //let texture = new THREE.Texture(canvas);
  14006. const texture = new CanvasTexture(canvas);
  14007. texture.needsUpdate = true;
  14008. texture.minFilter = LinearFilter;
  14009. texture.wrapS = RepeatWrapping;
  14010. texture.wrapT = RepeatWrapping;
  14011. texture.repeat.set(2, 2);
  14012. // textureImage = texture.image;
  14013. return texture;
  14014. }
  14015. function getCameraFrustum(camera) {
  14016. camera.updateMatrix(); // make sure camera's local matrix is updated
  14017. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14018. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14019. const frustum = new Frustum();
  14020. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14021. return frustum;
  14022. }
  14023. function loadersPlaneToMesh(plane) {
  14024. const group = new Group();
  14025. // Create a basic rectangle geometry from math.gl plane
  14026. const planeGeometry = new PlaneGeometry(10, 5);
  14027. // Align the geometry to the plane
  14028. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14029. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14030. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14031. planeGeometry.lookAt(focalPoint);
  14032. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14033. // Edges
  14034. /*
  14035. const edges = new EdgesGeometry(planeGeometry)
  14036. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14037. //plane
  14038. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14039. const mesh = new Mesh(planeGeometry, material);
  14040. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14041. group.add(arrowHelper);
  14042. group.add(mesh);
  14043. return group;
  14044. }
  14045. function loadersBoundingBoxToMesh(tile) {
  14046. // Create a basic rectangle geometry from math.gl half-axes
  14047. const { boundingVolume } = tile;
  14048. let redColor = 0;
  14049. if (tile.content) {
  14050. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14051. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14052. }
  14053. const boxColor = new Color(redColor, 1.0, 0.0);
  14054. const boxGeometry = new BoxGeometry(1, 1, 1);
  14055. const boxTransform = new Matrix4$1();
  14056. if (boundingVolume.halfAxes) {
  14057. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  14058. }
  14059. else if (boundingVolume.radius) {
  14060. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  14061. }
  14062. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundingVolume.center)) //add
  14063. boxGeometry.applyMatrix4(boxTransform);
  14064. const edges = new EdgesGeometry(boxGeometry);
  14065. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14066. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14067. dispPlane.matrixAutoUpdate = false //add
  14068. /* if(tile.content.byteLength == void 0){
  14069. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14070. dispPlane.updateMatrixWorld = (a,b)=>{
  14071. oldUpdate(a,b)
  14072. }
  14073. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14074. dispPlane.updateMatrix = (a,b)=>{
  14075. oldU(a,b)
  14076. }
  14077. } */
  14078. return dispPlane;
  14079. }
  14080. function getMatrix4FromHalfAxes(halfAxes) {
  14081. const m = halfAxes;
  14082. const rotateMatrix = new Matrix4$1().fromArray([
  14083. m[0] * 2,
  14084. m[1] * 2,
  14085. m[2] * 2,
  14086. 0,
  14087. m[3] * 2,
  14088. m[4] * 2,
  14089. m[5] * 2,
  14090. 0,
  14091. m[6] * 2,
  14092. m[7] * 2,
  14093. m[8] * 2,
  14094. 0,
  14095. 0,
  14096. 0,
  14097. 0,
  14098. 1,
  14099. ]);
  14100. return rotateMatrix;
  14101. }
  14102. /*
  14103. * from https://github.com/tentone/geo-three
  14104. * Tree-shaking did not work, probably due to static class methods
  14105. */
  14106. function datumsToSpherical(latitude, longitude) {
  14107. const EARTH_RADIUS = 6378137;
  14108. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14109. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14110. const x = longitude * EARTH_ORIGIN / 180.0;
  14111. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14112. y = y * EARTH_ORIGIN / 180.0;
  14113. return new Vector2$1(x, y);
  14114. }
  14115. const Gradients = {
  14116. // From chroma spectral http://gka.github.io/chroma.js/
  14117. SPECTRAL: [
  14118. [0, new Color(0.3686, 0.3098, 0.6353)],
  14119. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14120. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14121. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14122. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14123. [0.5, new Color(1.0, 1.0, 0.749)],
  14124. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14125. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14126. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14127. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14128. [1, new Color(0.6196, 0.0039, 0.2588)],
  14129. ],
  14130. PLASMA: [
  14131. [0.0, new Color(0.241, 0.015, 0.61)],
  14132. [0.1, new Color(0.387, 0.001, 0.654)],
  14133. [0.2, new Color(0.524, 0.025, 0.653)],
  14134. [0.3, new Color(0.651, 0.125, 0.596)],
  14135. [0.4, new Color(0.752, 0.227, 0.513)],
  14136. [0.5, new Color(0.837, 0.329, 0.431)],
  14137. [0.6, new Color(0.907, 0.435, 0.353)],
  14138. [0.7, new Color(0.963, 0.554, 0.272)],
  14139. [0.8, new Color(0.992, 0.681, 0.195)],
  14140. [0.9, new Color(0.987, 0.822, 0.144)],
  14141. [1.0, new Color(0.94, 0.975, 0.131)],
  14142. ],
  14143. YELLOW_GREEN: [
  14144. [0, new Color(0.1647, 0.2824, 0.3451)],
  14145. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14146. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14147. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14148. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14149. [0.5, new Color(0.137, 0.665, 0.5614)],
  14150. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14151. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14152. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14153. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14154. [1, new Color(0.9804, 0.9804, 0.4314)],
  14155. ],
  14156. VIRIDIS: [
  14157. [0.0, new Color(0.267, 0.005, 0.329)],
  14158. [0.1, new Color(0.283, 0.141, 0.458)],
  14159. [0.2, new Color(0.254, 0.265, 0.53)],
  14160. [0.3, new Color(0.207, 0.372, 0.553)],
  14161. [0.4, new Color(0.164, 0.471, 0.558)],
  14162. [0.5, new Color(0.128, 0.567, 0.551)],
  14163. [0.6, new Color(0.135, 0.659, 0.518)],
  14164. [0.7, new Color(0.267, 0.749, 0.441)],
  14165. [0.8, new Color(0.478, 0.821, 0.318)],
  14166. [0.9, new Color(0.741, 0.873, 0.15)],
  14167. [1.0, new Color(0.993, 0.906, 0.144)],
  14168. ],
  14169. INFERNO: [
  14170. [0.0, new Color(0.077, 0.042, 0.206)],
  14171. [0.1, new Color(0.225, 0.036, 0.388)],
  14172. [0.2, new Color(0.373, 0.074, 0.432)],
  14173. [0.3, new Color(0.522, 0.128, 0.42)],
  14174. [0.4, new Color(0.665, 0.182, 0.37)],
  14175. [0.5, new Color(0.797, 0.255, 0.287)],
  14176. [0.6, new Color(0.902, 0.364, 0.184)],
  14177. [0.7, new Color(0.969, 0.516, 0.063)],
  14178. [0.8, new Color(0.988, 0.683, 0.072)],
  14179. [0.9, new Color(0.961, 0.859, 0.298)],
  14180. [1.0, new Color(0.988, 0.998, 0.645)],
  14181. ],
  14182. GRAYSCALE: [
  14183. [0, new Color(0, 0, 0)],
  14184. [1, new Color(1, 1, 1)],
  14185. ],
  14186. // 16 samples of the TURBU color scheme
  14187. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14188. // original file licensed under Apache-2.0
  14189. TURBO: [
  14190. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14191. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14192. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14193. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14194. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14195. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14196. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14197. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14198. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14199. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14200. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14201. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14202. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14203. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14204. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14205. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14206. ],
  14207. RAINBOW: [
  14208. [0, new Color(0.278, 0, 0.714)],
  14209. [1 / 6, new Color(0, 0, 1)],
  14210. [2 / 6, new Color(0, 1, 1)],
  14211. [3 / 6, new Color(0, 1, 0)],
  14212. [4 / 6, new Color(1, 1, 0)],
  14213. [5 / 6, new Color(1, 0.64, 0)],
  14214. [1, new Color(1, 0, 0)],
  14215. ],
  14216. CONTOUR: [
  14217. [0.0, new Color(0, 0, 0)],
  14218. [0.03, new Color(0, 0, 0)],
  14219. [0.04, new Color(1, 1, 1)],
  14220. [1.0, new Color(1, 1, 1)],
  14221. ],
  14222. };
  14223. const PointCloudFS = `
  14224. varying vec3 vColor;
  14225. uniform float alpha;
  14226. void main() {
  14227. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14228. discard;
  14229. } else {
  14230. gl_FragColor = vec4( vColor, alpha);
  14231. }
  14232. }
  14233. `;
  14234. const PointCloudVS = `
  14235. varying vec3 vColor;
  14236. uniform sampler2D gradient;
  14237. uniform sampler2D grayscale;
  14238. attribute float intensity;
  14239. attribute float classification;
  14240. uniform vec3 rootCenter;
  14241. uniform vec3 rootNormal;
  14242. uniform vec2 elevationRange;
  14243. uniform int coloring;
  14244. uniform bool hideGround;
  14245. uniform float maxIntensity;
  14246. uniform float intensityContrast;
  14247. uniform float pointSize;
  14248. #ifdef USE_COLOR
  14249. vec3 getRGB() {
  14250. vec3 rgb = color;
  14251. return rgb;
  14252. }
  14253. #endif
  14254. vec3 getElevation(){
  14255. vec4 world = modelMatrix * vec4( position, 1.0 );
  14256. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14257. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14258. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14259. return cElevation;
  14260. }
  14261. vec3 getIntensity(){
  14262. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14263. float intmod = pow(intensity, intensityContrast);
  14264. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14265. return cIntensity;
  14266. }
  14267. vec3 getClassification(){
  14268. float classNormalized = classification / 255.0;
  14269. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14270. return cClassification;
  14271. }
  14272. vec3 getColor(){
  14273. vec3 color;
  14274. if (hideGround && classification == 2.0) {
  14275. return vec3(0.0, 0.0, 0.0);
  14276. }
  14277. if (coloring == 1) {
  14278. color = getIntensity();
  14279. }
  14280. else if (coloring == 2) {
  14281. color = getClassification();
  14282. } else if (coloring == 3) {
  14283. color = getElevation();
  14284. }
  14285. #ifdef USE_COLOR
  14286. else if (coloring == 4) {
  14287. color = getRGB();
  14288. }
  14289. #endif
  14290. else {
  14291. color = vec3(1.0, 1.0, 1.0);
  14292. }
  14293. return color;
  14294. }
  14295. void main() {
  14296. vColor = getColor();
  14297. gl_PointSize = pointSize;
  14298. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14299. }
  14300. `;
  14301. /** Types of coloring used when viewing point cloud tiles */
  14302. var PointCloudColoring;
  14303. (function (PointCloudColoring) {
  14304. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14305. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14306. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14307. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14308. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14309. })(PointCloudColoring || (PointCloudColoring = {}));
  14310. /** Types of shading used when viewing b3dm (mesh) tiles */
  14311. var Shading;
  14312. (function (Shading) {
  14313. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14314. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14315. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14316. })(Shading || (Shading = {}));
  14317. var GeoTransform;
  14318. (function (GeoTransform) {
  14319. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14320. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14321. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14322. })(GeoTransform || (GeoTransform = {}));
  14323. const gradient = Gradients.RAINBOW;
  14324. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14325. const grayscale = Gradients.GRAYSCALE;
  14326. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14327. const defaultOptions = {
  14328. throttleRequests: true,
  14329. maxRequests: 64,
  14330. updateInterval: 0.1,
  14331. maxConcurrency: 1,
  14332. maximumScreenSpaceError: 16,
  14333. maximumMemoryUsage: 32,
  14334. viewDistanceScale: 1.0,
  14335. skipLevelOfDetail: false,
  14336. updateTransforms: true,
  14337. shading: Shading.FlatTexture,
  14338. transparent: false,
  14339. pointCloudColoring: PointCloudColoring.White,
  14340. pointSize: 1.0,
  14341. worker: true,
  14342. wireframe: false,
  14343. debug: false,
  14344. basisTranscoderPath: null,
  14345. dracoDecoderPath: null,
  14346. material: null,
  14347. computeNormals: false,
  14348. shaderCallback: null,
  14349. geoTransform: GeoTransform.Reset,
  14350. preloadTilesCount: null
  14351. };
  14352. /** 3D Tiles Loader */
  14353. class Loader3DTiles {
  14354. /**
  14355. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14356. * @public
  14357. *
  14358. * @param props - Properties for this load call {@link LoaderProps}.
  14359. * @returns An object containing the 3D Model to be added to the scene
  14360. * and a runtime engine to be updated every frame.
  14361. */
  14362. static load(props) {
  14363. return __awaiter(this, void 0, void 0, function* () {
  14364. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14365. const { url } = props;
  14366. const UPDATE_INTERVAL = options.updateInterval;
  14367. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14368. const loadersGLOptions = {};
  14369. if (options.cesiumIONToken) {
  14370. loadersGLOptions['cesium-ion'] = {
  14371. accessToken: options.cesiumIONToken,
  14372. };
  14373. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14374. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14375. }
  14376. if (props.loadingManager) {
  14377. props.loadingManager.itemStart(url);
  14378. }
  14379. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14380. const renderMap = {};
  14381. const boxMap = {};
  14382. const unloadQueue = [];
  14383. const root = new Group();
  14384. const tileBoxes = new Group();
  14385. tileBoxes.matrixAutoUpdate = false//add
  14386. if (!options.debug) {
  14387. tileBoxes.visible = false;
  14388. }else{
  14389. options.parent.add(tileBoxes) //add
  14390. }
  14391. const pointcloudUniforms = {
  14392. pointSize: { type: 'f', value: options.pointSize },
  14393. gradient: { type: 't', value: gradientTexture },
  14394. grayscale: { type: 't', value: grayscaleTexture },
  14395. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14396. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14397. coloring: { type: 'i', value: options.pointCloudColoring },
  14398. hideGround: { type: 'b', value: true },
  14399. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14400. maxIntensity: { type: 'f', value: 1.0 },
  14401. intensityContrast: { type: 'f', value: 1.0 },
  14402. alpha: { type: 'f', value: 1.0 },
  14403. };
  14404. const pointcloudMaterial = new ShaderMaterial({
  14405. uniforms: pointcloudUniforms,
  14406. vertexShader: PointCloudVS,
  14407. fragmentShader: PointCloudFS,
  14408. transparent: options.transparent,
  14409. vertexColors: true
  14410. });
  14411. let cameraReference = null;
  14412. let rendererReference = null;
  14413. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14414. let ktx2Loader = undefined;
  14415. let dracoLoader = undefined;
  14416. if (options.basisTranscoderPath) {
  14417. ktx2Loader = new KTX2Loader();
  14418. ktx2Loader.detectSupport(props.renderer);
  14419. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14420. ktx2Loader.setWorkerLimit(1);
  14421. gltfLoader.setKTX2Loader(ktx2Loader);
  14422. }
  14423. if (options.dracoDecoderPath) {
  14424. dracoLoader = new DRACOLoader();
  14425. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14426. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14427. gltfLoader.setDRACOLoader(dracoLoader);
  14428. }
  14429. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14430. const tileOptions = {
  14431. maximumMemoryUsage: options.maximumMemoryUsage,
  14432. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14433. viewDistanceScale: options.viewDistanceScale,
  14434. skipLevelOfDetail: options.skipLevelOfDetail,
  14435. updateTransforms: options.updateTransforms,
  14436. throttleRequests: options.throttleRequests,
  14437. maxRequests: options.maxRequests,
  14438. maxDepth: options.maxDepth || 50, // !zeg改
  14439. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14440. let tileContent = null;
  14441. switch (tile.type) {
  14442. case TILE_TYPE.POINTCLOUD: {
  14443. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14444. break;
  14445. }
  14446. case TILE_TYPE.SCENEGRAPH:
  14447. case TILE_TYPE.MESH: {
  14448. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14449. break;
  14450. }
  14451. }
  14452. if (tileContent) {
  14453. tileContent.visible = false;
  14454. renderMap[tile.id] = tileContent;
  14455. root.add(renderMap[tile.id]);
  14456. if (options.debug) {
  14457. const box = loadersBoundingBoxToMesh(tile);
  14458. tileBoxes.add(box);
  14459. boxMap[tile.id] = box;
  14460. }
  14461. //xzw :
  14462. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14463. }
  14464. }),
  14465. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14466. if (tileset) {
  14467. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14468. detectOrientation(tile);
  14469. }
  14470. tileset._frameNumber++;
  14471. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14472. }
  14473. }),
  14474. onTileUnload: (tile) => {
  14475. unloadQueue.push(tile);
  14476. },
  14477. onTileError: (tile, message) => {
  14478. console.error('Tile error', tile.id, message);
  14479. },
  14480. };
  14481. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14482. loadImages: false,
  14483. }, '3d-tiles': {
  14484. loadGLTF: false
  14485. } }) }));
  14486. //
  14487. // transformations
  14488. const threeMat = new Matrix4$1();
  14489. const tileTrasnform = new Matrix4$1();
  14490. const rootCenter = new Vector3$1();
  14491. let orientationDetected = false;
  14492. if (tileset.root.boundingVolume) {
  14493. if (tileset.root.header.boundingVolume.region) {
  14494. // TODO: Handle region type bounding volumes
  14495. // https://github.com/visgl/loaders.gl/issues/1994
  14496. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14497. options.geoTransform = GeoTransform.WGS84Cartesian;
  14498. }
  14499. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14500. }
  14501. else {
  14502. console.warn("Bounding volume not found, no transformations applied");
  14503. }
  14504. if (options.debug) {
  14505. const box = loadersBoundingBoxToMesh(tileset.root);
  14506. tileBoxes.add(box);
  14507. boxMap[tileset.root.id] = box;
  14508. }
  14509. let disposeFlag = false;
  14510. let loadingEnded = false;
  14511. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14512. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14513. // Extra stats
  14514. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14515. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14516. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14517. let timer = 0;
  14518. let lastCameraTransform = null;
  14519. let lastCameraAspect = null;
  14520. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14521. let sseDenominator = null;
  14522. root.updateMatrixWorld(true);
  14523. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14524. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14525. detectOrientation(tileset.root);
  14526. updateResetTransform();
  14527. if (options.debug) {
  14528. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14529. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14530. }
  14531. if (options.geoTransform == GeoTransform.Mercator) {
  14532. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14533. rootCenter.set(coords.x, 0, -coords.y);
  14534. root.position.copy(rootCenter);
  14535. root.rotation.set(-Math.PI / 2, 0, 0);
  14536. root.updateMatrixWorld(true);
  14537. }
  14538. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14539. root.applyMatrix4(tileTrasnform);
  14540. root.updateMatrixWorld(true);
  14541. rootCenter.copy(root.position);
  14542. }
  14543. function detectOrientation(tile) {
  14544. if (!tile.boundingVolume.halfAxes) {
  14545. return;
  14546. }
  14547. const halfAxes = tile.boundingVolume.halfAxes;
  14548. const orientationMatrix = new Matrix4$1()
  14549. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14550. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14551. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14552. if (!rotation.equals(new Euler())) {
  14553. orientationDetected = true;
  14554. const pos = new Vector3$1(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  14555. tileTrasnform.extractRotation(orientationMatrix);
  14556. tileTrasnform.setPosition(pos);
  14557. updateResetTransform();
  14558. }
  14559. }
  14560. function updateResetTransform() {
  14561. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14562. // Reset the current model matrix and apply our own transformation
  14563. threeMat.copy(tileTrasnform).invert();
  14564. threeMat.premultiply(lastRootTransform);
  14565. threeMat.copy(lastRootTransform).multiply(new Matrix4$1().copy(tileTrasnform).invert());
  14566. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14567. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  14568. }
  14569. }
  14570. // 更新瓦片显隐和瓦片迭代更新
  14571. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14572. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14573. return
  14574. }
  14575. // Assumes camera fov, near and far are not changing
  14576. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14577. const loadersFrustum = new PerspectiveFrustum({
  14578. fov: (camera.fov / 180) * Math.PI,
  14579. aspectRatio: camera.aspect,
  14580. near: camera.near,
  14581. far: camera.far,
  14582. });
  14583. sseDenominator = loadersFrustum.sseDenominator;
  14584. lastCameraAspect = camera.aspect;
  14585. if(camera.aspect == 0)return//add
  14586. if (options.debug) {
  14587. console.log('Updated sse denonimator:', sseDenominator);
  14588. }
  14589. }
  14590. const frustum = getCameraFrustum(camera);
  14591. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14592. const cullingVolume = new CullingVolume(planes);
  14593. const rendererSize = new Vector2$1();
  14594. renderer.getSize(rendererSize);
  14595. const frameState = {
  14596. camera: {
  14597. position: lastCameraPosition.toArray(),
  14598. },
  14599. height: rendererSize.y,
  14600. frameNumber: tileset._frameNumber,
  14601. sseDenominator: sseDenominator,
  14602. cullingVolume: cullingVolume,
  14603. viewport: {
  14604. id: 0,
  14605. },
  14606. };
  14607. tileset._cache.reset();
  14608. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14609. for (const tile of tileset.tiles) {
  14610. if (tile.selected) {
  14611. if (!renderMap[tile.id]) {
  14612. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14613. }
  14614. else {
  14615. // Make sure it's visible
  14616. if(!renderMap[tile.id].visible){
  14617. if(visiVertexCount<maxVertexVisi){
  14618. renderMap[tile.id].visible = true;
  14619. visiVertexCount += renderMap[tile.id].vertexCount //xzw add
  14620. options.debug && (boxMap[tile.id].material.opacity = 1)
  14621. }else{
  14622. //console.log('超出', visiVertexCount)
  14623. }
  14624. }
  14625. /* if(!renderMap[tile.id].realVisible()){
  14626. console.error('!realVisible')
  14627. } */
  14628. }
  14629. }
  14630. else {
  14631. if (renderMap[tile.id]) {
  14632. if(renderMap[tile.id].visible){
  14633. renderMap[tile.id].visible = false;
  14634. options.debug && (boxMap[tile.id].material.opacity = 0.1)
  14635. visiVertexCount -= renderMap[tile.id].vertexCount //xzw add
  14636. }
  14637. }
  14638. }
  14639. }
  14640. while (unloadQueue.length > 0) {
  14641. const tile = unloadQueue.pop();
  14642. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14643. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14644. root.remove(renderMap[tile.id]);
  14645. disposeNode(renderMap[tile.id]);
  14646. delete renderMap[tile.id];
  14647. }
  14648. if (boxMap[tile.id]) {
  14649. disposeNode(boxMap[tile.id]);
  14650. tileBoxes.remove(boxMap[tile.id]);
  14651. delete boxMap[tile.id];
  14652. }
  14653. }
  14654. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14655. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14656. if (props.onProgress) {
  14657. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14658. }
  14659. if (props.loadingManager && !loadingEnded) {
  14660. if (tilesLoading == 0 &&
  14661. (options.preloadTilesCount == null ||
  14662. tilesLoaded >= options.preloadTilesCount)) {
  14663. loadingEnded = true;
  14664. props.loadingManager.itemEnd(props.url);
  14665. }
  14666. }
  14667. return frameState;
  14668. }
  14669. return {
  14670. model: root,
  14671. runtime: {
  14672. getTileset: () => {
  14673. return tileset;
  14674. },
  14675. getStats: () => {
  14676. return tileset.stats;
  14677. },
  14678. showTiles: (visible) => {
  14679. tileBoxes.visible = visible;
  14680. },
  14681. setWireframe: (wireframe) => {
  14682. options.wireframe = wireframe;
  14683. root.traverse((object) => {
  14684. if (object instanceof Mesh) {
  14685. object.material.wireframe = wireframe;
  14686. }
  14687. });
  14688. },
  14689. setDebug: (debug) => {
  14690. options.debug = debug;
  14691. tileBoxes.visible = debug;
  14692. },
  14693. setShading: (shading) => {
  14694. options.shading = shading;
  14695. },
  14696. getTileBoxes: () => {
  14697. return tileBoxes;
  14698. },
  14699. setViewDistanceScale: (scale) => {
  14700. tileset.options.viewDistanceScale = scale;
  14701. tileset._frameNumber++;
  14702. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14703. },
  14704. setHideGround: (enabled) => {
  14705. pointcloudUniforms.hideGround.value = enabled;
  14706. },
  14707. setPointCloudColoring: (selection) => {
  14708. pointcloudUniforms.coloring.value = selection;
  14709. },
  14710. setElevationRange: (range) => {
  14711. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14712. },
  14713. setMaxIntensity: (intensity) => {
  14714. pointcloudUniforms.maxIntensity.value = intensity;
  14715. },
  14716. setIntensityContrast: (contrast) => {
  14717. pointcloudUniforms.intensityContrast.value = contrast;
  14718. },
  14719. setPointAlpha: (alpha) => {
  14720. pointcloudUniforms.alpha.value = alpha;
  14721. },
  14722. getLatLongHeightFromPosition: (position) => {
  14723. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14724. return {
  14725. lat: cartographicPosition[1],
  14726. long: cartographicPosition[0],
  14727. height: cartographicPosition[2],
  14728. };
  14729. },
  14730. getPositionFromLatLongHeight: (coord) => {
  14731. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14732. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14733. },
  14734. getCameraFrustum: (camera) => {
  14735. const frustum = getCameraFrustum(camera);
  14736. const meshes = frustum.planes
  14737. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14738. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14739. const model = new Group();
  14740. for (const mesh of meshes)
  14741. model.add(mesh);
  14742. return model;
  14743. },
  14744. update: function (dt, renderer, camera, ifForce) {
  14745. cameraReference = camera;
  14746. rendererReference = renderer;
  14747. timer += dt;
  14748. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  14749. if (!lastRootTransform.equals(root.matrixWorld)) {
  14750. timer = 0;
  14751. lastRootTransform.copy(root.matrixWorld);
  14752. updateResetTransform();
  14753. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14754. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14755. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14756. rootTransformInverse.copy(lastRootTransform).invert();
  14757. if (options.debug) {
  14758. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14759. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14760. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14761. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14762. tileBoxes.matrix.copy(root.matrixWorld);
  14763. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14764. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14765. //boxMap[tileset.root.id].updateWorldMatrix()
  14766. }
  14767. }
  14768. if (this.lastCameraTransform == null) {
  14769. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14770. }
  14771. else {
  14772. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14773. !(camera.aspect == lastCameraAspect);
  14774. if (cameraChanged || ifForce) {
  14775. timer = 0;
  14776. tileset._frameNumber++;
  14777. camera.getWorldPosition(lastCameraPosition);
  14778. this.lastCameraTransform.copy(camera.matrixWorld);
  14779. tilesetUpdate(tileset, renderMap, renderer, camera);
  14780. }
  14781. }
  14782. }/* else{
  14783. console.log('11')
  14784. } */
  14785. },
  14786. dispose: function () {
  14787. disposeFlag = true;
  14788. tileset._destroy();
  14789. while (root.children.length > 0) {
  14790. const obj = root.children[0];
  14791. disposeNode(obj);
  14792. root.remove(obj);
  14793. }
  14794. while (tileBoxes.children.length > 0) {
  14795. const obj = tileBoxes.children[0];
  14796. tileBoxes.remove(obj);
  14797. obj.geometry.dispose();
  14798. obj.material.dispose();
  14799. }
  14800. if (ktx2Loader) {
  14801. ktx2Loader.dispose();
  14802. }
  14803. if (dracoLoader) {
  14804. dracoLoader.dispose();
  14805. }
  14806. },
  14807. },
  14808. };
  14809. });
  14810. }
  14811. }
  14812. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14813. return __awaiter(this, void 0, void 0, function* () {
  14814. return new Promise((resolve, reject) => {
  14815. var _a;
  14816. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14817. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14818. // The computed trasnform already contains the root's transform, so we have to invert it
  14819. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14820. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  14821. // 这句同tile.computedTransform左乘tileTrasnform。 因为tileTrasnform拿不到所以使用modelMatrix。modelMatrix为tileTrasnform左乘rootTransform, 所以再左乘rootTransformInverse
  14822. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  14823. if (shouldRotate) {
  14824. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  14825. }
  14826. gltfLoader.parse(
  14827. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14828. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14829. (gltf) => {
  14830. const tileContent = gltf.scenes[0];
  14831. //tileContent.applyMatrix4(contentTransform);
  14832. tileContent.vertexCount = 0 //xzw add
  14833. tileContent.traverse((object) => {
  14834. if (object.type == "Mesh") {
  14835. const mesh = object;
  14836. //mesh.tileId = tile.id//add
  14837. const originalMaterial = mesh.material;
  14838. const originalMap = originalMaterial.map;
  14839. if (options.material) {
  14840. mesh.material = options.material.clone();
  14841. originalMaterial.dispose();
  14842. }
  14843. else if (options.shading == Shading.FlatTexture) {
  14844. mesh.material = unlitMaterial.clone();
  14845. originalMaterial.dispose();
  14846. }
  14847. if (options.shading != Shading.ShadedNoTexture) {
  14848. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  14849. mesh.material.uniforms.map = { value: originalMap };
  14850. }
  14851. else {
  14852. mesh.material.map = originalMap;
  14853. }
  14854. }
  14855. else {
  14856. if (originalMap) {
  14857. originalMap.dispose();
  14858. }
  14859. mesh.material.map = null;
  14860. }
  14861. if (options.shaderCallback) {
  14862. mesh.onBeforeRender = options.shaderCallback;
  14863. }
  14864. mesh.material.wireframe = options.wireframe;
  14865. if (options.computeNormals) {
  14866. mesh.geometry.computeVertexNormals();
  14867. }
  14868. //xzw add:
  14869. tileContent.vertexCount += mesh.geometry.attributes.position.count
  14870. //------------------add on 2023.1.16----zeg
  14871. mesh.geometry.applyMatrix4(contentTransform)
  14872. if (tile.content.rtcCenter) {
  14873. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  14874. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  14875. } else {
  14876. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  14877. }
  14878. //---------------------
  14879. }
  14880. });
  14881. resolve(tileContent);
  14882. },
  14883. (e) => {
  14884. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  14885. }
  14886. );
  14887. });
  14888. });
  14889. }
  14890. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  14891. const d = {
  14892. rtc_center: tile.content.rtcCenter,
  14893. points: tile.content.attributes.positions,
  14894. intensities: tile.content.attributes.intensity,
  14895. classifications: tile.content.attributes.classification,
  14896. rgb: null,
  14897. rgba: null,
  14898. };
  14899. const { colors } = tile.content.attributes;
  14900. if (colors && colors.size === 3) {
  14901. d.rgb = colors.value;
  14902. }
  14903. if (colors && colors.size === 4) {
  14904. d.rgba = colors.value;
  14905. }
  14906. const geometry = new BufferGeometry();
  14907. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  14908. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  14909. if (d.rgba) {
  14910. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  14911. }
  14912. else if (d.rgb) {
  14913. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  14914. }
  14915. if (d.intensities) {
  14916. geometry.setAttribute('intensity',
  14917. // Handles both 16bit or 8bit intensity values
  14918. new BufferAttribute(d.intensities, 1, true));
  14919. }
  14920. if (d.classifications) {
  14921. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  14922. }
  14923. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  14924. if (d.rtc_center) {
  14925. const c = d.rtc_center;
  14926. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  14927. }
  14928. tileContent.applyMatrix4(contentTransform);
  14929. return tileContent;
  14930. }
  14931. function disposeMaterial(material) {
  14932. var _a, _b, _c, _d;
  14933. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  14934. (_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();
  14935. }
  14936. else if (material.map) {
  14937. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  14938. }
  14939. material.dispose();
  14940. }
  14941. function disposeNode(node) {
  14942. node.traverse((object) => {
  14943. if (object.isMesh) {
  14944. object.geometry.dispose();
  14945. if (object.material.isMaterial) {
  14946. disposeMaterial(object.material);
  14947. }
  14948. else {
  14949. // an array of materials
  14950. for (const material of object.material) {
  14951. disposeMaterial(material);
  14952. }
  14953. }
  14954. }
  14955. });
  14956. for (let i = node.children.length - 1; i >= 0; i--) {
  14957. const obj = node.children[i];
  14958. node.remove(obj);
  14959. }
  14960. }
  14961. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  14962. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  14963. /*
  14964. 关键搜寻:
  14965. Loader3DTiles : const tileset = new Tileset3D
  14966. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  14967. createGLTFNodes(gltfLoader 创建tile
  14968. executeTraversal(root, frameState) 遍历root
  14969. lastRootTransform rootTransformInverse
  14970. tileset._loadTiles 依次加载tiles
  14971. _getPriority 加载优先级 加了一句
  14972. 笔记:
  14973. 主要类:
  14974. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  14975. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  14976. tileset里算的tileTrasnform之后是不会改变的, tile.transform也是,是json里的。
  14977. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  14978. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  14979. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  14980. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  14981. get isVisibleAndInRequestVolume() {
  14982. return this._inRequestVolume; //去掉了_visible ||
  14983. }
  14984. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  14985. 原本会消失的地方虽然不会消失了但一直是模糊的
  14986. */