gaussian-splats-3d.module.js 565 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692
  1. /* import * as THREE from 'three';
  2. import { Ray as Ray$1, Plane, MathUtils, EventDispatcher, Vector3, MOUSE, TOUCH, Quaternion, Spherical, Vector2 } from 'three';
  3. */
  4. import * as THREE from '../three.js/build/three.module.js';
  5. import { Ray as Ray$1, Plane, MathUtils, EventDispatcher, Vector3, MOUSE, TOUCH, Quaternion, Spherical, Vector2 } from '../three.js/build/three.module.js';
  6. //加
  7. {
  8. const _tables = /*@__PURE__*/ _generateTables();
  9. function _generateTables() {
  10. // float32 to float16 helpers
  11. const buffer = new ArrayBuffer( 4 );
  12. const floatView = new Float32Array( buffer );
  13. const uint32View = new Uint32Array( buffer );
  14. const baseTable = new Uint32Array( 512 );
  15. const shiftTable = new Uint32Array( 512 );
  16. for ( let i = 0; i < 256; ++ i ) {
  17. const e = i - 127;
  18. // very small number (0, -0)
  19. if ( e < - 27 ) {
  20. baseTable[ i ] = 0x0000;
  21. baseTable[ i | 0x100 ] = 0x8000;
  22. shiftTable[ i ] = 24;
  23. shiftTable[ i | 0x100 ] = 24;
  24. // small number (denorm)
  25. } else if ( e < - 14 ) {
  26. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  27. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  28. shiftTable[ i ] = - e - 1;
  29. shiftTable[ i | 0x100 ] = - e - 1;
  30. // normal number
  31. } else if ( e <= 15 ) {
  32. baseTable[ i ] = ( e + 15 ) << 10;
  33. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  34. shiftTable[ i ] = 13;
  35. shiftTable[ i | 0x100 ] = 13;
  36. // large number (Infinity, -Infinity)
  37. } else if ( e < 128 ) {
  38. baseTable[ i ] = 0x7c00;
  39. baseTable[ i | 0x100 ] = 0xfc00;
  40. shiftTable[ i ] = 24;
  41. shiftTable[ i | 0x100 ] = 24;
  42. // stay (NaN, Infinity, -Infinity)
  43. } else {
  44. baseTable[ i ] = 0x7c00;
  45. baseTable[ i | 0x100 ] = 0xfc00;
  46. shiftTable[ i ] = 13;
  47. shiftTable[ i | 0x100 ] = 13;
  48. }
  49. }
  50. // float16 to float32 helpers
  51. const mantissaTable = new Uint32Array( 2048 );
  52. const exponentTable = new Uint32Array( 64 );
  53. const offsetTable = new Uint32Array( 64 );
  54. for ( let i = 1; i < 1024; ++ i ) {
  55. let m = i << 13; // zero pad mantissa bits
  56. let e = 0; // zero exponent
  57. // normalized
  58. while ( ( m & 0x00800000 ) === 0 ) {
  59. m <<= 1;
  60. e -= 0x00800000; // decrement exponent
  61. }
  62. m &= ~ 0x00800000; // clear leading 1 bit
  63. e += 0x38800000; // adjust bias
  64. mantissaTable[ i ] = m | e;
  65. }
  66. for ( let i = 1024; i < 2048; ++ i ) {
  67. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  68. }
  69. for ( let i = 1; i < 31; ++ i ) {
  70. exponentTable[ i ] = i << 23;
  71. }
  72. exponentTable[ 31 ] = 0x47800000;
  73. exponentTable[ 32 ] = 0x80000000;
  74. for ( let i = 33; i < 63; ++ i ) {
  75. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  76. }
  77. exponentTable[ 63 ] = 0xc7800000;
  78. for ( let i = 1; i < 64; ++ i ) {
  79. if ( i !== 32 ) {
  80. offsetTable[ i ] = 1024;
  81. }
  82. }
  83. return {
  84. floatView: floatView,
  85. uint32View: uint32View,
  86. baseTable: baseTable,
  87. shiftTable: shiftTable,
  88. mantissaTable: mantissaTable,
  89. exponentTable: exponentTable,
  90. offsetTable: offsetTable
  91. };
  92. }
  93. // float32 to float16
  94. /* function toHalfFloat( val ) {
  95. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  96. val = clamp( val, - 65504, 65504 );
  97. _tables.floatView[ 0 ] = val;
  98. const f = _tables.uint32View[ 0 ];
  99. const e = ( f >> 23 ) & 0x1ff;
  100. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  101. } */
  102. // float16 to float32
  103. function fromHalfFloat( val ) {
  104. const m = val >> 10;
  105. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  106. return _tables.floatView[ 0 ];
  107. }
  108. /*
  109. THREE.DataUtils = {
  110. toHalfFloat: toHalfFloat,
  111. fromHalfFloat: fromHalfFloat,
  112. };
  113. */
  114. THREE.DataUtils.fromHalfFloat = fromHalfFloat
  115. }
  116. //---------------------------------------------------
  117. class AbortablePromise {
  118. static idGen = 0;
  119. constructor(promiseFunc, abortHandler) {
  120. let resolver;
  121. let rejecter;
  122. this.promise = new Promise((resolve, reject) => {
  123. resolver = resolve;
  124. rejecter = reject;
  125. });
  126. const promiseResolve = resolver.bind(this);
  127. const promiseReject = rejecter.bind(this);
  128. const resolve = (...args) => {
  129. promiseResolve(...args);
  130. };
  131. const reject = (error) => {
  132. promiseReject(error);
  133. };
  134. promiseFunc(resolve.bind(this), reject.bind(this));
  135. this.abortHandler = abortHandler;
  136. this.id = AbortablePromise.idGen++;
  137. }
  138. then(onResolve) {
  139. return new AbortablePromise((resolve, reject) => {
  140. this.promise = this.promise
  141. .then((...args) => {
  142. const onResolveResult = onResolve(...args);
  143. if (onResolveResult instanceof Promise || onResolveResult instanceof AbortablePromise) {
  144. onResolveResult.then((...args2) => {
  145. resolve(...args2);
  146. });
  147. } else {
  148. resolve(onResolveResult);
  149. }
  150. })
  151. .catch((error) => {
  152. reject(error);
  153. });
  154. }, this.abortHandler);
  155. }
  156. catch(onFail) {
  157. return new AbortablePromise((resolve) => {
  158. this.promise = this.promise.then((...args) => {
  159. resolve(...args);
  160. })
  161. .catch(onFail);
  162. }, this.abortHandler);
  163. }
  164. abort(reason) {
  165. if (this.abortHandler) this.abortHandler(reason);
  166. }
  167. }
  168. class AbortedPromiseError extends Error {
  169. constructor(msg) {
  170. super(msg);
  171. }
  172. }
  173. const floatToHalf = function() {
  174. const floatView = new Float32Array(1);
  175. const int32View = new Int32Array(floatView.buffer);
  176. return function(val) {
  177. floatView[0] = val;
  178. const x = int32View[0];
  179. let bits = (x >> 16) & 0x8000;
  180. let m = (x >> 12) & 0x07ff;
  181. const e = (x >> 23) & 0xff;
  182. if (e < 103) return bits;
  183. if (e > 142) {
  184. bits |= 0x7c00;
  185. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  186. return bits;
  187. }
  188. if (e < 113) {
  189. m |= 0x0800;
  190. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  191. return bits;
  192. }
  193. bits |= (( e - 112) << 10) | (m >> 1);
  194. bits += m & 1;
  195. return bits;
  196. };
  197. }();
  198. const uintEncodedFloat = function() {
  199. const floatView = new Float32Array(1);
  200. const int32View = new Int32Array(floatView.buffer);
  201. return function(f) {
  202. floatView[0] = f;
  203. return int32View[0];
  204. };
  205. }();
  206. const rgbaToInteger = function(r, g, b, a) {
  207. return r + (g << 8) + (b << 16) + (a << 24);
  208. };
  209. const rgbaArrayToInteger = function(arr, offset) {
  210. return arr[offset] + (arr[offset + 1] << 8) + (arr[offset + 2] << 16) + (arr[offset + 3] << 24);
  211. };
  212. const fetchWithProgress = function(path, onProgress, saveChunks = true) {
  213. const abortController = new AbortController();
  214. const signal = abortController.signal;
  215. let aborted = false;
  216. const abortHandler = (reason) => {
  217. abortController.abort(new AbortedPromiseError(reason));
  218. aborted = true;
  219. };
  220. return new AbortablePromise((resolve, reject) => {
  221. fetch(path, { signal })
  222. .then(async (data) => {
  223. const reader = data.body.getReader();
  224. let bytesDownloaded = 0;
  225. let _fileSize = data.headers.get('Content-Length');
  226. let fileSize = _fileSize ? parseInt(_fileSize) : undefined;
  227. const chunks = [];
  228. while (!aborted) {
  229. try {
  230. const { value: chunk, done } = await reader.read();
  231. if (done) {
  232. if (onProgress) {
  233. onProgress(100, '100%', chunk, fileSize);
  234. }
  235. if (saveChunks) {
  236. const buffer = new Blob(chunks).arrayBuffer();
  237. resolve(buffer);
  238. } else {
  239. resolve();
  240. }
  241. break;
  242. }
  243. bytesDownloaded += chunk.length;
  244. let percent;
  245. let percentLabel;
  246. if (fileSize !== undefined) {
  247. percent = bytesDownloaded / fileSize * 100;
  248. percentLabel = `${percent.toFixed(2)}%`;
  249. }
  250. if (saveChunks) chunks.push(chunk);
  251. if (onProgress) {
  252. const cancelSaveChucnks = onProgress(percent, percentLabel, chunk, fileSize);
  253. if (cancelSaveChucnks) saveChunks = false;
  254. }
  255. } catch (error) {
  256. reject(error);
  257. break;
  258. }
  259. }
  260. })
  261. .catch((error) => {
  262. reject(error);
  263. });
  264. }, abortHandler);
  265. };
  266. const clamp = function(val, min, max) {
  267. return Math.max(Math.min(val, max), min);
  268. };
  269. const getCurrentTime = function() {
  270. return performance.now() / 1000;
  271. };
  272. const disposeAllMeshes = (object3D) => {
  273. if (object3D.geometry) {
  274. object3D.geometry.dispose();
  275. object3D.geometry = null;
  276. }
  277. if (object3D.material) {
  278. object3D.material.dispose();
  279. object3D.material = null;
  280. }
  281. if (object3D.children) {
  282. for (let child of object3D.children) {
  283. disposeAllMeshes(child);
  284. }
  285. }
  286. };
  287. const delayedExecute = (func, fast) => {
  288. return new Promise((resolve) => {
  289. window.setTimeout(() => {
  290. resolve(func());
  291. }, fast ? 1 : 50);
  292. });
  293. };
  294. const getSphericalHarmonicsComponentCountForDegree = (sphericalHarmonicsDegree = 0) => {
  295. switch (sphericalHarmonicsDegree) {
  296. case 1:
  297. return 9;
  298. case 2:
  299. return 24;
  300. }
  301. return 0;
  302. };
  303. const nativePromiseWithExtractedComponents = () => {
  304. let resolver;
  305. let rejecter;
  306. const promise = new Promise((resolve, reject) => {
  307. resolver = resolve;
  308. rejecter = reject;
  309. });
  310. return {
  311. 'promise': promise,
  312. 'resolve': resolver,
  313. 'reject': rejecter
  314. };
  315. };
  316. const abortablePromiseWithExtractedComponents = (abortHandler) => {
  317. let resolver;
  318. let rejecter;
  319. if (!abortHandler) {
  320. abortHandler = () => {};
  321. }
  322. const promise = new AbortablePromise((resolve, reject) => {
  323. resolver = resolve;
  324. rejecter = reject;
  325. }, abortHandler);
  326. return {
  327. 'promise': promise,
  328. 'resolve': resolver,
  329. 'reject': rejecter
  330. };
  331. };
  332. class Semver {
  333. constructor(major, minor, patch) {
  334. this.major = major;
  335. this.minor = minor;
  336. this.patch = patch;
  337. }
  338. toString() {
  339. return `${this.major}_${this.minor}_${this.patch}`;
  340. }
  341. }
  342. function isIOS() {
  343. const ua = navigator.userAgent;
  344. return ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0;
  345. }
  346. function getIOSSemever() {
  347. if (isIOS()) {
  348. const extract = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
  349. return new Semver(
  350. parseInt(extract[1] || 0, 10),
  351. parseInt(extract[2] || 0, 10),
  352. parseInt(extract[3] || 0, 10)
  353. );
  354. } else {
  355. return null; // or [0,0,0]
  356. }
  357. }
  358. const BASE_COMPONENT_COUNT = 14;
  359. class UncompressedSplatArray {
  360. static OFFSET = {
  361. X: 0,
  362. Y: 1,
  363. Z: 2,
  364. SCALE0: 3,
  365. SCALE1: 4,
  366. SCALE2: 5,
  367. ROTATION0: 6,
  368. ROTATION1: 7,
  369. ROTATION2: 8,
  370. ROTATION3: 9,
  371. FDC0: 10,
  372. FDC1: 11,
  373. FDC2: 12,
  374. OPACITY: 13,
  375. FRC0: 14,
  376. FRC1: 15,
  377. FRC2: 16,
  378. FRC3: 17,
  379. FRC4: 18,
  380. FRC5: 19,
  381. FRC6: 20,
  382. FRC7: 21,
  383. FRC8: 22,
  384. FRC9: 23,
  385. FRC10: 24,
  386. FRC11: 25,
  387. FRC12: 26,
  388. FRC13: 27,
  389. FRC14: 28,
  390. FRC15: 29,
  391. FRC16: 30,
  392. FRC17: 31,
  393. FRC18: 32,
  394. FRC19: 33,
  395. FRC20: 34,
  396. FRC21: 35,
  397. FRC22: 36,
  398. FRC23: 37
  399. };
  400. constructor(sphericalHarmonicsDegree = 0) {
  401. this.sphericalHarmonicsDegree = sphericalHarmonicsDegree;
  402. this.sphericalHarmonicsCount = getSphericalHarmonicsComponentCountForDegree(this.sphericalHarmonicsDegree);
  403. this.componentCount = this.sphericalHarmonicsCount + BASE_COMPONENT_COUNT;
  404. this.defaultSphericalHarmonics = new Array(this.sphericalHarmonicsCount).fill(0);
  405. this.splats = [];
  406. this.splatCount = 0;
  407. }
  408. static createSplat(sphericalHarmonicsDegree = 0) {
  409. const baseSplat = [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
  410. let shEntries = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree);
  411. for (let i = 0; i < shEntries; i++) baseSplat.push(0);
  412. return baseSplat;
  413. }
  414. addSplat(splat) {
  415. this.splats.push(splat);
  416. this.splatCount++;
  417. }
  418. getSplat(index) {
  419. return this.splats[index];
  420. }
  421. addDefaultSplat() {
  422. const newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree);
  423. this.addSplat(newSplat);
  424. return newSplat;
  425. }
  426. addSplatFromComonents(x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity, ...rest) {
  427. const newSplat = [x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity, ...this.defaultSphericalHarmonics];
  428. for (let i = 0; i < rest.length && i < this.sphericalHarmonicsCount; i++) {
  429. newSplat[i] = rest[i];
  430. }
  431. this.addSplat(newSplat);
  432. return newSplat;
  433. }
  434. addSplatFromArray(src, srcIndex) {
  435. const srcSplat = src.splats[srcIndex];
  436. const newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree);
  437. for (let i = 0; i < this.componentCount && i < srcSplat.length; i++) {
  438. newSplat[i] = srcSplat[i];
  439. }
  440. this.addSplat(newSplat);
  441. }
  442. }
  443. class Constants {
  444. static DepthMapRange = 1 << 16;
  445. static MemoryPageSize = 65536;
  446. static BytesPerFloat = 4;
  447. static BytesPerInt = 4;
  448. static MaxScenes = 32;
  449. static ProgressiveLoadSectionSize = 262144;
  450. static ProgressiveLoadSectionDelayDuration = 15;
  451. static SphericalHarmonics8BitCompressionRange = 3;
  452. }
  453. const DefaultSphericalHarmonics8BitCompressionRange = Constants.SphericalHarmonics8BitCompressionRange;
  454. const DefaultSphericalHarmonics8BitCompressionHalfRange = DefaultSphericalHarmonics8BitCompressionRange / 2.0;
  455. const toHalfFloat = THREE.DataUtils.toHalfFloat.bind(THREE.DataUtils);
  456. const fromHalfFloat$1 = THREE.DataUtils.fromHalfFloat.bind(THREE.DataUtils);
  457. const toUncompressedFloat = (f, compressionLevel, isSH = false, range8BitMin, range8BitMax) => {
  458. if (compressionLevel === 0) {
  459. return f;
  460. } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) {
  461. return THREE.DataUtils.fromHalfFloat(f);
  462. } else if (compressionLevel === 2) {
  463. return fromUint8(f, range8BitMin, range8BitMax);
  464. }
  465. };
  466. const toUint8 = (v, rangeMin, rangeMax) => {
  467. v = clamp(v, rangeMin, rangeMax);
  468. const range = (rangeMax - rangeMin);
  469. return clamp(Math.floor((v - rangeMin) / range * 255), 0, 255);
  470. };
  471. const fromUint8 = (v, rangeMin, rangeMax) => {
  472. const range = (rangeMax - rangeMin);
  473. return (v / 255 * range + rangeMin);
  474. };
  475. const fromHalfFloatToUint8 = (v, rangeMin, rangeMax) => {
  476. return toUint8(fromHalfFloat$1(v, rangeMin, rangeMax));
  477. };
  478. const fromUint8ToHalfFloat = (v, rangeMin, rangeMax) => {
  479. return toHalfFloat(fromUint8(v, rangeMin, rangeMax));
  480. };
  481. const dataViewFloatForCompressionLevel = (dataView, floatIndex, compressionLevel, isSH = false) => {
  482. if (compressionLevel === 0) {
  483. return dataView.getFloat32(floatIndex * 4, true);
  484. } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) {
  485. return dataView.getUint16(floatIndex * 2, true);
  486. } else {
  487. return dataView.getUint8(floatIndex, true);
  488. }
  489. };
  490. const convertBetweenCompressionLevels = function() {
  491. const noop = (v) => v;
  492. return function(val, fromLevel, toLevel, isSH = false) {
  493. if (fromLevel === toLevel) return val;
  494. let outputConversionFunc = noop;
  495. if (fromLevel === 2 && isSH) {
  496. if (toLevel === 1) outputConversionFunc = fromUint8ToHalfFloat;
  497. else if (toLevel == 0) {
  498. outputConversionFunc = fromUint8;
  499. }
  500. } else if (fromLevel === 2 || fromLevel === 1) {
  501. if (toLevel === 0) outputConversionFunc = fromHalfFloat$1;
  502. else if (toLevel == 2) {
  503. if (!isSH) outputConversionFunc = noop;
  504. else outputConversionFunc = fromHalfFloatToUint8;
  505. }
  506. } else if (fromLevel === 0) {
  507. if (toLevel === 1) outputConversionFunc = toHalfFloat;
  508. else if (toLevel == 2) {
  509. if (!isSH) outputConversionFunc = toHalfFloat;
  510. else outputConversionFunc = toUint8;
  511. }
  512. }
  513. return outputConversionFunc(val);
  514. };
  515. }();
  516. const copyBetweenBuffers = (srcBuffer, srcOffset, destBuffer, destOffset, byteCount = 0) => {
  517. const src = new Uint8Array(srcBuffer, srcOffset);
  518. const dest = new Uint8Array(destBuffer, destOffset);
  519. for (let i = 0; i < byteCount; i++) {
  520. dest[i] = src[i];
  521. }
  522. };
  523. /**
  524. * SplatBuffer: Container for splat data from a single scene/file and capable of (mediocre) compression.
  525. */
  526. class SplatBuffer {
  527. static CurrentMajorVersion = 0;
  528. static CurrentMinorVersion = 1;
  529. static CenterComponentCount = 3;
  530. static ScaleComponentCount = 3;
  531. static RotationComponentCount = 4;
  532. static ColorComponentCount = 4;
  533. static CovarianceComponentCount = 6;
  534. static SplatScaleOffsetFloat = 3;
  535. static SplatRotationOffsetFloat = 6;
  536. static CompressionLevels = {
  537. 0: {
  538. BytesPerCenter: 12,
  539. BytesPerScale: 12,
  540. BytesPerRotation: 16,
  541. BytesPerColor: 4,
  542. ScaleOffsetBytes: 12,
  543. RotationffsetBytes: 24,
  544. ColorOffsetBytes: 40,
  545. SphericalHarmonicsOffsetBytes: 44,
  546. ScaleRange: 1,
  547. BytesPerSphericalHarmonicsComponent: 4,
  548. SphericalHarmonicsOffsetFloat: 11,
  549. SphericalHarmonicsDegrees: {
  550. 0: { BytesPerSplat: 44 },
  551. 1: { BytesPerSplat: 80 },
  552. 2: { BytesPerSplat: 140 }
  553. },
  554. },
  555. 1: {
  556. BytesPerCenter: 6,
  557. BytesPerScale: 6,
  558. BytesPerRotation: 8,
  559. BytesPerColor: 4,
  560. ScaleOffsetBytes: 6,
  561. RotationffsetBytes: 12,
  562. ColorOffsetBytes: 20,
  563. SphericalHarmonicsOffsetBytes: 24,
  564. ScaleRange: 32767,
  565. BytesPerSphericalHarmonicsComponent: 2,
  566. SphericalHarmonicsOffsetFloat: 12,
  567. SphericalHarmonicsDegrees: {
  568. 0: { BytesPerSplat: 24 },
  569. 1: { BytesPerSplat: 42 },
  570. 2: { BytesPerSplat: 72 }
  571. },
  572. },
  573. 2: {
  574. BytesPerCenter: 6,
  575. BytesPerScale: 6,
  576. BytesPerRotation: 8,
  577. BytesPerColor: 4,
  578. ScaleOffsetBytes: 6,
  579. RotationffsetBytes: 12,
  580. ColorOffsetBytes: 20,
  581. SphericalHarmonicsOffsetBytes: 24,
  582. ScaleRange: 32767,
  583. BytesPerSphericalHarmonicsComponent: 1,
  584. SphericalHarmonicsOffsetFloat: 12,
  585. SphericalHarmonicsDegrees: {
  586. 0: { BytesPerSplat: 24 },
  587. 1: { BytesPerSplat: 33 },
  588. 2: { BytesPerSplat: 48 }
  589. },
  590. }
  591. };
  592. static CovarianceSizeFloats = 6;
  593. static HeaderSizeBytes = 4096;
  594. static SectionHeaderSizeBytes = 1024;
  595. static BucketStorageSizeBytes = 12;
  596. static BucketStorageSizeFloats = 3;
  597. static BucketBlockSize = 5.0;
  598. static BucketSize = 256;
  599. constructor(bufferData, secLoadedCountsToMax = true) {
  600. this.constructFromBuffer(bufferData, secLoadedCountsToMax);
  601. }
  602. getSplatCount() {
  603. return this.splatCount;
  604. }
  605. getMaxSplatCount() {
  606. return this.maxSplatCount;
  607. }
  608. getMinSphericalHarmonicsDegree() {
  609. let minSphericalHarmonicsDegree = 0;
  610. for (let i = 0; i < this.sections.length; i++) {
  611. const section = this.sections[i];
  612. if (i === 0 || section.sphericalHarmonicsDegree < minSphericalHarmonicsDegree) {
  613. minSphericalHarmonicsDegree = section.sphericalHarmonicsDegree;
  614. }
  615. }
  616. return minSphericalHarmonicsDegree;
  617. }
  618. getBucketIndex(section, localSplatIndex) {
  619. let bucketIndex;
  620. const maxSplatIndexInFullBuckets = section.fullBucketCount * section.bucketSize;
  621. if (localSplatIndex < maxSplatIndexInFullBuckets) {
  622. bucketIndex = Math.floor(localSplatIndex / section.bucketSize);
  623. } else {
  624. let bucketSplatIndex = maxSplatIndexInFullBuckets;
  625. bucketIndex = section.fullBucketCount;
  626. let partiallyFullBucketIndex = 0;
  627. while (bucketSplatIndex < section.splatCount) {
  628. let currentPartiallyFilledBucketSize = section.partiallyFilledBucketLengths[partiallyFullBucketIndex];
  629. if (localSplatIndex >= bucketSplatIndex && localSplatIndex < bucketSplatIndex + currentPartiallyFilledBucketSize) {
  630. break;
  631. }
  632. bucketSplatIndex += currentPartiallyFilledBucketSize;
  633. bucketIndex++;
  634. partiallyFullBucketIndex++;
  635. }
  636. }
  637. return bucketIndex;
  638. }
  639. getSplatCenter(globalSplatIndex, outCenter, transform) {
  640. const sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex];
  641. const section = this.sections[sectionIndex];
  642. const localSplatIndex = globalSplatIndex - section.splatCountOffset;
  643. const srcSplatCentersBase = section.bytesPerSplat * localSplatIndex;
  644. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase);
  645. const x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel);
  646. const y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel);
  647. const z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel);
  648. if (this.compressionLevel >= 1) {
  649. const bucketIndex = this.getBucketIndex(section, localSplatIndex);
  650. const bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats;
  651. const sf = section.compressionScaleFactor;
  652. const sr = section.compressionScaleRange;
  653. outCenter.x = (x - sr) * sf + section.bucketArray[bucketBase];
  654. outCenter.y = (y - sr) * sf + section.bucketArray[bucketBase + 1];
  655. outCenter.z = (z - sr) * sf + section.bucketArray[bucketBase + 2];
  656. } else {
  657. outCenter.x = x;
  658. outCenter.y = y;
  659. outCenter.z = z;
  660. }
  661. if (transform) outCenter.applyMatrix4(transform);
  662. }
  663. getSplatScaleAndRotation = function() {
  664. const scaleMatrix = new THREE.Matrix4();
  665. const rotationMatrix = new THREE.Matrix4();
  666. const tempMatrix = new THREE.Matrix4();
  667. const tempPosition = new THREE.Vector3();
  668. const scale = new THREE.Vector3();
  669. const rotation = new THREE.Quaternion();
  670. return function(index, outScale, outRotation, transform, scaleOverride) {
  671. const sectionIndex = this.globalSplatIndexToSectionMap[index];
  672. const section = this.sections[sectionIndex];
  673. const localSplatIndex = index - section.splatCountOffset;
  674. const srcSplatScalesBase = section.bytesPerSplat * localSplatIndex +
  675. SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes;
  676. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase);
  677. scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel),
  678. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel),
  679. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel));
  680. if (scaleOverride) {
  681. if (scaleOverride.x !== undefined) scale.x = scaleOverride.x;
  682. if (scaleOverride.y !== undefined) scale.y = scaleOverride.y;
  683. if (scaleOverride.z !== undefined) scale.z = scaleOverride.z;
  684. }
  685. rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel),
  686. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel),
  687. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel),
  688. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel));
  689. if (transform) {
  690. scaleMatrix.makeScale(scale.x, scale.y, scale.z);
  691. rotationMatrix.makeRotationFromQuaternion(rotation);
  692. tempMatrix.copy(scaleMatrix).multiply(rotationMatrix).multiply(transform);
  693. tempMatrix.decompose(tempPosition, outRotation, outScale);
  694. } else {
  695. outScale.copy(scale);
  696. outRotation.copy(rotation);
  697. }
  698. };
  699. }();
  700. getSplatColor(globalSplatIndex, outColor) {
  701. const sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex];
  702. const section = this.sections[sectionIndex];
  703. const localSplatIndex = globalSplatIndex - section.splatCountOffset;
  704. const srcSplatColorsBase = section.bytesPerSplat * localSplatIndex +
  705. SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes;
  706. const splatColorsArray = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase, 4);
  707. outColor.set(splatColorsArray[0], splatColorsArray[1],
  708. splatColorsArray[2], splatColorsArray[3]);
  709. }
  710. fillSplatCenterArray(outCenterArray, transform, srcFrom, srcTo, destFrom) {
  711. const splatCount = this.splatCount;
  712. srcFrom = srcFrom || 0;
  713. srcTo = srcTo || splatCount - 1;
  714. if (destFrom === undefined) destFrom = srcFrom;
  715. const center = new THREE.Vector3();
  716. for (let i = srcFrom; i <= srcTo; i++) {
  717. const sectionIndex = this.globalSplatIndexToSectionMap[i];
  718. const section = this.sections[sectionIndex];
  719. const localSplatIndex = i - section.splatCountOffset;
  720. const centerDestBase = (i - srcFrom + destFrom) * SplatBuffer.CenterComponentCount;
  721. const srcSplatCentersBase = section.bytesPerSplat * localSplatIndex;
  722. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase);
  723. const x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel);
  724. const y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel);
  725. const z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel);
  726. if (this.compressionLevel >= 1) {
  727. const bucketIndex = this.getBucketIndex(section, localSplatIndex);
  728. const bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats;
  729. const sf = section.compressionScaleFactor;
  730. const sr = section.compressionScaleRange;
  731. center.x = (x - sr) * sf + section.bucketArray[bucketBase];
  732. center.y = (y - sr) * sf + section.bucketArray[bucketBase + 1];
  733. center.z = (z - sr) * sf + section.bucketArray[bucketBase + 2];
  734. } else {
  735. center.x = x;
  736. center.y = y;
  737. center.z = z;
  738. }
  739. if (transform) {
  740. center.applyMatrix4(transform);
  741. }
  742. outCenterArray[centerDestBase] = center.x;
  743. outCenterArray[centerDestBase + 1] = center.y;
  744. outCenterArray[centerDestBase + 2] = center.z;
  745. }
  746. }
  747. fillSplatScaleRotationArray = function() {
  748. const scaleMatrix = new THREE.Matrix4();
  749. const rotationMatrix = new THREE.Matrix4();
  750. const tempMatrix = new THREE.Matrix4();
  751. const scale = new THREE.Vector3();
  752. const rotation = new THREE.Quaternion();
  753. const tempPosition = new THREE.Vector3();
  754. const ensurePositiveW = (quaternion) => {
  755. const flip = quaternion.w < 0 ? -1 : 1;
  756. quaternion.x *= flip;
  757. quaternion.y *= flip;
  758. quaternion.z *= flip;
  759. quaternion.w *= flip;
  760. };
  761. return function(outScaleArray, outRotationArray, transform, srcFrom, srcTo, destFrom,
  762. desiredOutputCompressionLevel, scaleOverride) {
  763. const splatCount = this.splatCount;
  764. srcFrom = srcFrom || 0;
  765. srcTo = srcTo || splatCount - 1;
  766. if (destFrom === undefined) destFrom = srcFrom;
  767. const outputConversion = (value, srcCompressionLevel) => {
  768. if (srcCompressionLevel === undefined) srcCompressionLevel = this.compressionLevel;
  769. return convertBetweenCompressionLevels(value, srcCompressionLevel, desiredOutputCompressionLevel);
  770. };
  771. for (let i = srcFrom; i <= srcTo; i++) {
  772. const sectionIndex = this.globalSplatIndexToSectionMap[i];
  773. const section = this.sections[sectionIndex];
  774. const localSplatIndex = i - section.splatCountOffset;
  775. const srcSplatScalesBase = section.bytesPerSplat * localSplatIndex +
  776. SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes;
  777. const scaleDestBase = (i - srcFrom + destFrom) * SplatBuffer.ScaleComponentCount;
  778. const rotationDestBase = (i - srcFrom + destFrom) * SplatBuffer.RotationComponentCount;
  779. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase);
  780. const srcScaleX = (scaleOverride && scaleOverride.x !== undefined) ? scaleOverride.x :
  781. dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel);
  782. const srcScaleY = (scaleOverride && scaleOverride.y !== undefined) ? scaleOverride.y :
  783. dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel);
  784. const srcScaleZ = (scaleOverride && scaleOverride.z !== undefined) ? scaleOverride.z :
  785. dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel);
  786. const srcRotationW = dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel);
  787. const srcRotationX = dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel);
  788. const srcRotationY = dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel);
  789. const srcRotationZ = dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel);
  790. scale.set(toUncompressedFloat(srcScaleX, this.compressionLevel),
  791. toUncompressedFloat(srcScaleY, this.compressionLevel),
  792. toUncompressedFloat(srcScaleZ, this.compressionLevel));
  793. rotation.set(toUncompressedFloat(srcRotationX, this.compressionLevel),
  794. toUncompressedFloat(srcRotationY, this.compressionLevel),
  795. toUncompressedFloat(srcRotationZ, this.compressionLevel),
  796. toUncompressedFloat(srcRotationW, this.compressionLevel)).normalize();
  797. if (transform) {
  798. tempPosition.set(0, 0, 0);
  799. scaleMatrix.makeScale(scale.x, scale.y, scale.z);
  800. rotationMatrix.makeRotationFromQuaternion(rotation);
  801. tempMatrix.identity().premultiply(scaleMatrix).premultiply(rotationMatrix);
  802. tempMatrix.premultiply(transform);
  803. tempMatrix.decompose(tempPosition, rotation, scale);
  804. rotation.normalize();
  805. }
  806. ensurePositiveW(rotation);
  807. if (outScaleArray) {
  808. outScaleArray[scaleDestBase] = outputConversion(scale.x, 0);
  809. outScaleArray[scaleDestBase + 1] = outputConversion(scale.y, 0);
  810. outScaleArray[scaleDestBase + 2] = outputConversion(scale.z, 0);
  811. }
  812. if (outRotationArray) {
  813. outRotationArray[rotationDestBase] = outputConversion(rotation.x, 0);
  814. outRotationArray[rotationDestBase + 1] = outputConversion(rotation.y, 0);
  815. outRotationArray[rotationDestBase + 2] = outputConversion(rotation.z, 0);
  816. outRotationArray[rotationDestBase + 3] = outputConversion(rotation.w, 0);
  817. }
  818. }
  819. };
  820. }();
  821. static computeCovariance = function() {
  822. const tempMatrix4 = new THREE.Matrix4();
  823. const scaleMatrix = new THREE.Matrix3();
  824. const rotationMatrix = new THREE.Matrix3();
  825. const covarianceMatrix = new THREE.Matrix3();
  826. const transformedCovariance = new THREE.Matrix3();
  827. const transform3x3 = new THREE.Matrix3();
  828. const transform3x3Transpose = new THREE.Matrix3();
  829. return function(scale, rotation, transform, outCovariance, outOffset = 0, desiredOutputCompressionLevel) {
  830. tempMatrix4.makeScale(scale.x, scale.y, scale.z);
  831. scaleMatrix.setFromMatrix4(tempMatrix4);
  832. tempMatrix4.makeRotationFromQuaternion(rotation);
  833. rotationMatrix.setFromMatrix4(tempMatrix4);
  834. covarianceMatrix.copy(rotationMatrix).multiply(scaleMatrix);
  835. transformedCovariance.copy(covarianceMatrix).transpose().premultiply(covarianceMatrix);
  836. if (transform) {
  837. transform3x3.setFromMatrix4(transform);
  838. transform3x3Transpose.copy(transform3x3).transpose();
  839. transformedCovariance.multiply(transform3x3Transpose);
  840. transformedCovariance.premultiply(transform3x3);
  841. }
  842. if (desiredOutputCompressionLevel >= 1) {
  843. outCovariance[outOffset] = toHalfFloat(transformedCovariance.elements[0]);
  844. outCovariance[outOffset + 1] = toHalfFloat(transformedCovariance.elements[3]);
  845. outCovariance[outOffset + 2] = toHalfFloat(transformedCovariance.elements[6]);
  846. outCovariance[outOffset + 3] = toHalfFloat(transformedCovariance.elements[4]);
  847. outCovariance[outOffset + 4] = toHalfFloat(transformedCovariance.elements[7]);
  848. outCovariance[outOffset + 5] = toHalfFloat(transformedCovariance.elements[8]);
  849. } else {
  850. outCovariance[outOffset] = transformedCovariance.elements[0];
  851. outCovariance[outOffset + 1] = transformedCovariance.elements[3];
  852. outCovariance[outOffset + 2] = transformedCovariance.elements[6];
  853. outCovariance[outOffset + 3] = transformedCovariance.elements[4];
  854. outCovariance[outOffset + 4] = transformedCovariance.elements[7];
  855. outCovariance[outOffset + 5] = transformedCovariance.elements[8];
  856. }
  857. };
  858. }();
  859. fillSplatCovarianceArray(covarianceArray, transform, srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) {
  860. const splatCount = this.splatCount;
  861. const scale = new THREE.Vector3();
  862. const rotation = new THREE.Quaternion();
  863. srcFrom = srcFrom || 0;
  864. srcTo = srcTo || splatCount - 1;
  865. if (destFrom === undefined) destFrom = srcFrom;
  866. for (let i = srcFrom; i <= srcTo; i++) {
  867. const sectionIndex = this.globalSplatIndexToSectionMap[i];
  868. const section = this.sections[sectionIndex];
  869. const localSplatIndex = i - section.splatCountOffset;
  870. const covarianceDestBase = (i - srcFrom + destFrom) * SplatBuffer.CovarianceComponentCount;
  871. const srcSplatScalesBase = section.bytesPerSplat * localSplatIndex +
  872. SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes;
  873. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase);
  874. scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel),
  875. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel),
  876. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel));
  877. rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel),
  878. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel),
  879. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel),
  880. toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel));
  881. SplatBuffer.computeCovariance(scale, rotation, transform, covarianceArray, covarianceDestBase, desiredOutputCompressionLevel);
  882. }
  883. }
  884. fillSplatColorArray(outColorArray, minimumAlpha, srcFrom, srcTo, destFrom) {
  885. const splatCount = this.splatCount;
  886. srcFrom = srcFrom || 0;
  887. srcTo = srcTo || splatCount - 1;
  888. if (destFrom === undefined) destFrom = srcFrom;
  889. for (let i = srcFrom; i <= srcTo; i++) {
  890. const sectionIndex = this.globalSplatIndexToSectionMap[i];
  891. const section = this.sections[sectionIndex];
  892. const localSplatIndex = i - section.splatCountOffset;
  893. const colorDestBase = (i - srcFrom + destFrom) * SplatBuffer.ColorComponentCount;
  894. const srcSplatColorsBase = section.bytesPerSplat * localSplatIndex +
  895. SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes;
  896. const dataView = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase);
  897. let alpha = dataView[3];
  898. alpha = (alpha >= minimumAlpha) ? alpha : 0;
  899. outColorArray[colorDestBase] = dataView[0];
  900. outColorArray[colorDestBase + 1] = dataView[1];
  901. outColorArray[colorDestBase + 2] = dataView[2];
  902. outColorArray[colorDestBase + 3] = alpha;
  903. }
  904. }
  905. fillSphericalHarmonicsArray = function() {
  906. const sphericalHarmonicVectors = [];
  907. for (let i = 0; i < 15; i++) {
  908. sphericalHarmonicVectors[i] = new THREE.Vector3();
  909. }
  910. const tempMatrix3 = new THREE.Matrix3();
  911. const tempMatrix4 = new THREE.Matrix4();
  912. const tempTranslation = new THREE.Vector3();
  913. const tempScale = new THREE.Vector3();
  914. const tempRotation = new THREE.Quaternion();
  915. const sh11 = [];
  916. const sh12 = [];
  917. const sh13 = [];
  918. const sh21 = [];
  919. const sh22 = [];
  920. const sh23 = [];
  921. const sh24 = [];
  922. const sh25 = [];
  923. const shIn1 = [];
  924. const shIn2 = [];
  925. const shIn3 = [];
  926. const shIn4 = [];
  927. const shIn5 = [];
  928. const shOut1 = [];
  929. const shOut2 = [];
  930. const shOut3 = [];
  931. const shOut4 = [];
  932. const shOut5 = [];
  933. const noop = (v) => v;
  934. const set3 = (array, val1, val2, val3) => {
  935. array[0] = val1;
  936. array[1] = val2;
  937. array[2] = val3;
  938. };
  939. const set3FromArray = (array, srcDestView, stride, srcBase, compressionLevel) => {
  940. array[0] = dataViewFloatForCompressionLevel(srcDestView, srcBase, compressionLevel, true);
  941. array[1] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride, compressionLevel, true);
  942. array[2] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride + stride, compressionLevel, true);
  943. };
  944. const copy3 = (srcArray, destArray) => {
  945. destArray[0] = srcArray[0];
  946. destArray[1] = srcArray[1];
  947. destArray[2] = srcArray[2];
  948. };
  949. const setOutput3 = (srcArray, destArray, destBase, conversionFunc) => {
  950. destArray[destBase] = conversionFunc(srcArray[0]);
  951. destArray[destBase + 1] = conversionFunc(srcArray[1]);
  952. destArray[destBase + 2] = conversionFunc(srcArray[2]);
  953. };
  954. const toUncompressedFloatArray3 = (src, dest, compressionLevel, range8BitMin, range8BitMax) => {
  955. dest[0] = toUncompressedFloat(src[0], compressionLevel, true, range8BitMin, range8BitMax);
  956. dest[1] = toUncompressedFloat(src[1], compressionLevel, true, range8BitMin, range8BitMax);
  957. dest[2] = toUncompressedFloat(src[2], compressionLevel, true, range8BitMin, range8BitMax);
  958. return dest;
  959. };
  960. return function(outSphericalHarmonicsArray, outSphericalHarmonicsDegree, transform,
  961. srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) {
  962. const splatCount = this.splatCount;
  963. srcFrom = srcFrom || 0;
  964. srcTo = srcTo || splatCount - 1;
  965. if (destFrom === undefined) destFrom = srcFrom;
  966. if (transform && outSphericalHarmonicsDegree >= 1) {
  967. tempMatrix4.copy(transform);
  968. tempMatrix4.decompose(tempTranslation, tempRotation, tempScale);
  969. tempRotation.normalize();
  970. tempMatrix4.makeRotationFromQuaternion(tempRotation);
  971. tempMatrix3.setFromMatrix4(tempMatrix4);
  972. set3(sh11, tempMatrix3.elements[4], -tempMatrix3.elements[7], tempMatrix3.elements[1]);
  973. set3(sh12, -tempMatrix3.elements[5], tempMatrix3.elements[8], -tempMatrix3.elements[2]);
  974. set3(sh13, tempMatrix3.elements[3], -tempMatrix3.elements[6], tempMatrix3.elements[0]);
  975. }
  976. const localFromHalfFloatToUint8 = (v) => {
  977. return fromHalfFloatToUint8(v, this.minSphericalHarmonicsCoeff, this.maxSphericalHarmonicsCoeff);
  978. };
  979. const localToUint8 = (v) => {
  980. return toUint8(v, this.minSphericalHarmonicsCoeff, this.maxSphericalHarmonicsCoeff);
  981. };
  982. for (let i = srcFrom; i <= srcTo; i++) {
  983. const sectionIndex = this.globalSplatIndexToSectionMap[i];
  984. const section = this.sections[sectionIndex];
  985. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, section.sphericalHarmonicsDegree);
  986. const outSphericalHarmonicsComponentsCount = getSphericalHarmonicsComponentCountForDegree(outSphericalHarmonicsDegree);
  987. const localSplatIndex = i - section.splatCountOffset;
  988. const srcSplatSHBase = section.bytesPerSplat * localSplatIndex +
  989. SplatBuffer.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes;
  990. const dataView = new DataView(this.bufferData, section.dataBase + srcSplatSHBase);
  991. const shDestBase = (i - srcFrom + destFrom) * outSphericalHarmonicsComponentsCount;
  992. let compressionLevelForOutputConversion = transform ? 0 : this.compressionLevel;
  993. let outputConversionFunc = noop;
  994. if (compressionLevelForOutputConversion !== desiredOutputCompressionLevel) {
  995. if (compressionLevelForOutputConversion === 1) {
  996. if (desiredOutputCompressionLevel === 0) outputConversionFunc = fromHalfFloat$1;
  997. else if (desiredOutputCompressionLevel == 2) outputConversionFunc = localFromHalfFloatToUint8;
  998. } else if (compressionLevelForOutputConversion === 0) {
  999. if (desiredOutputCompressionLevel === 1) outputConversionFunc = toHalfFloat;
  1000. else if (desiredOutputCompressionLevel == 2) outputConversionFunc = localToUint8;
  1001. }
  1002. }
  1003. const minShCoeff = this.minSphericalHarmonicsCoeff;
  1004. const maxShCoeff = this.maxSphericalHarmonicsCoeff;
  1005. if (outSphericalHarmonicsDegree >= 1) {
  1006. set3FromArray(shIn1, dataView, 3, 0, this.compressionLevel);
  1007. set3FromArray(shIn2, dataView, 3, 1, this.compressionLevel);
  1008. set3FromArray(shIn3, dataView, 3, 2, this.compressionLevel);
  1009. if (transform) {
  1010. toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel, minShCoeff, maxShCoeff);
  1011. toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel, minShCoeff, maxShCoeff);
  1012. toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel, minShCoeff, maxShCoeff);
  1013. SplatBuffer.rotateSphericalHarmonics3(shIn1, shIn2, shIn3, sh11, sh12, sh13, shOut1, shOut2, shOut3);
  1014. } else {
  1015. copy3(shIn1, shOut1);
  1016. copy3(shIn2, shOut2);
  1017. copy3(shIn3, shOut3);
  1018. }
  1019. setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase, outputConversionFunc);
  1020. setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 3, outputConversionFunc);
  1021. setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 6, outputConversionFunc);
  1022. if (outSphericalHarmonicsDegree >= 2) {
  1023. set3FromArray(shIn1, dataView, 5, 9, this.compressionLevel);
  1024. set3FromArray(shIn2, dataView, 5, 10, this.compressionLevel);
  1025. set3FromArray(shIn3, dataView, 5, 11, this.compressionLevel);
  1026. set3FromArray(shIn4, dataView, 5, 12, this.compressionLevel);
  1027. set3FromArray(shIn5, dataView, 5, 13, this.compressionLevel);
  1028. if (transform) {
  1029. toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel, minShCoeff, maxShCoeff);
  1030. toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel, minShCoeff, maxShCoeff);
  1031. toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel, minShCoeff, maxShCoeff);
  1032. toUncompressedFloatArray3(shIn4, shIn4, this.compressionLevel, minShCoeff, maxShCoeff);
  1033. toUncompressedFloatArray3(shIn5, shIn5, this.compressionLevel, minShCoeff, maxShCoeff);
  1034. SplatBuffer.rotateSphericalHarmonics5(shIn1, shIn2, shIn3, shIn4, shIn5,
  1035. sh11, sh12, sh13, sh21, sh22, sh23, sh24, sh25,
  1036. shOut1, shOut2, shOut3, shOut4, shOut5);
  1037. } else {
  1038. copy3(shIn1, shOut1);
  1039. copy3(shIn2, shOut2);
  1040. copy3(shIn3, shOut3);
  1041. copy3(shIn4, shOut4);
  1042. copy3(shIn5, shOut5);
  1043. }
  1044. setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase + 9, outputConversionFunc);
  1045. setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 12, outputConversionFunc);
  1046. setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 15, outputConversionFunc);
  1047. setOutput3(shOut4, outSphericalHarmonicsArray, shDestBase + 18, outputConversionFunc);
  1048. setOutput3(shOut5, outSphericalHarmonicsArray, shDestBase + 21, outputConversionFunc);
  1049. }
  1050. }
  1051. }
  1052. };
  1053. }();
  1054. static dot3 = (v1, v2, v3, transformRow, outArray) => {
  1055. outArray[0] = outArray[1] = outArray[2] = 0;
  1056. const t0 = transformRow[0];
  1057. const t1 = transformRow[1];
  1058. const t2 = transformRow[2];
  1059. SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray);
  1060. SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray);
  1061. SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray);
  1062. };
  1063. static addInto3 = (val1, val2, val3, destArray) => {
  1064. destArray[0] = destArray[0] + val1;
  1065. destArray[1] = destArray[1] + val2;
  1066. destArray[2] = destArray[2] + val3;
  1067. };
  1068. static dot5 = (v1, v2, v3, v4, v5, transformRow, outArray) => {
  1069. outArray[0] = outArray[1] = outArray[2] = 0;
  1070. const t0 = transformRow[0];
  1071. const t1 = transformRow[1];
  1072. const t2 = transformRow[2];
  1073. const t3 = transformRow[3];
  1074. const t4 = transformRow[4];
  1075. SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray);
  1076. SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray);
  1077. SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray);
  1078. SplatBuffer.addInto3(v4[0] * t3, v4[1] * t3, v4[2] * t3, outArray);
  1079. SplatBuffer.addInto3(v5[0] * t4, v5[1] * t4, v5[2] * t4, outArray);
  1080. };
  1081. static rotateSphericalHarmonics3 = (in1, in2, in3, tsh11, tsh12, tsh13, out1, out2, out3) => {
  1082. SplatBuffer.dot3(in1, in2, in3, tsh11, out1);
  1083. SplatBuffer.dot3(in1, in2, in3, tsh12, out2);
  1084. SplatBuffer.dot3(in1, in2, in3, tsh13, out3);
  1085. };
  1086. static rotateSphericalHarmonics5 = (in1, in2, in3, in4, in5, tsh11, tsh12, tsh13,
  1087. tsh21, tsh22, tsh23, tsh24, tsh25, out1, out2, out3, out4, out5) => {
  1088. const kSqrt0104 = Math.sqrt(1.0 / 4.0);
  1089. const kSqrt0304 = Math.sqrt(3.0 / 4.0);
  1090. const kSqrt0103 = Math.sqrt(1.0 / 3.0);
  1091. const kSqrt0403 = Math.sqrt(4.0 / 3.0);
  1092. const kSqrt0112 = Math.sqrt(1.0 / 12.0);
  1093. tsh21[0] = kSqrt0104 * ((tsh13[2] * tsh11[0] + tsh13[0] * tsh11[2]) + (tsh11[2] * tsh13[0] + tsh11[0] * tsh13[2]));
  1094. tsh21[1] = (tsh13[1] * tsh11[0] + tsh11[1] * tsh13[0]);
  1095. tsh21[2] = kSqrt0304 * (tsh13[1] * tsh11[1] + tsh11[1] * tsh13[1]);
  1096. tsh21[3] = (tsh13[1] * tsh11[2] + tsh11[1] * tsh13[2]);
  1097. tsh21[4] = kSqrt0104 * ((tsh13[2] * tsh11[2] - tsh13[0] * tsh11[0]) + (tsh11[2] * tsh13[2] - tsh11[0] * tsh13[0]));
  1098. SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh21, out1);
  1099. tsh22[0] = kSqrt0104 * ((tsh12[2] * tsh11[0] + tsh12[0] * tsh11[2]) + (tsh11[2] * tsh12[0] + tsh11[0] * tsh12[2]));
  1100. tsh22[1] = tsh12[1] * tsh11[0] + tsh11[1] * tsh12[0];
  1101. tsh22[2] = kSqrt0304 * (tsh12[1] * tsh11[1] + tsh11[1] * tsh12[1]);
  1102. tsh22[3] = tsh12[1] * tsh11[2] + tsh11[1] * tsh12[2];
  1103. tsh22[4] = kSqrt0104 * ((tsh12[2] * tsh11[2] - tsh12[0] * tsh11[0]) + (tsh11[2] * tsh12[2] - tsh11[0] * tsh12[0]));
  1104. SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh22, out2);
  1105. tsh23[0] = kSqrt0103 * (tsh12[2] * tsh12[0] + tsh12[0] * tsh12[2]) + -kSqrt0112 *
  1106. ((tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2]) + (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2]));
  1107. tsh23[1] = kSqrt0403 * tsh12[1] * tsh12[0] + -kSqrt0103 * (tsh13[1] * tsh13[0] + tsh11[1] * tsh11[0]);
  1108. tsh23[2] = tsh12[1] * tsh12[1] + -kSqrt0104 * (tsh13[1] * tsh13[1] + tsh11[1] * tsh11[1]);
  1109. tsh23[3] = kSqrt0403 * tsh12[1] * tsh12[2] + -kSqrt0103 * (tsh13[1] * tsh13[2] + tsh11[1] * tsh11[2]);
  1110. tsh23[4] = kSqrt0103 * (tsh12[2] * tsh12[2] - tsh12[0] * tsh12[0]) + -kSqrt0112 *
  1111. ((tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0]) + (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0]));
  1112. SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh23, out3);
  1113. tsh24[0] = kSqrt0104 * ((tsh12[2] * tsh13[0] + tsh12[0] * tsh13[2]) + (tsh13[2] * tsh12[0] + tsh13[0] * tsh12[2]));
  1114. tsh24[1] = tsh12[1] * tsh13[0] + tsh13[1] * tsh12[0];
  1115. tsh24[2] = kSqrt0304 * (tsh12[1] * tsh13[1] + tsh13[1] * tsh12[1]);
  1116. tsh24[3] = tsh12[1] * tsh13[2] + tsh13[1] * tsh12[2];
  1117. tsh24[4] = kSqrt0104 * ((tsh12[2] * tsh13[2] - tsh12[0] * tsh13[0]) + (tsh13[2] * tsh12[2] - tsh13[0] * tsh12[0]));
  1118. SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh24, out4);
  1119. tsh25[0] = kSqrt0104 * ((tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2]) - (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2]));
  1120. tsh25[1] = (tsh13[1] * tsh13[0] - tsh11[1] * tsh11[0]);
  1121. tsh25[2] = kSqrt0304 * (tsh13[1] * tsh13[1] - tsh11[1] * tsh11[1]);
  1122. tsh25[3] = (tsh13[1] * tsh13[2] - tsh11[1] * tsh11[2]);
  1123. tsh25[4] = kSqrt0104 * ((tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0]) - (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0]));
  1124. SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh25, out5);
  1125. };
  1126. static parseHeader(buffer) {
  1127. const headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes);
  1128. const headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2);
  1129. const headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  1130. const headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  1131. const versionMajor = headerArrayUint8[0];
  1132. const versionMinor = headerArrayUint8[1];
  1133. const maxSectionCount = headerArrayUint32[1];
  1134. const sectionCount = headerArrayUint32[2];
  1135. const maxSplatCount = headerArrayUint32[3];
  1136. const splatCount = headerArrayUint32[4];
  1137. const compressionLevel = headerArrayUint16[10];
  1138. const sceneCenter = new THREE.Vector3(headerArrayFloat32[6], headerArrayFloat32[7], headerArrayFloat32[8]);
  1139. const minSphericalHarmonicsCoeff = headerArrayFloat32[9] || -DefaultSphericalHarmonics8BitCompressionHalfRange;
  1140. const maxSphericalHarmonicsCoeff = headerArrayFloat32[10] || DefaultSphericalHarmonics8BitCompressionHalfRange;
  1141. return {
  1142. versionMajor,
  1143. versionMinor,
  1144. maxSectionCount,
  1145. sectionCount,
  1146. maxSplatCount,
  1147. splatCount,
  1148. compressionLevel,
  1149. sceneCenter,
  1150. minSphericalHarmonicsCoeff,
  1151. maxSphericalHarmonicsCoeff
  1152. };
  1153. }
  1154. static writeHeaderCountsToBuffer(sectionCount, splatCount, buffer) {
  1155. const headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  1156. headerArrayUint32[2] = sectionCount;
  1157. headerArrayUint32[4] = splatCount;
  1158. }
  1159. static writeHeaderToBuffer(header, buffer) {
  1160. const headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes);
  1161. const headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2);
  1162. const headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  1163. const headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  1164. headerArrayUint8[0] = header.versionMajor;
  1165. headerArrayUint8[1] = header.versionMinor;
  1166. headerArrayUint8[2] = 0; // unused for now
  1167. headerArrayUint8[3] = 0; // unused for now
  1168. headerArrayUint32[1] = header.maxSectionCount;
  1169. headerArrayUint32[2] = header.sectionCount;
  1170. headerArrayUint32[3] = header.maxSplatCount;
  1171. headerArrayUint32[4] = header.splatCount;
  1172. headerArrayUint16[10] = header.compressionLevel;
  1173. headerArrayFloat32[6] = header.sceneCenter.x;
  1174. headerArrayFloat32[7] = header.sceneCenter.y;
  1175. headerArrayFloat32[8] = header.sceneCenter.z;
  1176. headerArrayFloat32[9] = header.minSphericalHarmonicsCoeff || -DefaultSphericalHarmonics8BitCompressionHalfRange;
  1177. headerArrayFloat32[10] = header.maxSphericalHarmonicsCoeff || DefaultSphericalHarmonics8BitCompressionHalfRange;
  1178. }
  1179. static parseSectionHeaders(header, buffer, offset = 0, secLoadedCountsToMax) {
  1180. const compressionLevel = header.compressionLevel;
  1181. const maxSectionCount = header.maxSectionCount;
  1182. const sectionHeaderArrayUint16 = new Uint16Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 2);
  1183. const sectionHeaderArrayUint32 = new Uint32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4);
  1184. const sectionHeaderArrayFloat32 = new Float32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4);
  1185. const sectionHeaders = [];
  1186. let sectionHeaderBase = 0;
  1187. let sectionHeaderBaseUint16 = sectionHeaderBase / 2;
  1188. let sectionHeaderBaseUint32 = sectionHeaderBase / 4;
  1189. let sectionBase = SplatBuffer.HeaderSizeBytes + header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes;
  1190. let splatCountOffset = 0;
  1191. for (let i = 0; i < maxSectionCount; i++) {
  1192. const maxSplatCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 1];
  1193. const bucketSize = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 2];
  1194. const bucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 3];
  1195. const bucketBlockSize = sectionHeaderArrayFloat32[sectionHeaderBaseUint32 + 4];
  1196. const halfBucketBlockSize = bucketBlockSize / 2.0;
  1197. const bucketStorageSizeBytes = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 10];
  1198. const compressionScaleRange = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 6] ||
  1199. SplatBuffer.CompressionLevels[compressionLevel].ScaleRange;
  1200. const fullBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 8];
  1201. const partiallyFilledBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 9];
  1202. const bucketsMetaDataSizeBytes = partiallyFilledBucketCount * 4;
  1203. const bucketsStorageSizeBytes = bucketStorageSizeBytes * bucketCount + bucketsMetaDataSizeBytes;
  1204. const sphericalHarmonicsDegree = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 20];
  1205. const { bytesPerSplat } = SplatBuffer.calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree);
  1206. const splatDataStorageSizeBytes = bytesPerSplat * maxSplatCount;
  1207. const storageSizeBytes = splatDataStorageSizeBytes + bucketsStorageSizeBytes;
  1208. const sectionHeader = {
  1209. bytesPerSplat: bytesPerSplat,
  1210. splatCountOffset: splatCountOffset,
  1211. splatCount: secLoadedCountsToMax ? maxSplatCount : 0,
  1212. maxSplatCount: maxSplatCount,
  1213. bucketSize: bucketSize,
  1214. bucketCount: bucketCount,
  1215. bucketBlockSize: bucketBlockSize,
  1216. halfBucketBlockSize: halfBucketBlockSize,
  1217. bucketStorageSizeBytes: bucketStorageSizeBytes,
  1218. bucketsStorageSizeBytes: bucketsStorageSizeBytes,
  1219. splatDataStorageSizeBytes: splatDataStorageSizeBytes,
  1220. storageSizeBytes: storageSizeBytes,
  1221. compressionScaleRange: compressionScaleRange,
  1222. compressionScaleFactor: halfBucketBlockSize / compressionScaleRange,
  1223. base: sectionBase,
  1224. bucketsBase: sectionBase + bucketsMetaDataSizeBytes,
  1225. dataBase: sectionBase + bucketsStorageSizeBytes,
  1226. fullBucketCount: fullBucketCount,
  1227. partiallyFilledBucketCount: partiallyFilledBucketCount,
  1228. sphericalHarmonicsDegree: sphericalHarmonicsDegree
  1229. };
  1230. sectionHeaders[i] = sectionHeader;
  1231. sectionBase += storageSizeBytes;
  1232. sectionHeaderBase += SplatBuffer.SectionHeaderSizeBytes;
  1233. sectionHeaderBaseUint16 = sectionHeaderBase / 2;
  1234. sectionHeaderBaseUint32 = sectionHeaderBase / 4;
  1235. splatCountOffset += maxSplatCount;
  1236. }
  1237. return sectionHeaders;
  1238. }
  1239. static writeSectionHeaderToBuffer(sectionHeader, compressionLevel, buffer, offset = 0) {
  1240. const sectionHeadeArrayUint16 = new Uint16Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 2);
  1241. const sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  1242. const sectionHeadeArrayFloat32 = new Float32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  1243. sectionHeadeArrayUint32[0] = sectionHeader.splatCount;
  1244. sectionHeadeArrayUint32[1] = sectionHeader.maxSplatCount;
  1245. sectionHeadeArrayUint32[2] = compressionLevel >= 1 ? sectionHeader.bucketSize : 0;
  1246. sectionHeadeArrayUint32[3] = compressionLevel >= 1 ? sectionHeader.bucketCount : 0;
  1247. sectionHeadeArrayFloat32[4] = compressionLevel >= 1 ? sectionHeader.bucketBlockSize : 0.0;
  1248. sectionHeadeArrayUint16[10] = compressionLevel >= 1 ? SplatBuffer.BucketStorageSizeBytes : 0;
  1249. sectionHeadeArrayUint32[6] = compressionLevel >= 1 ? sectionHeader.compressionScaleRange : 0;
  1250. sectionHeadeArrayUint32[7] = sectionHeader.storageSizeBytes;
  1251. sectionHeadeArrayUint32[8] = compressionLevel >= 1 ? sectionHeader.fullBucketCount : 0;
  1252. sectionHeadeArrayUint32[9] = compressionLevel >= 1 ? sectionHeader.partiallyFilledBucketCount : 0;
  1253. sectionHeadeArrayUint16[20] = sectionHeader.sphericalHarmonicsDegree;
  1254. }
  1255. static writeSectionHeaderSplatCountToBuffer(splatCount, buffer, offset = 0) {
  1256. const sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  1257. sectionHeadeArrayUint32[0] = splatCount;
  1258. }
  1259. constructFromBuffer(bufferData, secLoadedCountsToMax) {
  1260. this.bufferData = bufferData;
  1261. this.globalSplatIndexToLocalSplatIndexMap = [];
  1262. this.globalSplatIndexToSectionMap = [];
  1263. const header = SplatBuffer.parseHeader(this.bufferData);
  1264. this.versionMajor = header.versionMajor;
  1265. this.versionMinor = header.versionMinor;
  1266. this.maxSectionCount = header.maxSectionCount;
  1267. this.sectionCount = secLoadedCountsToMax ? header.maxSectionCount : 0;
  1268. this.maxSplatCount = header.maxSplatCount;
  1269. this.splatCount = secLoadedCountsToMax ? header.maxSplatCount : 0;
  1270. this.compressionLevel = header.compressionLevel;
  1271. this.sceneCenter = new THREE.Vector3().copy(header.sceneCenter);
  1272. this.minSphericalHarmonicsCoeff = header.minSphericalHarmonicsCoeff;
  1273. this.maxSphericalHarmonicsCoeff = header.maxSphericalHarmonicsCoeff;
  1274. this.sections = SplatBuffer.parseSectionHeaders(header, this.bufferData, SplatBuffer.HeaderSizeBytes, secLoadedCountsToMax);
  1275. this.linkBufferArrays();
  1276. this.buildMaps();
  1277. }
  1278. static calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree) {
  1279. const bytesPerCenter = SplatBuffer.CompressionLevels[compressionLevel].BytesPerCenter;
  1280. const bytesPerScale = SplatBuffer.CompressionLevels[compressionLevel].BytesPerScale;
  1281. const bytesPerRotation = SplatBuffer.CompressionLevels[compressionLevel].BytesPerRotation;
  1282. const bytesPerColor = SplatBuffer.CompressionLevels[compressionLevel].BytesPerColor;
  1283. const sphericalHarmonicsComponentsPerSplat = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree);
  1284. const sphericalHarmonicsBytesPerSplat = SplatBuffer.CompressionLevels[compressionLevel].BytesPerSphericalHarmonicsComponent *
  1285. sphericalHarmonicsComponentsPerSplat;
  1286. const bytesPerSplat = bytesPerCenter + bytesPerScale + bytesPerRotation +
  1287. bytesPerColor + sphericalHarmonicsBytesPerSplat;
  1288. return {
  1289. bytesPerCenter,
  1290. bytesPerScale,
  1291. bytesPerRotation,
  1292. bytesPerColor,
  1293. sphericalHarmonicsComponentsPerSplat,
  1294. sphericalHarmonicsBytesPerSplat,
  1295. bytesPerSplat
  1296. };
  1297. }
  1298. linkBufferArrays() {
  1299. for (let i = 0; i < this.maxSectionCount; i++) {
  1300. const section = this.sections[i];
  1301. section.bucketArray = new Float32Array(this.bufferData, section.bucketsBase,
  1302. section.bucketCount * SplatBuffer.BucketStorageSizeFloats);
  1303. if (section.partiallyFilledBucketCount > 0) {
  1304. section.partiallyFilledBucketLengths = new Uint32Array(this.bufferData, section.base,
  1305. section.partiallyFilledBucketCount);
  1306. }
  1307. }
  1308. }
  1309. buildMaps() {
  1310. let cumulativeSplatCount = 0;
  1311. for (let i = 0; i < this.maxSectionCount; i++) {
  1312. const section = this.sections[i];
  1313. for (let j = 0; j < section.maxSplatCount; j++) {
  1314. const globalSplatIndex = cumulativeSplatCount + j;
  1315. this.globalSplatIndexToLocalSplatIndexMap[globalSplatIndex] = j;
  1316. this.globalSplatIndexToSectionMap[globalSplatIndex] = i;
  1317. }
  1318. cumulativeSplatCount += section.maxSplatCount;
  1319. }
  1320. }
  1321. updateLoadedCounts(newSectionCount, newSplatCount) {
  1322. SplatBuffer.writeHeaderCountsToBuffer(newSectionCount, newSplatCount, this.bufferData);
  1323. this.sectionCount = newSectionCount;
  1324. this.splatCount = newSplatCount;
  1325. }
  1326. updateSectionLoadedCounts(sectionIndex, newSplatCount) {
  1327. const sectionHeaderOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * sectionIndex;
  1328. SplatBuffer.writeSectionHeaderSplatCountToBuffer(newSplatCount, this.bufferData, sectionHeaderOffset);
  1329. this.sections[sectionIndex].splatCount = newSplatCount;
  1330. }
  1331. static writeSplatDataToSectionBuffer = function() {
  1332. const tempCenterBuffer = new ArrayBuffer(12);
  1333. const tempScaleBuffer = new ArrayBuffer(12);
  1334. const tempRotationBuffer = new ArrayBuffer(16);
  1335. const tempColorBuffer = new ArrayBuffer(4);
  1336. const tempSHBuffer = new ArrayBuffer(256);
  1337. const tempRot = new THREE.Quaternion();
  1338. const tempScale = new THREE.Vector3();
  1339. const bucketCenterDelta = new THREE.Vector3();
  1340. const {
  1341. X: OFFSET_X, Y: OFFSET_Y, Z: OFFSET_Z,
  1342. SCALE0: OFFSET_SCALE0, SCALE1: OFFSET_SCALE1, SCALE2: OFFSET_SCALE2,
  1343. ROTATION0: OFFSET_ROT0, ROTATION1: OFFSET_ROT1, ROTATION2: OFFSET_ROT2, ROTATION3: OFFSET_ROT3,
  1344. FDC0: OFFSET_FDC0, FDC1: OFFSET_FDC1, FDC2: OFFSET_FDC2, OPACITY: OFFSET_OPACITY,
  1345. FRC0: OFFSET_FRC0, FRC9: OFFSET_FRC9,
  1346. } = UncompressedSplatArray.OFFSET;
  1347. const compressPositionOffset = (v, compressionScaleFactor, compressionScaleRange) => {
  1348. const doubleCompressionScaleRange = compressionScaleRange * 2 + 1;
  1349. v = Math.round(v * compressionScaleFactor) + compressionScaleRange;
  1350. return clamp(v, 0, doubleCompressionScaleRange);
  1351. };
  1352. return function(targetSplat, sectionBuffer, bufferOffset, compressionLevel, sphericalHarmonicsDegree,
  1353. bucketCenter, compressionScaleFactor, compressionScaleRange,
  1354. minSphericalHarmonicsCoeff = -DefaultSphericalHarmonics8BitCompressionHalfRange,
  1355. maxSphericalHarmonicsCoeff = DefaultSphericalHarmonics8BitCompressionHalfRange) {
  1356. const sphericalHarmonicsComponentsPerSplat = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree);
  1357. const bytesPerCenter = SplatBuffer.CompressionLevels[compressionLevel].BytesPerCenter;
  1358. const bytesPerScale = SplatBuffer.CompressionLevels[compressionLevel].BytesPerScale;
  1359. const bytesPerRotation = SplatBuffer.CompressionLevels[compressionLevel].BytesPerRotation;
  1360. const bytesPerColor = SplatBuffer.CompressionLevels[compressionLevel].BytesPerColor;
  1361. const centerBase = bufferOffset;
  1362. const scaleBase = centerBase + bytesPerCenter;
  1363. const rotationBase = scaleBase + bytesPerScale;
  1364. const colorBase = rotationBase + bytesPerRotation;
  1365. const sphericalHarmonicsBase = colorBase + bytesPerColor;
  1366. if (targetSplat[OFFSET_ROT0] !== undefined) {
  1367. tempRot.set(targetSplat[OFFSET_ROT0], targetSplat[OFFSET_ROT1], targetSplat[OFFSET_ROT2], targetSplat[OFFSET_ROT3]);
  1368. tempRot.normalize();
  1369. } else {
  1370. tempRot.set(1.0, 0.0, 0.0, 0.0);
  1371. }
  1372. if (targetSplat[OFFSET_SCALE0] !== undefined) {
  1373. tempScale.set(targetSplat[OFFSET_SCALE0] || 0,
  1374. targetSplat[OFFSET_SCALE1] || 0,
  1375. targetSplat[OFFSET_SCALE2] || 0);
  1376. } else {
  1377. tempScale.set(0, 0, 0);
  1378. }
  1379. if (compressionLevel === 0) {
  1380. const center = new Float32Array(sectionBuffer, centerBase, SplatBuffer.CenterComponentCount);
  1381. const rot = new Float32Array(sectionBuffer, rotationBase, SplatBuffer.RotationComponentCount);
  1382. const scale = new Float32Array(sectionBuffer, scaleBase, SplatBuffer.ScaleComponentCount);
  1383. rot.set([tempRot.x, tempRot.y, tempRot.z, tempRot.w]);
  1384. scale.set([tempScale.x, tempScale.y, tempScale.z]);
  1385. center.set([targetSplat[OFFSET_X], targetSplat[OFFSET_Y], targetSplat[OFFSET_Z]]);
  1386. if (sphericalHarmonicsDegree > 0) {
  1387. const shOut = new Float32Array(sectionBuffer, sphericalHarmonicsBase, sphericalHarmonicsComponentsPerSplat);
  1388. if (sphericalHarmonicsDegree >= 1) {
  1389. for (let s = 0; s < 9; s++) shOut[s] = targetSplat[OFFSET_FRC0 + s] || 0;
  1390. if (sphericalHarmonicsDegree >= 2) {
  1391. for (let s = 0; s < 15; s++) shOut[s + 9] = targetSplat[OFFSET_FRC9 + s] || 0;
  1392. }
  1393. }
  1394. }
  1395. } else {
  1396. const center = new Uint16Array(tempCenterBuffer, 0, SplatBuffer.CenterComponentCount);
  1397. const rot = new Uint16Array(tempRotationBuffer, 0, SplatBuffer.RotationComponentCount);
  1398. const scale = new Uint16Array(tempScaleBuffer, 0, SplatBuffer.ScaleComponentCount);
  1399. rot.set([toHalfFloat(tempRot.x), toHalfFloat(tempRot.y), toHalfFloat(tempRot.z), toHalfFloat(tempRot.w)]);
  1400. scale.set([toHalfFloat(tempScale.x), toHalfFloat(tempScale.y), toHalfFloat(tempScale.z)]);
  1401. bucketCenterDelta.set(targetSplat[OFFSET_X], targetSplat[OFFSET_Y], targetSplat[OFFSET_Z]).sub(bucketCenter);
  1402. bucketCenterDelta.x = compressPositionOffset(bucketCenterDelta.x, compressionScaleFactor, compressionScaleRange);
  1403. bucketCenterDelta.y = compressPositionOffset(bucketCenterDelta.y, compressionScaleFactor, compressionScaleRange);
  1404. bucketCenterDelta.z = compressPositionOffset(bucketCenterDelta.z, compressionScaleFactor, compressionScaleRange);
  1405. center.set([bucketCenterDelta.x, bucketCenterDelta.y, bucketCenterDelta.z]);
  1406. if (sphericalHarmonicsDegree > 0) {
  1407. const SHArrayType = compressionLevel === 1 ? Uint16Array : Uint8Array;
  1408. const bytesPerSHComponent = compressionLevel === 1 ? 2 : 1;
  1409. const shOut = new SHArrayType(tempSHBuffer, 0, sphericalHarmonicsComponentsPerSplat);
  1410. if (sphericalHarmonicsDegree >= 1) {
  1411. for (let s = 0; s < 9; s++) {
  1412. const srcVal = targetSplat[OFFSET_FRC0 + s] || 0;
  1413. shOut[s] = compressionLevel === 1 ? toHalfFloat(srcVal) :
  1414. toUint8(srcVal, minSphericalHarmonicsCoeff, maxSphericalHarmonicsCoeff);
  1415. }
  1416. const degree1ByteCount = 9 * bytesPerSHComponent;
  1417. copyBetweenBuffers(shOut.buffer, 0, sectionBuffer, sphericalHarmonicsBase, degree1ByteCount);
  1418. if (sphericalHarmonicsDegree >= 2) {
  1419. for (let s = 0; s < 15; s++) {
  1420. const srcVal = targetSplat[OFFSET_FRC9 + s] || 0;
  1421. shOut[s + 9] = compressionLevel === 1 ? toHalfFloat(srcVal) :
  1422. toUint8(srcVal, minSphericalHarmonicsCoeff, maxSphericalHarmonicsCoeff);
  1423. }
  1424. copyBetweenBuffers(shOut.buffer, degree1ByteCount, sectionBuffer,
  1425. sphericalHarmonicsBase + degree1ByteCount, 15 * bytesPerSHComponent);
  1426. }
  1427. }
  1428. }
  1429. copyBetweenBuffers(center.buffer, 0, sectionBuffer, centerBase, 6);
  1430. copyBetweenBuffers(scale.buffer, 0, sectionBuffer, scaleBase, 6);
  1431. copyBetweenBuffers(rot.buffer, 0, sectionBuffer, rotationBase, 8);
  1432. }
  1433. const rgba = new Uint8ClampedArray(tempColorBuffer, 0, 4);
  1434. rgba.set([targetSplat[OFFSET_FDC0] || 0, targetSplat[OFFSET_FDC1] || 0, targetSplat[OFFSET_FDC2] || 0]);
  1435. rgba[3] = targetSplat[OFFSET_OPACITY] || 0;
  1436. copyBetweenBuffers(rgba.buffer, 0, sectionBuffer, colorBase, 4);
  1437. };
  1438. }();
  1439. static generateFromUncompressedSplatArrays(splatArrays, minimumAlpha, compressionLevel,
  1440. sceneCenter, blockSize, bucketSize, options = []) {
  1441. let shDegree = 0;
  1442. for (let sa = 0; sa < splatArrays.length; sa ++) {
  1443. const splatArray = splatArrays[sa];
  1444. shDegree = Math.max(splatArray.sphericalHarmonicsDegree, shDegree);
  1445. }
  1446. let minSphericalHarmonicsCoeff;
  1447. let maxSphericalHarmonicsCoeff;
  1448. for (let sa = 0; sa < splatArrays.length; sa ++) {
  1449. const splatArray = splatArrays[sa];
  1450. for (let i = 0; i < splatArray.splats.length; i++) {
  1451. const splat = splatArray.splats[i];
  1452. for (let sc = UncompressedSplatArray.OFFSET.FRC0; sc < UncompressedSplatArray.OFFSET.FRC23 && sc < splat.length; sc++) {
  1453. if (!minSphericalHarmonicsCoeff || splat[sc] < minSphericalHarmonicsCoeff) {
  1454. minSphericalHarmonicsCoeff = splat[sc];
  1455. }
  1456. if (!maxSphericalHarmonicsCoeff || splat[sc] > maxSphericalHarmonicsCoeff) {
  1457. maxSphericalHarmonicsCoeff = splat[sc];
  1458. }
  1459. }
  1460. }
  1461. }
  1462. minSphericalHarmonicsCoeff = minSphericalHarmonicsCoeff || -DefaultSphericalHarmonics8BitCompressionHalfRange;
  1463. maxSphericalHarmonicsCoeff = maxSphericalHarmonicsCoeff || DefaultSphericalHarmonics8BitCompressionHalfRange;
  1464. const { bytesPerSplat } = SplatBuffer.calculateComponentStorage(compressionLevel, shDegree);
  1465. const compressionScaleRange = SplatBuffer.CompressionLevels[compressionLevel].ScaleRange;
  1466. const sectionBuffers = [];
  1467. const sectionHeaderBuffers = [];
  1468. let totalSplatCount = 0;
  1469. for (let sa = 0; sa < splatArrays.length; sa ++) {
  1470. const splatArray = splatArrays[sa];
  1471. const validSplats = new UncompressedSplatArray(shDegree);
  1472. for (let i = 0; i < splatArray.splatCount; i++) {
  1473. const targetSplat = splatArray.splats[i];
  1474. if ((targetSplat[UncompressedSplatArray.OFFSET.OPACITY] || 0) >= minimumAlpha) {
  1475. validSplats.addSplat(targetSplat);
  1476. }
  1477. }
  1478. const sectionOptions = options[sa] || {};
  1479. const sectionBlockSize = (sectionOptions.blockSizeFactor || 1) * (blockSize || SplatBuffer.BucketBlockSize);
  1480. const sectionBucketSize = Math.ceil((sectionOptions.bucketSizeFactor || 1) * (bucketSize || SplatBuffer.BucketSize));
  1481. const bucketInfo = SplatBuffer.computeBucketsForUncompressedSplatArray(validSplats, sectionBlockSize, sectionBucketSize);
  1482. const fullBucketCount = bucketInfo.fullBuckets.length;
  1483. const partiallyFullBucketLengths = bucketInfo.partiallyFullBuckets.map((bucket) => bucket.splats.length);
  1484. const partiallyFilledBucketCount = partiallyFullBucketLengths.length;
  1485. const buckets = [...bucketInfo.fullBuckets, ...bucketInfo.partiallyFullBuckets];
  1486. const sectionDataSizeBytes = validSplats.splats.length * bytesPerSplat;
  1487. const bucketMetaDataSizeBytes = partiallyFilledBucketCount * 4;
  1488. const bucketDataBytes = compressionLevel >= 1 ? buckets.length *
  1489. SplatBuffer.BucketStorageSizeBytes + bucketMetaDataSizeBytes : 0;
  1490. const sectionSizeBytes = sectionDataSizeBytes + bucketDataBytes;
  1491. const sectionBuffer = new ArrayBuffer(sectionSizeBytes);
  1492. const compressionScaleFactor = compressionScaleRange / (sectionBlockSize * 0.5);
  1493. const bucketCenter = new THREE.Vector3();
  1494. let outSplatCount = 0;
  1495. for (let b = 0; b < buckets.length; b++) {
  1496. const bucket = buckets[b];
  1497. bucketCenter.fromArray(bucket.center);
  1498. for (let i = 0; i < bucket.splats.length; i++) {
  1499. let row = bucket.splats[i];
  1500. const targetSplat = validSplats.splats[row];
  1501. const bufferOffset = bucketDataBytes + outSplatCount * bytesPerSplat;
  1502. SplatBuffer.writeSplatDataToSectionBuffer(targetSplat, sectionBuffer, bufferOffset, compressionLevel, shDegree,
  1503. bucketCenter, compressionScaleFactor, compressionScaleRange,
  1504. minSphericalHarmonicsCoeff, maxSphericalHarmonicsCoeff);
  1505. outSplatCount++;
  1506. }
  1507. }
  1508. totalSplatCount += outSplatCount;
  1509. if (compressionLevel >= 1) {
  1510. const bucketMetaDataArray = new Uint32Array(sectionBuffer, 0, partiallyFullBucketLengths.length * 4);
  1511. for (let pfb = 0; pfb < partiallyFullBucketLengths.length; pfb ++) {
  1512. bucketMetaDataArray[pfb] = partiallyFullBucketLengths[pfb];
  1513. }
  1514. const bucketArray = new Float32Array(sectionBuffer, bucketMetaDataSizeBytes,
  1515. buckets.length * SplatBuffer.BucketStorageSizeFloats);
  1516. for (let b = 0; b < buckets.length; b++) {
  1517. const bucket = buckets[b];
  1518. const base = b * 3;
  1519. bucketArray[base] = bucket.center[0];
  1520. bucketArray[base + 1] = bucket.center[1];
  1521. bucketArray[base + 2] = bucket.center[2];
  1522. }
  1523. }
  1524. sectionBuffers.push(sectionBuffer);
  1525. const sectionHeaderBuffer = new ArrayBuffer(SplatBuffer.SectionHeaderSizeBytes);
  1526. SplatBuffer.writeSectionHeaderToBuffer({
  1527. maxSplatCount: outSplatCount,
  1528. splatCount: outSplatCount,
  1529. bucketSize: sectionBucketSize,
  1530. bucketCount: buckets.length,
  1531. bucketBlockSize: sectionBlockSize,
  1532. compressionScaleRange: compressionScaleRange,
  1533. storageSizeBytes: sectionSizeBytes,
  1534. fullBucketCount: fullBucketCount,
  1535. partiallyFilledBucketCount: partiallyFilledBucketCount,
  1536. sphericalHarmonicsDegree: shDegree
  1537. }, compressionLevel, sectionHeaderBuffer, 0);
  1538. sectionHeaderBuffers.push(sectionHeaderBuffer);
  1539. }
  1540. let sectionsCumulativeSizeBytes = 0;
  1541. for (let sectionBuffer of sectionBuffers) sectionsCumulativeSizeBytes += sectionBuffer.byteLength;
  1542. const unifiedBufferSize = SplatBuffer.HeaderSizeBytes +
  1543. SplatBuffer.SectionHeaderSizeBytes * sectionBuffers.length + sectionsCumulativeSizeBytes;
  1544. const unifiedBuffer = new ArrayBuffer(unifiedBufferSize);
  1545. SplatBuffer.writeHeaderToBuffer({
  1546. versionMajor: 0,
  1547. versionMinor: 1,
  1548. maxSectionCount: sectionBuffers.length,
  1549. sectionCount: sectionBuffers.length,
  1550. maxSplatCount: totalSplatCount,
  1551. splatCount: totalSplatCount,
  1552. compressionLevel: compressionLevel,
  1553. sceneCenter: sceneCenter,
  1554. minSphericalHarmonicsCoeff: minSphericalHarmonicsCoeff,
  1555. maxSphericalHarmonicsCoeff: maxSphericalHarmonicsCoeff
  1556. }, unifiedBuffer);
  1557. let currentUnifiedBase = SplatBuffer.HeaderSizeBytes;
  1558. for (let sectionHeaderBuffer of sectionHeaderBuffers) {
  1559. new Uint8Array(unifiedBuffer, currentUnifiedBase, SplatBuffer.SectionHeaderSizeBytes).set(new Uint8Array(sectionHeaderBuffer));
  1560. currentUnifiedBase += SplatBuffer.SectionHeaderSizeBytes;
  1561. }
  1562. for (let sectionBuffer of sectionBuffers) {
  1563. new Uint8Array(unifiedBuffer, currentUnifiedBase, sectionBuffer.byteLength).set(new Uint8Array(sectionBuffer));
  1564. currentUnifiedBase += sectionBuffer.byteLength;
  1565. }
  1566. const splatBuffer = new SplatBuffer(unifiedBuffer);
  1567. return splatBuffer;
  1568. }
  1569. static computeBucketsForUncompressedSplatArray(splatArray, blockSize, bucketSize) {
  1570. let splatCount = splatArray.splatCount;
  1571. const halfBlockSize = blockSize / 2.0;
  1572. const min = new THREE.Vector3();
  1573. const max = new THREE.Vector3();
  1574. for (let i = 0; i < splatCount; i++) {
  1575. const targetSplat = splatArray.splats[i];
  1576. const center = [targetSplat[UncompressedSplatArray.OFFSET.X],
  1577. targetSplat[UncompressedSplatArray.OFFSET.Y],
  1578. targetSplat[UncompressedSplatArray.OFFSET.Z]];
  1579. if (i === 0 || center[0] < min.x) min.x = center[0];
  1580. if (i === 0 || center[0] > max.x) max.x = center[0];
  1581. if (i === 0 || center[1] < min.y) min.y = center[1];
  1582. if (i === 0 || center[1] > max.y) max.y = center[1];
  1583. if (i === 0 || center[2] < min.z) min.z = center[2];
  1584. if (i === 0 || center[2] > max.z) max.z = center[2];
  1585. }
  1586. const dimensions = new THREE.Vector3().copy(max).sub(min);
  1587. const yBlocks = Math.ceil(dimensions.y / blockSize);
  1588. const zBlocks = Math.ceil(dimensions.z / blockSize);
  1589. const blockCenter = new THREE.Vector3();
  1590. const fullBuckets = [];
  1591. const partiallyFullBuckets = {};
  1592. for (let i = 0; i < splatCount; i++) {
  1593. const targetSplat = splatArray.splats[i];
  1594. const center = [targetSplat[UncompressedSplatArray.OFFSET.X],
  1595. targetSplat[UncompressedSplatArray.OFFSET.Y],
  1596. targetSplat[UncompressedSplatArray.OFFSET.Z]];
  1597. const xBlock = Math.floor((center[0] - min.x) / blockSize);
  1598. const yBlock = Math.floor((center[1] - min.y) / blockSize);
  1599. const zBlock = Math.floor((center[2] - min.z) / blockSize);
  1600. blockCenter.x = xBlock * blockSize + min.x + halfBlockSize;
  1601. blockCenter.y = yBlock * blockSize + min.y + halfBlockSize;
  1602. blockCenter.z = zBlock * blockSize + min.z + halfBlockSize;
  1603. const bucketId = xBlock * (yBlocks * zBlocks) + yBlock * zBlocks + zBlock;
  1604. let bucket = partiallyFullBuckets[bucketId];
  1605. if (!bucket) {
  1606. partiallyFullBuckets[bucketId] = bucket = {
  1607. 'splats': [],
  1608. 'center': blockCenter.toArray()
  1609. };
  1610. }
  1611. bucket.splats.push(i);
  1612. if (bucket.splats.length >= bucketSize) {
  1613. fullBuckets.push(bucket);
  1614. partiallyFullBuckets[bucketId] = null;
  1615. }
  1616. }
  1617. const partiallyFullBucketArray = [];
  1618. for (let bucketId in partiallyFullBuckets) {
  1619. if (partiallyFullBuckets.hasOwnProperty(bucketId)) {
  1620. const bucket = partiallyFullBuckets[bucketId];
  1621. if (bucket) {
  1622. partiallyFullBucketArray.push(bucket);
  1623. }
  1624. }
  1625. }
  1626. return {
  1627. 'fullBuckets': fullBuckets,
  1628. 'partiallyFullBuckets': partiallyFullBucketArray,
  1629. };
  1630. }
  1631. }
  1632. const HeaderMagicBytes = new Uint8Array([112, 108, 121, 10]);
  1633. const HeaderEndTokenBytes = new Uint8Array([10, 101, 110, 100, 95, 104, 101, 97, 100, 101, 114, 10]);
  1634. const HeaderEndToken = 'end_header';
  1635. const DataTypeMap = new Map([
  1636. ['char', Int8Array],
  1637. ['uchar', Uint8Array],
  1638. ['short', Int16Array],
  1639. ['ushort', Uint16Array],
  1640. ['int', Int32Array],
  1641. ['uint', Uint32Array],
  1642. ['float', Float32Array],
  1643. ['double', Float64Array],
  1644. ]);
  1645. const unpackUnorm = (value, bits) => {
  1646. const t = (1 << bits) - 1;
  1647. return (value & t) / t;
  1648. };
  1649. const unpack111011 = (result, value) => {
  1650. result.x = unpackUnorm(value >>> 21, 11);
  1651. result.y = unpackUnorm(value >>> 11, 10);
  1652. result.z = unpackUnorm(value, 11);
  1653. };
  1654. const unpack8888 = (result, value) => {
  1655. result.x = unpackUnorm(value >>> 24, 8);
  1656. result.y = unpackUnorm(value >>> 16, 8);
  1657. result.z = unpackUnorm(value >>> 8, 8);
  1658. result.w = unpackUnorm(value, 8);
  1659. };
  1660. // unpack quaternion with 2,10,10,10 format (largest element, 3x10bit element)
  1661. const unpackRot = (result, value) => {
  1662. const norm = 1.0 / (Math.sqrt(2) * 0.5);
  1663. const a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm;
  1664. const b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm;
  1665. const c = (unpackUnorm(value, 10) - 0.5) * norm;
  1666. const m = Math.sqrt(1.0 - (a * a + b * b + c * c));
  1667. switch (value >>> 30) {
  1668. case 0:
  1669. result.set(m, a, b, c);
  1670. break;
  1671. case 1:
  1672. result.set(a, m, b, c);
  1673. break;
  1674. case 2:
  1675. result.set(a, b, m, c);
  1676. break;
  1677. case 3:
  1678. result.set(a, b, c, m);
  1679. break;
  1680. }
  1681. };
  1682. const lerp = (a, b, t) => {
  1683. return a * (1 - t) + b * t;
  1684. };
  1685. const getElementPropStorage = (element, name) => {
  1686. return element.properties.find((p) => p.name === name && p.storage)
  1687. ?.storage;
  1688. };
  1689. class PlayCanvasCompressedPlyParser {
  1690. static decodeHeaderText(headerText) {
  1691. let element;
  1692. let chunkElement;
  1693. let vertexElement;
  1694. const headerLines = headerText.split('\n').filter((line) => !line.startsWith('comment '));
  1695. let bytesPerSplat = 0;
  1696. let done = false;
  1697. for (let i = 1; i < headerLines.length; ++i) {
  1698. const words = headerLines[i].split(' ');
  1699. switch (words[0]) {
  1700. case 'format':
  1701. if (words[1] !== 'binary_little_endian') {
  1702. throw new Error('Unsupported ply format');
  1703. }
  1704. break;
  1705. case 'element':
  1706. element = {
  1707. name: words[1],
  1708. count: parseInt(words[2], 10),
  1709. properties: [],
  1710. storageSizeBytes: 0
  1711. };
  1712. if (element.name === 'chunk') chunkElement = element;
  1713. else if (element.name === 'vertex') vertexElement = element;
  1714. break;
  1715. case 'property': {
  1716. if (!DataTypeMap.has(words[1])) {
  1717. throw new Error(
  1718. `Unrecognized property data type '${words[1]}' in ply header`
  1719. );
  1720. }
  1721. const StorageType = DataTypeMap.get(words[1]);
  1722. const storageSizeByes = StorageType.BYTES_PER_ELEMENT * element.count;
  1723. if (element.name === 'vertex') bytesPerSplat += StorageType.BYTES_PER_ELEMENT;
  1724. element.properties.push({
  1725. type: words[1],
  1726. name: words[2],
  1727. storage: null,
  1728. byteSize: StorageType.BYTES_PER_ELEMENT,
  1729. storageSizeByes: storageSizeByes
  1730. });
  1731. element.storageSizeBytes += storageSizeByes;
  1732. break;
  1733. }
  1734. case HeaderEndToken:
  1735. done = true;
  1736. break;
  1737. default:
  1738. throw new Error(
  1739. `Unrecognized header value '${words[0]}' in ply header`
  1740. );
  1741. }
  1742. if (done) break;
  1743. }
  1744. return {
  1745. 'chunkElement': chunkElement,
  1746. 'vertexElement': vertexElement,
  1747. 'bytesPerSplat': bytesPerSplat,
  1748. 'headerSizeBytes': headerText.indexOf(HeaderEndToken) + HeaderEndToken.length + 1,
  1749. 'sphericalHarmonicsDegree': 0
  1750. };
  1751. }
  1752. static decodeHeader(plyBuffer) {
  1753. /**
  1754. * Searches for the first occurrence of a sequence within a buffer.
  1755. * @example
  1756. * find(new Uint8Array([1, 2, 3, 4]), new Uint8Array([3, 4])); // 2
  1757. * @param {Uint8Array} buf - The buffer in which to search.
  1758. * @param {Uint8Array} search - The sequence to search for.
  1759. * @return {number} The index of the first occurrence of the search sequence in the buffer, or -1 if not found.
  1760. */
  1761. const find = (buf, search) => {
  1762. const endIndex = buf.length - search.length;
  1763. let i;
  1764. let j;
  1765. for (i = 0; i <= endIndex; ++i) {
  1766. for (j = 0; j < search.length; ++j) {
  1767. if (buf[i + j] !== search[j]) {
  1768. break;
  1769. }
  1770. }
  1771. if (j === search.length) {
  1772. return i;
  1773. }
  1774. }
  1775. return -1;
  1776. };
  1777. /**
  1778. * Checks if array 'a' starts with the same elements as array 'b'.
  1779. * @example
  1780. * startsWith(new Uint8Array([1, 2, 3, 4]), new Uint8Array([1, 2])); // true
  1781. * @param {Uint8Array} a - The array to check against.
  1782. * @param {Uint8Array} b - The array of elements to look for at the start of 'a'.
  1783. * @return {boolean} - True if 'a' starts with all elements of 'b', otherwise false.
  1784. */
  1785. const startsWith = (a, b) => {
  1786. if (a.length < b.length) {
  1787. return false;
  1788. }
  1789. for (let i = 0; i < b.length; ++i) {
  1790. if (a[i] !== b[i]) {
  1791. return false;
  1792. }
  1793. }
  1794. return true;
  1795. };
  1796. let buf = new Uint8Array(plyBuffer);
  1797. let endHeaderTokenOffset;
  1798. if (buf.length >= HeaderMagicBytes.length && !startsWith(buf, HeaderMagicBytes)) {
  1799. throw new Error('Invalid PLY header');
  1800. }
  1801. endHeaderTokenOffset = find(buf, HeaderEndTokenBytes);
  1802. if (endHeaderTokenOffset === -1) {
  1803. throw new Error('End of PLY header not found');
  1804. }
  1805. const headerText = new TextDecoder('ascii').decode(
  1806. buf.slice(0, endHeaderTokenOffset)
  1807. );
  1808. const {chunkElement, vertexElement, bytesPerSplat} = PlayCanvasCompressedPlyParser.decodeHeaderText(headerText);
  1809. return {
  1810. 'headerSizeBytes': endHeaderTokenOffset + HeaderEndTokenBytes.length,
  1811. 'bytesPerSplat': bytesPerSplat,
  1812. 'chunkElement': chunkElement,
  1813. 'vertexElement': vertexElement
  1814. };
  1815. }
  1816. static readElementData(element, readBuffer, readOffset, fromIndex, toIndex, propertyFilter = null) {
  1817. let dataView = readBuffer instanceof DataView ? readBuffer : new DataView(readBuffer);
  1818. fromIndex = fromIndex || 0;
  1819. toIndex = toIndex || element.count - 1;
  1820. for (let e = fromIndex; e <= toIndex; ++e) {
  1821. for (let j = 0; j < element.properties.length; ++j) {
  1822. const property = element.properties[j];
  1823. const StorageType = DataTypeMap.get(property.type);
  1824. const requiredStorageSizeBytes = StorageType.BYTES_PER_ELEMENT * element.count;
  1825. if ((!property.storage || property.storage.byteLength < requiredStorageSizeBytes) &&
  1826. (!propertyFilter || propertyFilter(property.name))) {
  1827. property.storage = new StorageType(element.count);
  1828. }
  1829. if (property.storage) {
  1830. switch (property.type) {
  1831. case 'char':
  1832. property.storage[e] = dataView.getInt8(readOffset);
  1833. break;
  1834. case 'uchar':
  1835. property.storage[e] = dataView.getUint8(readOffset);
  1836. break;
  1837. case 'short':
  1838. property.storage[e] = dataView.getInt16(readOffset, true);
  1839. break;
  1840. case 'ushort':
  1841. property.storage[e] = dataView.getUint16(readOffset, true);
  1842. break;
  1843. case 'int':
  1844. property.storage[e] = dataView.getInt32(readOffset, true);
  1845. break;
  1846. case 'uint':
  1847. property.storage[e] = dataView.getUint32(readOffset, true);
  1848. break;
  1849. case 'float':
  1850. property.storage[e] = dataView.getFloat32(readOffset, true);
  1851. break;
  1852. case 'double':
  1853. property.storage[e] = dataView.getFloat64(readOffset, true);
  1854. break;
  1855. }
  1856. }
  1857. readOffset += property.byteSize;
  1858. }
  1859. }
  1860. return readOffset;
  1861. }
  1862. static readPly(plyBuffer, propertyFilter = null) {
  1863. const header = PlayCanvasCompressedPlyParser.decodeHeader(plyBuffer);
  1864. let readIndex = PlayCanvasCompressedPlyParser.readElementData(header.chunkElement, plyBuffer,
  1865. header.headerSizeBytes, null, null, propertyFilter);
  1866. PlayCanvasCompressedPlyParser.readElementData(header.vertexElement, plyBuffer, readIndex, null, null, propertyFilter);
  1867. return {
  1868. 'chunkElement': header.chunkElement,
  1869. 'vertexElement': header.vertexElement
  1870. };
  1871. }
  1872. static getElementStorageArrays(chunkElement, vertexElement) {
  1873. const minX = getElementPropStorage(chunkElement, 'min_x');
  1874. const minY = getElementPropStorage(chunkElement, 'min_y');
  1875. const minZ = getElementPropStorage(chunkElement, 'min_z');
  1876. const maxX = getElementPropStorage(chunkElement, 'max_x');
  1877. const maxY = getElementPropStorage(chunkElement, 'max_y');
  1878. const maxZ = getElementPropStorage(chunkElement, 'max_z');
  1879. const minScaleX = getElementPropStorage(chunkElement, 'min_scale_x');
  1880. const minScaleY = getElementPropStorage(chunkElement, 'min_scale_y');
  1881. const minScaleZ = getElementPropStorage(chunkElement, 'min_scale_z');
  1882. const maxScaleX = getElementPropStorage(chunkElement, 'max_scale_x');
  1883. const maxScaleY = getElementPropStorage(chunkElement, 'max_scale_y');
  1884. const maxScaleZ = getElementPropStorage(chunkElement, 'max_scale_z');
  1885. const position = getElementPropStorage(vertexElement, 'packed_position');
  1886. const rotation = getElementPropStorage(vertexElement, 'packed_rotation');
  1887. const scale = getElementPropStorage(vertexElement, 'packed_scale');
  1888. const color = getElementPropStorage(vertexElement, 'packed_color');
  1889. return {
  1890. positionExtremes: {
  1891. minX, maxX,
  1892. minY, maxY,
  1893. minZ, maxZ
  1894. },
  1895. scaleExtremes: {
  1896. minScaleX, maxScaleX, minScaleY,
  1897. maxScaleY, minScaleZ, maxScaleZ
  1898. },
  1899. position,
  1900. rotation,
  1901. scale,
  1902. color
  1903. };
  1904. }
  1905. static decompressSplat = function() {
  1906. const p = new THREE.Vector3();
  1907. const r = new THREE.Quaternion();
  1908. const s = new THREE.Vector3();
  1909. const c = new THREE.Vector4();
  1910. const OFFSET = UncompressedSplatArray.OFFSET;
  1911. return function(index, chunkSplatIndexOffset, positionArray, positionExtremes, scaleArray, scaleExtremes,
  1912. rotationArray, colorArray, outSplat) {
  1913. outSplat = outSplat || UncompressedSplatArray.createSplat();
  1914. const chunkIndex = Math.floor((chunkSplatIndexOffset + index) / 256);
  1915. unpack111011(p, positionArray[index]);
  1916. unpackRot(r, rotationArray[index]);
  1917. unpack111011(s, scaleArray[index]);
  1918. unpack8888(c, colorArray[index]);
  1919. outSplat[OFFSET.X] = lerp(positionExtremes.minX[chunkIndex], positionExtremes.maxX[chunkIndex], p.x);
  1920. outSplat[OFFSET.Y] = lerp(positionExtremes.minY[chunkIndex], positionExtremes.maxY[chunkIndex], p.y);
  1921. outSplat[OFFSET.Z] = lerp(positionExtremes.minZ[chunkIndex], positionExtremes.maxZ[chunkIndex], p.z);
  1922. outSplat[OFFSET.ROTATION0] = r.x;
  1923. outSplat[OFFSET.ROTATION1] = r.y;
  1924. outSplat[OFFSET.ROTATION2] = r.z;
  1925. outSplat[OFFSET.ROTATION3] = r.w;
  1926. outSplat[OFFSET.SCALE0] = Math.exp(lerp(scaleExtremes.minScaleX[chunkIndex], scaleExtremes.maxScaleX[chunkIndex], s.x));
  1927. outSplat[OFFSET.SCALE1] = Math.exp(lerp(scaleExtremes.minScaleY[chunkIndex], scaleExtremes.maxScaleY[chunkIndex], s.y));
  1928. outSplat[OFFSET.SCALE2] = Math.exp(lerp(scaleExtremes.minScaleZ[chunkIndex], scaleExtremes.maxScaleZ[chunkIndex], s.z));
  1929. outSplat[OFFSET.FDC0] = clamp(Math.floor(c.x * 255), 0, 255);
  1930. outSplat[OFFSET.FDC1] = clamp(Math.floor(c.y * 255), 0, 255);
  1931. outSplat[OFFSET.FDC2] = clamp(Math.floor(c.z * 255), 0, 255);
  1932. outSplat[OFFSET.OPACITY] = clamp(Math.floor(c.w * 255), 0, 255);
  1933. return outSplat;
  1934. };
  1935. }();
  1936. static parseToUncompressedSplatBufferSection(chunkElement, vertexElement, fromIndex, toIndex, chunkSplatIndexOffset,
  1937. vertexDataBuffer, veretxReadOffset, outBuffer, outOffset, propertyFilter = null) {
  1938. PlayCanvasCompressedPlyParser.readElementData(vertexElement, vertexDataBuffer, veretxReadOffset, fromIndex, toIndex, propertyFilter);
  1939. const outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  1940. const { positionExtremes, scaleExtremes, position, rotation, scale, color } =
  1941. PlayCanvasCompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement);
  1942. const tempSplat = UncompressedSplatArray.createSplat();
  1943. for (let i = fromIndex; i <= toIndex; ++i) {
  1944. PlayCanvasCompressedPlyParser.decompressSplat(i, chunkSplatIndexOffset, position, positionExtremes,
  1945. scale, scaleExtremes, rotation, color, tempSplat);
  1946. const outBase = i * outBytesPerSplat + outOffset;
  1947. SplatBuffer.writeSplatDataToSectionBuffer(tempSplat, outBuffer, outBase, 0, 0);
  1948. }
  1949. }
  1950. static parseToUncompressedSplatArray(plyBuffer) {
  1951. const { chunkElement, vertexElement } = PlayCanvasCompressedPlyParser.readPly(plyBuffer);
  1952. const splatArray = new UncompressedSplatArray();
  1953. const { positionExtremes, scaleExtremes, position, rotation, scale, color } =
  1954. PlayCanvasCompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement);
  1955. for (let i = 0; i < vertexElement.count; ++i) {
  1956. splatArray.addDefaultSplat();
  1957. const newSplat = splatArray.getSplat(splatArray.splatCount - 1);
  1958. PlayCanvasCompressedPlyParser.decompressSplat(i, 0, position, positionExtremes, scale, scaleExtremes, rotation, color, newSplat);
  1959. }
  1960. const mat = new THREE.Matrix4();
  1961. mat.identity();
  1962. return splatArray;
  1963. }
  1964. }
  1965. const PlyFormat = {
  1966. 'INRIAV1': 0,
  1967. 'INRIAV2': 1,
  1968. 'PlayCanvasCompressed': 2
  1969. };
  1970. const [
  1971. FieldSizeIdDouble, FieldSizeIdInt, FieldSizeIdUInt, FieldSizeIdFloat, FieldSizeIdShort, FieldSizeIdUShort, FieldSizeIdUChar
  1972. ] = [0, 1, 2, 3, 4, 5, 6];
  1973. const FieldSizeStringMap = {
  1974. 'double': FieldSizeIdDouble,
  1975. 'int': FieldSizeIdInt,
  1976. 'uint': FieldSizeIdUInt,
  1977. 'float': FieldSizeIdFloat,
  1978. 'short': FieldSizeIdShort,
  1979. 'ushort': FieldSizeIdUShort,
  1980. 'uchar': FieldSizeIdUChar,
  1981. };
  1982. const FieldSize = {
  1983. [FieldSizeIdDouble]: 8,
  1984. [FieldSizeIdInt]: 4,
  1985. [FieldSizeIdUInt]: 4,
  1986. [FieldSizeIdFloat]: 4,
  1987. [FieldSizeIdShort]: 2,
  1988. [FieldSizeIdUShort]: 2,
  1989. [FieldSizeIdUChar]: 1,
  1990. };
  1991. class PlyParserUtils {
  1992. static HeaderEndToken = 'end_header';
  1993. constructor() {
  1994. }
  1995. decodeSectionHeader(headerLines, fieldNameIdMap, headerStartLine = 0) {
  1996. const extractedLines = [];
  1997. let processingSection = false;
  1998. let headerEndLine = -1;
  1999. let vertexCount = 0;
  2000. let endOfHeader = false;
  2001. let sectionName = null;
  2002. const fieldIds = [];
  2003. const fieldTypes = [];
  2004. const allFieldNames = [];
  2005. const usedFieldNames = [];
  2006. const fieldTypesByName = {};
  2007. for (let i = headerStartLine; i < headerLines.length; i++) {
  2008. const line = headerLines[i].trim();
  2009. if (line.startsWith('element')) {
  2010. if (processingSection) {
  2011. headerEndLine--;
  2012. break;
  2013. } else {
  2014. processingSection = true;
  2015. headerStartLine = i;
  2016. headerEndLine = i;
  2017. const lineComponents = line.split(' ');
  2018. let validComponents = 0;
  2019. for (let lineComponent of lineComponents) {
  2020. const trimmedComponent = lineComponent.trim();
  2021. if (trimmedComponent.length > 0) {
  2022. validComponents++;
  2023. if (validComponents === 2) {
  2024. sectionName = trimmedComponent;
  2025. } else if (validComponents === 3) {
  2026. vertexCount = parseInt(trimmedComponent);
  2027. }
  2028. }
  2029. }
  2030. }
  2031. } else if (line.startsWith('property')) {
  2032. const fieldMatch = line.match(/(\w+)\s+(\w+)\s+(\w+)/);
  2033. if (fieldMatch) {
  2034. const fieldTypeStr = fieldMatch[2];
  2035. const fieldName = fieldMatch[3];
  2036. allFieldNames.push(fieldName);
  2037. const fieldId = fieldNameIdMap[fieldName];
  2038. fieldTypesByName[fieldName] = fieldTypeStr;
  2039. const fieldType = FieldSizeStringMap[fieldTypeStr];
  2040. if (fieldId !== undefined) {
  2041. usedFieldNames.push(fieldName);
  2042. fieldIds.push(fieldId);
  2043. fieldTypes[fieldId] = fieldType;
  2044. }
  2045. }
  2046. }
  2047. if (line === PlyParserUtils.HeaderEndToken) {
  2048. endOfHeader = true;
  2049. break;
  2050. }
  2051. if (processingSection) {
  2052. extractedLines.push(line);
  2053. headerEndLine++;
  2054. }
  2055. }
  2056. const fieldOffsets = [];
  2057. let bytesPerVertex = 0;
  2058. for (let fieldName of allFieldNames) {
  2059. const fieldType = fieldTypesByName[fieldName];
  2060. if (fieldTypesByName.hasOwnProperty(fieldName)) {
  2061. const fieldId = fieldNameIdMap[fieldName];
  2062. if (fieldId !== undefined) {
  2063. fieldOffsets[fieldId] = bytesPerVertex;
  2064. }
  2065. }
  2066. bytesPerVertex += FieldSize[FieldSizeStringMap[fieldType]];
  2067. }
  2068. const sphericalHarmonics = this.decodeSphericalHarmonicsFromSectionHeader(allFieldNames, fieldNameIdMap);
  2069. return {
  2070. 'headerLines': extractedLines,
  2071. 'headerStartLine': headerStartLine,
  2072. 'headerEndLine': headerEndLine,
  2073. 'fieldTypes': fieldTypes,
  2074. 'fieldIds': fieldIds,
  2075. 'fieldOffsets': fieldOffsets,
  2076. 'bytesPerVertex': bytesPerVertex,
  2077. 'vertexCount': vertexCount,
  2078. 'dataSizeBytes': bytesPerVertex * vertexCount,
  2079. 'endOfHeader': endOfHeader,
  2080. 'sectionName': sectionName,
  2081. 'sphericalHarmonicsDegree': sphericalHarmonics.degree,
  2082. 'sphericalHarmonicsCoefficientsPerChannel': sphericalHarmonics.coefficientsPerChannel,
  2083. 'sphericalHarmonicsDegree1Fields': sphericalHarmonics.degree1Fields,
  2084. 'sphericalHarmonicsDegree2Fields': sphericalHarmonics.degree2Fields
  2085. };
  2086. }
  2087. decodeSphericalHarmonicsFromSectionHeader(fieldNames, fieldNameIdMap) {
  2088. let sphericalHarmonicsFieldCount = 0;
  2089. let coefficientsPerChannel = 0;
  2090. for (let fieldName of fieldNames) {
  2091. if (fieldName.startsWith('f_rest')) sphericalHarmonicsFieldCount++;
  2092. }
  2093. coefficientsPerChannel = sphericalHarmonicsFieldCount / 3;
  2094. let degree = 0;
  2095. if (coefficientsPerChannel >= 3) degree = 1;
  2096. if (coefficientsPerChannel >= 8) degree = 2;
  2097. let degree1Fields = [];
  2098. let degree2Fields = [];
  2099. for (let rgb = 0; rgb < 3; rgb++) {
  2100. if (degree >= 1) {
  2101. for (let i = 0; i < 3; i++) {
  2102. degree1Fields.push(fieldNameIdMap['f_rest_' + (i + coefficientsPerChannel * rgb)]);
  2103. }
  2104. }
  2105. if (degree >= 2) {
  2106. for (let i = 0; i < 5; i++) {
  2107. degree2Fields.push(fieldNameIdMap['f_rest_' + (i + coefficientsPerChannel * rgb + 3)]);
  2108. }
  2109. }
  2110. }
  2111. return {
  2112. 'degree': degree,
  2113. 'coefficientsPerChannel': coefficientsPerChannel,
  2114. 'degree1Fields': degree1Fields,
  2115. 'degree2Fields': degree2Fields
  2116. };
  2117. }
  2118. static getHeaderSectionNames(headerLines) {
  2119. const sectionNames = [];
  2120. for (let headerLine of headerLines) {
  2121. if (headerLine.startsWith('element')) {
  2122. const lineComponents = headerLine.split(' ');
  2123. let validComponents = 0;
  2124. for (let lineComponent of lineComponents) {
  2125. const trimmedComponent = lineComponent.trim();
  2126. if (trimmedComponent.length > 0) {
  2127. validComponents++;
  2128. if (validComponents === 2) {
  2129. sectionNames.push(trimmedComponent);
  2130. }
  2131. }
  2132. }
  2133. }
  2134. }
  2135. return sectionNames;
  2136. }
  2137. static checkTextForEndHeader(endHeaderTestText) {
  2138. if (endHeaderTestText.includes(PlyParserUtils.HeaderEndToken)) {
  2139. return true;
  2140. }
  2141. return false;
  2142. }
  2143. static checkBufferForEndHeader(buffer, searchOfset, chunkSize, decoder) {
  2144. const endHeaderTestChunk = new Uint8Array(buffer, Math.max(0, searchOfset - chunkSize), chunkSize);
  2145. const endHeaderTestText = decoder.decode(endHeaderTestChunk);
  2146. return PlyParserUtils.checkTextForEndHeader(endHeaderTestText);
  2147. }
  2148. static extractHeaderFromBufferToText(plyBuffer) {
  2149. const decoder = new TextDecoder();
  2150. let headerOffset = 0;
  2151. let headerText = '';
  2152. const readChunkSize = 100;
  2153. while (true) {
  2154. if (headerOffset + readChunkSize >= plyBuffer.byteLength) {
  2155. throw new Error('End of file reached while searching for end of header');
  2156. }
  2157. const headerChunk = new Uint8Array(plyBuffer, headerOffset, readChunkSize);
  2158. headerText += decoder.decode(headerChunk);
  2159. headerOffset += readChunkSize;
  2160. if (PlyParserUtils.checkBufferForEndHeader(plyBuffer, headerOffset, readChunkSize * 2, decoder)) {
  2161. break;
  2162. }
  2163. }
  2164. return headerText;
  2165. }
  2166. readHeaderFromBuffer(plyBuffer) {
  2167. const decoder = new TextDecoder();
  2168. let headerOffset = 0;
  2169. let headerText = '';
  2170. const readChunkSize = 100;
  2171. while (true) {
  2172. if (headerOffset + readChunkSize >= plyBuffer.byteLength) {
  2173. throw new Error('End of file reached while searching for end of header');
  2174. }
  2175. const headerChunk = new Uint8Array(plyBuffer, headerOffset, readChunkSize);
  2176. headerText += decoder.decode(headerChunk);
  2177. headerOffset += readChunkSize;
  2178. if (PlyParserUtils.checkBufferForEndHeader(plyBuffer, headerOffset, readChunkSize * 2, decoder)) {
  2179. break;
  2180. }
  2181. }
  2182. return headerText;
  2183. }
  2184. static convertHeaderTextToLines(headerText) {
  2185. const headerLines = headerText.split('\n');
  2186. const prunedLines = [];
  2187. for (let i = 0; i < headerLines.length; i++) {
  2188. const line = headerLines[i].trim();
  2189. prunedLines.push(line);
  2190. if (line === PlyParserUtils.HeaderEndToken) {
  2191. break;
  2192. }
  2193. }
  2194. return prunedLines;
  2195. }
  2196. static determineHeaderFormatFromHeaderText(headertText) {
  2197. const headerLines = PlyParserUtils.convertHeaderTextToLines(headertText);
  2198. let format = PlyFormat.INRIAV1;
  2199. for (let i = 0; i < headerLines.length; i++) {
  2200. const line = headerLines[i].trim();
  2201. if (line.startsWith('element chunk') || line.match(/[A-Za-z]*packed_[A-Za-z]*/)) {
  2202. format = PlyFormat.PlayCanvasCompressed;
  2203. } else if (line.startsWith('element codebook_centers')) {
  2204. format = PlyFormat.INRIAV2;
  2205. } else if (line === PlyParserUtils.HeaderEndToken) {
  2206. break;
  2207. }
  2208. }
  2209. return format;
  2210. }
  2211. static determineHeaderFormatFromPlyBuffer(plyBuffer) {
  2212. const headertText = PlyParserUtils.extractHeaderFromBufferToText(plyBuffer);
  2213. return PlyParserUtils.determineHeaderFormatFromHeaderText(headertText);
  2214. }
  2215. static readVertex(vertexData, header, row, dataOffset, fieldsToRead, rawVertex, normalize = true) {
  2216. const offset = row * header.bytesPerVertex + dataOffset;
  2217. const fieldOffsets = header.fieldOffsets;
  2218. const fieldTypes = header.fieldTypes;
  2219. for (let fieldId of fieldsToRead) {
  2220. const fieldType = fieldTypes[fieldId];
  2221. if (fieldType === FieldSizeIdFloat) {
  2222. rawVertex[fieldId] = vertexData.getFloat32(offset + fieldOffsets[fieldId], true);
  2223. } else if (fieldType === FieldSizeIdShort) {
  2224. rawVertex[fieldId] = vertexData.getInt16(offset + fieldOffsets[fieldId], true);
  2225. } else if (fieldType === FieldSizeIdUShort) {
  2226. rawVertex[fieldId] = vertexData.getUint16(offset + fieldOffsets[fieldId], true);
  2227. } else if (fieldType === FieldSizeIdInt) {
  2228. rawVertex[fieldId] = vertexData.getInt32(offset + fieldOffsets[fieldId], true);
  2229. } else if (fieldType === FieldSizeIdUInt) {
  2230. rawVertex[fieldId] = vertexData.getUint32(offset + fieldOffsets[fieldId], true);
  2231. } else if (fieldType === FieldSizeIdUChar) {
  2232. if (normalize) {
  2233. rawVertex[fieldId] = vertexData.getUint8(offset + fieldOffsets[fieldId]) / 255.0;
  2234. } else {
  2235. rawVertex[fieldId] = vertexData.getUint8(offset + fieldOffsets[fieldId]);
  2236. }
  2237. }
  2238. }
  2239. }
  2240. }
  2241. const BaseFieldNamesToRead = ['scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3', 'x', 'y', 'z',
  2242. 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'red', 'green', 'blue', 'f_rest_0', 'filter_3D'];
  2243. const BaseFieldsToReadIndexes = BaseFieldNamesToRead.map((e, i) => i);
  2244. const [
  2245. // eslint-disable-next-line max-len
  2246. SCALE_0, SCALE_1, SCALE_2, ROT_0, ROT_1, ROT_2, ROT_3, X, Y, Z, F_DC_0, F_DC_1, F_DC_2, OPACITY, RED, GREEN, BLUE, F_REST_0, FILTER_3D
  2247. ] = BaseFieldsToReadIndexes;
  2248. class INRIAV1PlyParser {
  2249. constructor() {
  2250. this.plyParserutils = new PlyParserUtils();
  2251. }
  2252. decodeHeaderLines(headerLines) {
  2253. let shLineCount = 0;
  2254. headerLines.forEach((line) => {
  2255. if (line.includes('f_rest_')) shLineCount++;
  2256. });
  2257. let shFieldsToReadCount = 0;
  2258. if (shLineCount >= 45) {
  2259. shFieldsToReadCount = 45;
  2260. } else if (shLineCount >= 24) {
  2261. shFieldsToReadCount = 24;
  2262. } else if (shLineCount >= 9) {
  2263. shFieldsToReadCount = 9;
  2264. }
  2265. const shFieldIndexesToMap = Array.from(Array(Math.max(shFieldsToReadCount - 1, 0)));
  2266. let shRemainingFieldNamesToRead = shFieldIndexesToMap.map((element, index) => `f_rest_${index + 1}`);
  2267. const fieldNamesToRead = [...BaseFieldNamesToRead, ...shRemainingFieldNamesToRead];
  2268. const fieldsToReadIndexes = fieldNamesToRead.map((e, i) => i);
  2269. const fieldNameIdMap = fieldsToReadIndexes.reduce((acc, element) => {
  2270. acc[fieldNamesToRead[element]] = element;
  2271. return acc;
  2272. }, {});
  2273. const header = this.plyParserutils.decodeSectionHeader(headerLines, fieldNameIdMap, 0);
  2274. header.splatCount = header.vertexCount;
  2275. header.bytesPerSplat = header.bytesPerVertex;
  2276. header.fieldsToReadIndexes = fieldsToReadIndexes;
  2277. return header;
  2278. }
  2279. decodeHeaderText(headerText) {
  2280. const headerLines = PlyParserUtils.convertHeaderTextToLines(headerText);
  2281. const header = this.decodeHeaderLines(headerLines);
  2282. header.headerText = headerText;
  2283. header.headerSizeBytes = headerText.indexOf(PlyParserUtils.HeaderEndToken) + PlyParserUtils.HeaderEndToken.length + 1;
  2284. return header;
  2285. }
  2286. decodeHeaderFromBuffer(plyBuffer) {
  2287. const headerText = this.plyParserutils.readHeaderFromBuffer(plyBuffer);
  2288. return this.decodeHeaderText(headerText);
  2289. }
  2290. findSplatData(plyBuffer, header) {
  2291. return new DataView(plyBuffer, header.headerSizeBytes);
  2292. }
  2293. parseToUncompressedSplatBufferSection(header, fromSplat, toSplat, splatData, splatDataOffset,
  2294. toBuffer, toOffset, outSphericalHarmonicsDegree = 0) {
  2295. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  2296. const outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree].BytesPerSplat;
  2297. for (let i = fromSplat; i <= toSplat; i++) {
  2298. const parsedSplat = INRIAV1PlyParser.parseToUncompressedSplat(splatData, i, header,
  2299. splatDataOffset, outSphericalHarmonicsDegree);
  2300. const outBase = i * outBytesPerSplat + toOffset;
  2301. SplatBuffer.writeSplatDataToSectionBuffer(parsedSplat, toBuffer, outBase, 0, outSphericalHarmonicsDegree);
  2302. }
  2303. }
  2304. decodeSectionSplatData(sectionSplatData, splatCount, sectionHeader, outSphericalHarmonicsDegree) {
  2305. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, sectionHeader.sphericalHarmonicsDegree);
  2306. const splatArray = new UncompressedSplatArray(outSphericalHarmonicsDegree);
  2307. for (let row = 0; row < splatCount; row++) {
  2308. const newSplat = INRIAV1PlyParser.parseToUncompressedSplat(sectionSplatData, row, sectionHeader,
  2309. 0, outSphericalHarmonicsDegree);
  2310. splatArray.addSplat(newSplat);
  2311. }
  2312. return splatArray;
  2313. }
  2314. static parseToUncompressedSplat = function() {
  2315. let rawSplat = [];
  2316. const tempRotation = new THREE.Quaternion();
  2317. const OFFSET_X = UncompressedSplatArray.OFFSET.X;
  2318. const OFFSET_Y = UncompressedSplatArray.OFFSET.Y;
  2319. const OFFSET_Z = UncompressedSplatArray.OFFSET.Z;
  2320. const OFFSET_SCALE0 = UncompressedSplatArray.OFFSET.SCALE0;
  2321. const OFFSET_SCALE1 = UncompressedSplatArray.OFFSET.SCALE1;
  2322. const OFFSET_SCALE2 = UncompressedSplatArray.OFFSET.SCALE2;
  2323. const OFFSET_ROTATION0 = UncompressedSplatArray.OFFSET.ROTATION0;
  2324. const OFFSET_ROTATION1 = UncompressedSplatArray.OFFSET.ROTATION1;
  2325. const OFFSET_ROTATION2 = UncompressedSplatArray.OFFSET.ROTATION2;
  2326. const OFFSET_ROTATION3 = UncompressedSplatArray.OFFSET.ROTATION3;
  2327. const OFFSET_FDC0 = UncompressedSplatArray.OFFSET.FDC0;
  2328. const OFFSET_FDC1 = UncompressedSplatArray.OFFSET.FDC1;
  2329. const OFFSET_FDC2 = UncompressedSplatArray.OFFSET.FDC2;
  2330. const OFFSET_OPACITY = UncompressedSplatArray.OFFSET.OPACITY;
  2331. const OFFSET_FRC = [];
  2332. for (let i = 0; i < 45; i++) {
  2333. OFFSET_FRC[i] = UncompressedSplatArray.OFFSET.FRC0 + i;
  2334. }
  2335. return function(splatData, row, header, splatDataOffset = 0, outSphericalHarmonicsDegree = 0) {
  2336. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  2337. INRIAV1PlyParser.readSplat(splatData, header, row, splatDataOffset, rawSplat);
  2338. const newSplat = UncompressedSplatArray.createSplat(outSphericalHarmonicsDegree);
  2339. if (rawSplat[SCALE_0] !== undefined) {
  2340. newSplat[OFFSET_SCALE0] = Math.exp(rawSplat[SCALE_0]);
  2341. newSplat[OFFSET_SCALE1] = Math.exp(rawSplat[SCALE_1]);
  2342. newSplat[OFFSET_SCALE2] = Math.exp(rawSplat[SCALE_2]);
  2343. } else {
  2344. newSplat[OFFSET_SCALE0] = 0.01;
  2345. newSplat[OFFSET_SCALE1] = 0.01;
  2346. newSplat[OFFSET_SCALE2] = 0.01;
  2347. }
  2348. if (rawSplat[F_DC_0] !== undefined) {
  2349. const SH_C0 = 0.28209479177387814;
  2350. newSplat[OFFSET_FDC0] = (0.5 + SH_C0 * rawSplat[F_DC_0]) * 255;
  2351. newSplat[OFFSET_FDC1] = (0.5 + SH_C0 * rawSplat[F_DC_1]) * 255;
  2352. newSplat[OFFSET_FDC2] = (0.5 + SH_C0 * rawSplat[F_DC_2]) * 255;
  2353. } else if (rawSplat[RED] !== undefined) {
  2354. newSplat[OFFSET_FDC0] = rawSplat[RED] * 255;
  2355. newSplat[OFFSET_FDC1] = rawSplat[GREEN] * 255;
  2356. newSplat[OFFSET_FDC2] = rawSplat[BLUE] * 255;
  2357. } else {
  2358. newSplat[OFFSET_FDC0] = 0;
  2359. newSplat[OFFSET_FDC1] = 0;
  2360. newSplat[OFFSET_FDC2] = 0;
  2361. }
  2362. if (rawSplat[OPACITY] !== undefined) {
  2363. newSplat[OFFSET_OPACITY] = (1 / (1 + Math.exp(-rawSplat[OPACITY]))) * 255;
  2364. }
  2365. if (rawSplat[FILTER_3D] !== undefined) {
  2366. const filter3d = rawSplat[FILTER_3D];
  2367. const filter3dSquare = filter3d*filter3d;
  2368. // x2,y2,z2, 2代表平方
  2369. const scaleXSquare = newSplat[OFFSET_SCALE0]*newSplat[OFFSET_SCALE0];
  2370. const scaleYSquare = newSplat[OFFSET_SCALE1]*newSplat[OFFSET_SCALE1];
  2371. const scaleZSquare = newSplat[OFFSET_SCALE2]*newSplat[OFFSET_SCALE2];
  2372. const det1 = scaleXSquare*scaleYSquare*scaleZSquare; // 计算所有列元素乘积之和 x2*y2*z2
  2373. // x2+d2, y2+d2, z2+d2
  2374. const scaleXAfterSquare = scaleXSquare + filter3dSquare;
  2375. const scaleYAfterSquare = scaleYSquare + filter3dSquare;
  2376. const scaleZAfterSquare = scaleZSquare + filter3dSquare;
  2377. // (x2+d2)*(y2+d2)*(z2+d2)
  2378. const det2 = scaleXAfterSquare*scaleYAfterSquare*scaleZAfterSquare;
  2379. const coef = Math.sqrt(det1 / det2); // sqrt( (x2*y2*z2)/{(x2+d2)*(y2+d2)*(z2+d2)} )
  2380. // sqrt(x2+d2),sqrt(y2+d2), sqrt(z2+d2)
  2381. newSplat[OFFSET_SCALE0] = Math.sqrt(scaleXAfterSquare);
  2382. newSplat[OFFSET_SCALE1] = Math.sqrt(scaleYAfterSquare);
  2383. newSplat[OFFSET_SCALE2] = Math.sqrt(scaleZAfterSquare);
  2384. newSplat[OFFSET_OPACITY] = newSplat[OFFSET_OPACITY] * coef;
  2385. }
  2386. newSplat[OFFSET_FDC0] = clamp(Math.floor(newSplat[OFFSET_FDC0]), 0, 255);
  2387. newSplat[OFFSET_FDC1] = clamp(Math.floor(newSplat[OFFSET_FDC1]), 0, 255);
  2388. newSplat[OFFSET_FDC2] = clamp(Math.floor(newSplat[OFFSET_FDC2]), 0, 255);
  2389. newSplat[OFFSET_OPACITY] = clamp(Math.floor(newSplat[OFFSET_OPACITY]), 0, 255);
  2390. if (outSphericalHarmonicsDegree >= 1) {
  2391. if (rawSplat[F_REST_0] !== undefined) {
  2392. for (let i = 0; i < 9; i++) {
  2393. newSplat[OFFSET_FRC[i]] = rawSplat[header.sphericalHarmonicsDegree1Fields[i]];
  2394. }
  2395. if (outSphericalHarmonicsDegree >= 2) {
  2396. for (let i = 0; i < 15; i++) {
  2397. newSplat[OFFSET_FRC[9 + i]] = rawSplat[header.sphericalHarmonicsDegree2Fields[i]];
  2398. }
  2399. }
  2400. }
  2401. }
  2402. tempRotation.set(rawSplat[ROT_0], rawSplat[ROT_1], rawSplat[ROT_2], rawSplat[ROT_3]);
  2403. tempRotation.normalize();
  2404. newSplat[OFFSET_ROTATION0] = tempRotation.x;
  2405. newSplat[OFFSET_ROTATION1] = tempRotation.y;
  2406. newSplat[OFFSET_ROTATION2] = tempRotation.z;
  2407. newSplat[OFFSET_ROTATION3] = tempRotation.w;
  2408. newSplat[OFFSET_X] = rawSplat[X];
  2409. newSplat[OFFSET_Y] = rawSplat[Y];
  2410. newSplat[OFFSET_Z] = rawSplat[Z];
  2411. return newSplat;
  2412. };
  2413. }();
  2414. static readSplat(splatData, header, row, dataOffset, rawSplat) {
  2415. return PlyParserUtils.readVertex(splatData, header, row, dataOffset, header.fieldsToReadIndexes, rawSplat, true);
  2416. }
  2417. parseToUncompressedSplatArray(plyBuffer, outSphericalHarmonicsDegree = 0) {
  2418. const header = this.decodeHeaderFromBuffer(plyBuffer);
  2419. const splatCount = header.splatCount;
  2420. const splatData = this.findSplatData(plyBuffer, header);
  2421. const splatArray = this.decodeSectionSplatData(splatData, splatCount, header, outSphericalHarmonicsDegree);
  2422. return splatArray;
  2423. }
  2424. }
  2425. const CodeBookEntryNamesToRead = [
  2426. 'features_dc', 'features_rest_0', 'features_rest_1', 'features_rest_2', 'features_rest_3', 'features_rest_4', 'features_rest_5',
  2427. 'features_rest_6', 'features_rest_7', 'features_rest_8', 'features_rest_9', 'features_rest_10', 'features_rest_11', 'features_rest_12',
  2428. 'features_rest_13', 'features_rest_14', 'opacity', 'scaling', 'rotation_re', 'rotation_im'
  2429. ];
  2430. const CodeBookEntriesToReadIndexes = CodeBookEntryNamesToRead.map((e, i) => i);
  2431. const [
  2432. CB_FEATURES_DC, CB_FEATURES_REST_0, CB_FEATURES_REST_3, CB_OPACITY, CB_SCALING, CB_ROTATION_RE, CB_ROTATION_IM
  2433. ] = [0, 1, 4, 16, 17, 18, 19];
  2434. const FieldNamesToRead = ['scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3',
  2435. 'x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'red', 'green', 'blue',
  2436. 'f_rest_0', 'f_rest_1', 'f_rest_2', 'f_rest_3', 'f_rest_4', 'f_rest_5', 'f_rest_6', 'f_rest_7', 'f_rest_8',
  2437. 'f_rest_9', 'f_rest_10', 'f_rest_11', 'f_rest_12', 'f_rest_13', 'f_rest_14', 'f_rest_15', 'f_rest_16',
  2438. 'f_rest_17', 'f_rest_18', 'f_rest_19', 'f_rest_20', 'f_rest_21', 'f_rest_22', 'f_rest_23', 'f_rest_24',
  2439. 'f_rest_25', 'f_rest_26', 'f_rest_27', 'f_rest_28', 'f_rest_29', 'f_rest_30', 'f_rest_31', 'f_rest_32',
  2440. 'f_rest_33', 'f_rest_34', 'f_rest_35', 'f_rest_36', 'f_rest_37', 'f_rest_38', 'f_rest_39', 'f_rest_40',
  2441. 'f_rest_41', 'f_rest_42', 'f_rest_43', 'f_rest_44', 'f_rest_45'
  2442. ];
  2443. const FieldsToReadIndexes = FieldNamesToRead.map((e, i) => i);
  2444. const [
  2445. PLY_SCALE_0, PLY_SCALE_1, PLY_SCALE_2, PLY_ROT_0, PLY_ROT_1, PLY_ROT_2, PLY_ROT_3, PLY_X, PLY_Y, PLY_Z,
  2446. PLY_F_DC_0, PLY_F_DC_1, PLY_F_DC_2, PLY_OPACITY,
  2447. ] = FieldsToReadIndexes;
  2448. const PLY_RED = PLY_F_DC_0;
  2449. const PLY_GREEN = PLY_F_DC_1;
  2450. const PLY_BLUE = PLY_F_DC_2;
  2451. const fromHalfFloat = (hf) =>{
  2452. const t = (31744 & hf) >> 10;
  2453. const a = 1023 & hf;
  2454. return (hf >> 15 ? -1 : 1)*(t ? t === 31 ? a ? NaN : 1/0 : Math.pow(2, t - 15) *( 1 + a / 1024) : a / 1024*6103515625e-14);
  2455. };
  2456. class INRIAV2PlyParser {
  2457. constructor() {
  2458. this.plyParserutils = new PlyParserUtils();
  2459. }
  2460. decodeSectionHeadersFromHeaderLines(headerLines) {
  2461. const fieldNameIdMap = FieldsToReadIndexes.reduce((acc, element) => {
  2462. acc[FieldNamesToRead[element]] = element;
  2463. return acc;
  2464. }, {});
  2465. const codeBookEntriesToReadIdMap = CodeBookEntriesToReadIndexes.reduce((acc, element) => {
  2466. acc[CodeBookEntryNamesToRead[element]] = element;
  2467. return acc;
  2468. }, {});
  2469. const sectionNames = PlyParserUtils.getHeaderSectionNames(headerLines);
  2470. let codeBookSectionIndex;
  2471. for (let s = 0; s < sectionNames.length; s++) {
  2472. const sectionName = sectionNames[s];
  2473. if (sectionName === 'codebook_centers') {
  2474. codeBookSectionIndex = s;
  2475. }
  2476. }
  2477. let currentStartLine = 0;
  2478. let lastSectionFound = false;
  2479. const sectionHeaders = [];
  2480. let sectionIndex = 0;
  2481. while (!lastSectionFound) {
  2482. let sectionHeader;
  2483. if (sectionIndex === codeBookSectionIndex) {
  2484. sectionHeader = this.plyParserutils.decodeSectionHeader(headerLines, codeBookEntriesToReadIdMap, currentStartLine);
  2485. } else {
  2486. sectionHeader = this.plyParserutils.decodeSectionHeader(headerLines, fieldNameIdMap, currentStartLine);
  2487. }
  2488. lastSectionFound = sectionHeader.endOfHeader;
  2489. currentStartLine = sectionHeader.headerEndLine + 1;
  2490. if (!lastSectionFound) {
  2491. sectionHeader.splatCount = sectionHeader.vertexCount;
  2492. sectionHeader.bytesPerSplat = sectionHeader.bytesPerVertex;
  2493. }
  2494. sectionHeaders.push(sectionHeader);
  2495. sectionIndex++;
  2496. }
  2497. return sectionHeaders;
  2498. }
  2499. decodeSectionHeadersFromHeaderText(headerText) {
  2500. const headerLines = PlyParserUtils.convertHeaderTextToLines(headerText);
  2501. return this.decodeSectionHeadersFromHeaderLines(headerLines);
  2502. }
  2503. getSplatCountFromSectionHeaders(sectionHeaders) {
  2504. let splatCount = 0;
  2505. for (let sectionHeader of sectionHeaders) {
  2506. if (sectionHeader.sectionName !== 'codebook_centers') {
  2507. splatCount += sectionHeader.vertexCount;
  2508. }
  2509. }
  2510. return splatCount;
  2511. }
  2512. decodeHeaderFromHeaderText(headerText) {
  2513. const headerSizeBytes = headerText.indexOf(PlyParserUtils.HeaderEndToken) + PlyParserUtils.HeaderEndToken.length + 1;
  2514. const sectionHeaders = this.decodeSectionHeadersFromHeaderText(headerText);
  2515. const splatCount = this.getSplatCountFromSectionHeaders(sectionHeaders);
  2516. return {
  2517. 'headerSizeBytes': headerSizeBytes,
  2518. 'sectionHeaders': sectionHeaders,
  2519. 'splatCount': splatCount
  2520. };
  2521. }
  2522. decodeHeaderFromBuffer(plyBuffer) {
  2523. const headerText = this.plyParserutils.readHeaderFromBuffer(plyBuffer);
  2524. return this.decodeHeaderFromHeaderText(headerText);
  2525. }
  2526. findVertexData(plyBuffer, header, targetSection) {
  2527. let byteOffset = header.headerSizeBytes;
  2528. for (let s = 0; s < targetSection && s < header.sectionHeaders.length; s++) {
  2529. const sectionHeader = header.sectionHeaders[s];
  2530. byteOffset += sectionHeader.dataSizeBytes;
  2531. }
  2532. return new DataView(plyBuffer, byteOffset, header.sectionHeaders[targetSection].dataSizeBytes);
  2533. }
  2534. decodeCodeBook(codeBookData, sectionHeader) {
  2535. const rawVertex = [];
  2536. const codeBook = [];
  2537. for (let row = 0; row < sectionHeader.vertexCount; row++) {
  2538. PlyParserUtils.readVertex(codeBookData, sectionHeader, row, 0, CodeBookEntriesToReadIndexes, rawVertex);
  2539. for (let index of CodeBookEntriesToReadIndexes) {
  2540. const codeBookElementOffset = CodeBookEntriesToReadIndexes[index];
  2541. let codeBookPage = codeBook[codeBookElementOffset];
  2542. if (!codeBookPage) {
  2543. codeBook[codeBookElementOffset] = codeBookPage = [];
  2544. }
  2545. codeBookPage.push(rawVertex[index]);
  2546. }
  2547. }
  2548. for (let page = 0; page < codeBook.length; page++) {
  2549. const codeBookPage = codeBook[page];
  2550. const SH_C0 = 0.28209479177387814;
  2551. for (let i = 0; i < codeBookPage.length; i++) {
  2552. const baseValue = fromHalfFloat(codeBookPage[i]);
  2553. if (page === CB_OPACITY) {
  2554. codeBookPage[i] = Math.round((1 / (1 + Math.exp(-baseValue))) * 255);
  2555. } else if (page === CB_FEATURES_DC) {
  2556. codeBookPage[i] = Math.round((0.5 + SH_C0 * baseValue) * 255);
  2557. } else if (page === CB_SCALING) {
  2558. codeBookPage[i] = Math.exp(baseValue);
  2559. } else {
  2560. codeBookPage[i] = baseValue;
  2561. }
  2562. }
  2563. }
  2564. return codeBook;
  2565. }
  2566. decodeSectionSplatData(sectionSplatData, splatCount, sectionHeader, codeBook, outSphericalHarmonicsDegree) {
  2567. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, sectionHeader.sphericalHarmonicsDegree);
  2568. const splatArray = new UncompressedSplatArray(outSphericalHarmonicsDegree);
  2569. for (let row = 0; row < splatCount; row++) {
  2570. const newSplat = INRIAV2PlyParser.parseToUncompressedSplat(sectionSplatData, row, sectionHeader, codeBook,
  2571. 0, outSphericalHarmonicsDegree);
  2572. splatArray.addSplat(newSplat);
  2573. }
  2574. return splatArray;
  2575. }
  2576. static parseToUncompressedSplat = function() {
  2577. let rawSplat = [];
  2578. const tempRotation = new THREE.Quaternion();
  2579. const OFFSET_X = UncompressedSplatArray.OFFSET.X;
  2580. const OFFSET_Y = UncompressedSplatArray.OFFSET.Y;
  2581. const OFFSET_Z = UncompressedSplatArray.OFFSET.Z;
  2582. const OFFSET_SCALE0 = UncompressedSplatArray.OFFSET.SCALE0;
  2583. const OFFSET_SCALE1 = UncompressedSplatArray.OFFSET.SCALE1;
  2584. const OFFSET_SCALE2 = UncompressedSplatArray.OFFSET.SCALE2;
  2585. const OFFSET_ROTATION0 = UncompressedSplatArray.OFFSET.ROTATION0;
  2586. const OFFSET_ROTATION1 = UncompressedSplatArray.OFFSET.ROTATION1;
  2587. const OFFSET_ROTATION2 = UncompressedSplatArray.OFFSET.ROTATION2;
  2588. const OFFSET_ROTATION3 = UncompressedSplatArray.OFFSET.ROTATION3;
  2589. const OFFSET_FDC0 = UncompressedSplatArray.OFFSET.FDC0;
  2590. const OFFSET_FDC1 = UncompressedSplatArray.OFFSET.FDC1;
  2591. const OFFSET_FDC2 = UncompressedSplatArray.OFFSET.FDC2;
  2592. const OFFSET_OPACITY = UncompressedSplatArray.OFFSET.OPACITY;
  2593. const OFFSET_FRC = [];
  2594. for (let i = 0; i < 45; i++) {
  2595. OFFSET_FRC[i] = UncompressedSplatArray.OFFSET.FRC0 + i;
  2596. }
  2597. return function(splatData, row, header, codeBook, splatDataOffset = 0, outSphericalHarmonicsDegree = 0) {
  2598. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  2599. INRIAV2PlyParser.readSplat(splatData, header, row, splatDataOffset, rawSplat);
  2600. const newSplat = UncompressedSplatArray.createSplat(outSphericalHarmonicsDegree);
  2601. if (rawSplat[PLY_SCALE_0] !== undefined) {
  2602. newSplat[OFFSET_SCALE0] = codeBook[CB_SCALING][rawSplat[PLY_SCALE_0]];
  2603. newSplat[OFFSET_SCALE1] = codeBook[CB_SCALING][rawSplat[PLY_SCALE_1]];
  2604. newSplat[OFFSET_SCALE2] = codeBook[CB_SCALING][rawSplat[PLY_SCALE_2]];
  2605. } else {
  2606. newSplat[OFFSET_SCALE0] = 0.01;
  2607. newSplat[OFFSET_SCALE1] = 0.01;
  2608. newSplat[OFFSET_SCALE2] = 0.01;
  2609. }
  2610. if (rawSplat[PLY_F_DC_0] !== undefined) {
  2611. newSplat[OFFSET_FDC0] = codeBook[CB_FEATURES_DC][rawSplat[PLY_F_DC_0]];
  2612. newSplat[OFFSET_FDC1] = codeBook[CB_FEATURES_DC][rawSplat[PLY_F_DC_1]];
  2613. newSplat[OFFSET_FDC2] = codeBook[CB_FEATURES_DC][rawSplat[PLY_F_DC_2]];
  2614. } else if (rawSplat[PLY_RED] !== undefined) {
  2615. newSplat[OFFSET_FDC0] = rawSplat[PLY_RED] * 255;
  2616. newSplat[OFFSET_FDC1] = rawSplat[PLY_GREEN] * 255;
  2617. newSplat[OFFSET_FDC2] = rawSplat[PLY_BLUE] * 255;
  2618. } else {
  2619. newSplat[OFFSET_FDC0] = 0;
  2620. newSplat[OFFSET_FDC1] = 0;
  2621. newSplat[OFFSET_FDC2] = 0;
  2622. }
  2623. if (rawSplat[PLY_OPACITY] !== undefined) {
  2624. newSplat[OFFSET_OPACITY] = codeBook[CB_OPACITY][rawSplat[PLY_OPACITY]];
  2625. }
  2626. newSplat[OFFSET_FDC0] = clamp(Math.floor(newSplat[OFFSET_FDC0]), 0, 255);
  2627. newSplat[OFFSET_FDC1] = clamp(Math.floor(newSplat[OFFSET_FDC1]), 0, 255);
  2628. newSplat[OFFSET_FDC2] = clamp(Math.floor(newSplat[OFFSET_FDC2]), 0, 255);
  2629. newSplat[OFFSET_OPACITY] = clamp(Math.floor(newSplat[OFFSET_OPACITY]), 0, 255);
  2630. if (outSphericalHarmonicsDegree >= 1 && header.sphericalHarmonicsDegree >= 1) {
  2631. for (let i = 0; i < 9; i++) {
  2632. const codeBookPage = codeBook[CB_FEATURES_REST_0 + i % 3];
  2633. newSplat[OFFSET_FRC[i]] = codeBookPage[rawSplat[header.sphericalHarmonicsDegree1Fields[i]]];
  2634. }
  2635. if (outSphericalHarmonicsDegree >= 2 && header.sphericalHarmonicsDegree >= 2) {
  2636. for (let i = 0; i < 15; i++) {
  2637. const codeBookPage = codeBook[CB_FEATURES_REST_3 + i % 5];
  2638. newSplat[OFFSET_FRC[9 + i]] = codeBookPage[rawSplat[header.sphericalHarmonicsDegree2Fields[i]]];
  2639. }
  2640. }
  2641. }
  2642. const rot0 = codeBook[CB_ROTATION_RE][rawSplat[PLY_ROT_0]];
  2643. const rot1 = codeBook[CB_ROTATION_IM][rawSplat[PLY_ROT_1]];
  2644. const rot2 = codeBook[CB_ROTATION_IM][rawSplat[PLY_ROT_2]];
  2645. const rot3 = codeBook[CB_ROTATION_IM][rawSplat[PLY_ROT_3]];
  2646. tempRotation.set(rot0, rot1, rot2, rot3);
  2647. tempRotation.normalize();
  2648. newSplat[OFFSET_ROTATION0] = tempRotation.x;
  2649. newSplat[OFFSET_ROTATION1] = tempRotation.y;
  2650. newSplat[OFFSET_ROTATION2] = tempRotation.z;
  2651. newSplat[OFFSET_ROTATION3] = tempRotation.w;
  2652. newSplat[OFFSET_X] = fromHalfFloat(rawSplat[PLY_X]);
  2653. newSplat[OFFSET_Y] = fromHalfFloat(rawSplat[PLY_Y]);
  2654. newSplat[OFFSET_Z] = fromHalfFloat(rawSplat[PLY_Z]);
  2655. return newSplat;
  2656. };
  2657. }();
  2658. static readSplat(splatData, header, row, dataOffset, rawSplat) {
  2659. return PlyParserUtils.readVertex(splatData, header, row, dataOffset, FieldsToReadIndexes, rawSplat, false);
  2660. }
  2661. parseToUncompressedSplatArray(plyBuffer, outSphericalHarmonicsDegree = 0) {
  2662. const splatArrays = [];
  2663. const header = this.decodeHeaderFromBuffer(plyBuffer, outSphericalHarmonicsDegree);
  2664. let codeBook;
  2665. for (let s = 0; s < header.sectionHeaders.length; s++) {
  2666. const sectionHeader = header.sectionHeaders[s];
  2667. if (sectionHeader.sectionName === 'codebook_centers') {
  2668. const codeBookData = this.findVertexData(plyBuffer, header, s);
  2669. codeBook = this.decodeCodeBook(codeBookData, sectionHeader);
  2670. }
  2671. }
  2672. for (let s = 0; s < header.sectionHeaders.length; s++) {
  2673. const sectionHeader = header.sectionHeaders[s];
  2674. if (sectionHeader.sectionName !== 'codebook_centers') {
  2675. const splatCount = sectionHeader.vertexCount;
  2676. const vertexData = this.findVertexData(plyBuffer, header, s);
  2677. const splatArray = this.decodeSectionSplatData(vertexData, splatCount, sectionHeader,
  2678. codeBook, outSphericalHarmonicsDegree);
  2679. splatArrays.push(splatArray);
  2680. }
  2681. }
  2682. const unified = new UncompressedSplatArray(outSphericalHarmonicsDegree);
  2683. for (let splatArray of splatArrays) {
  2684. for (let splat of splatArray.splats) {
  2685. unified.addSplat(splat);
  2686. }
  2687. }
  2688. return unified;
  2689. }
  2690. }
  2691. class PlyParser {
  2692. static parseToUncompressedSplatArray(plyBuffer, outSphericalHarmonicsDegree = 0) {
  2693. const plyFormat = PlyParserUtils.determineHeaderFormatFromPlyBuffer(plyBuffer);
  2694. if (plyFormat === PlyFormat.PlayCanvasCompressed) {
  2695. return PlayCanvasCompressedPlyParser.parseToUncompressedSplatArray(plyBuffer);
  2696. } else if (plyFormat === PlyFormat.INRIAV1) {
  2697. return new INRIAV1PlyParser().parseToUncompressedSplatArray(plyBuffer, outSphericalHarmonicsDegree);
  2698. } else if (plyFormat === PlyFormat.INRIAV2) {
  2699. return new INRIAV2PlyParser().parseToUncompressedSplatArray(plyBuffer, outSphericalHarmonicsDegree);
  2700. }
  2701. }
  2702. }
  2703. class SplatPartitioner {
  2704. constructor(sectionCount, sectionFilters, groupingParameters, partitionGenerator) {
  2705. this.sectionCount = sectionCount;
  2706. this.sectionFilters = sectionFilters;
  2707. this.groupingParameters = groupingParameters;
  2708. this.partitionGenerator = partitionGenerator;
  2709. }
  2710. partitionUncompressedSplatArray(splatArray) {
  2711. let groupingParameters;
  2712. let sectionCount;
  2713. let sectionFilters;
  2714. if (this.partitionGenerator) {
  2715. const results = this.partitionGenerator(splatArray);
  2716. groupingParameters = results.groupingParameters;
  2717. sectionCount = results.sectionCount;
  2718. sectionFilters = results.sectionFilters;
  2719. } else {
  2720. groupingParameters = this.groupingParameters;
  2721. sectionCount = this.sectionCount;
  2722. sectionFilters = this.sectionFilters;
  2723. }
  2724. const newArrays = [];
  2725. for (let s = 0; s < sectionCount; s++) {
  2726. const sectionSplats = new UncompressedSplatArray(splatArray.sphericalHarmonicsDegree);
  2727. const sectionFilter = sectionFilters[s];
  2728. for (let i = 0; i < splatArray.splatCount; i++) {
  2729. if (sectionFilter(i)) {
  2730. sectionSplats.addSplatFromArray(splatArray, i);
  2731. }
  2732. }
  2733. newArrays.push(sectionSplats);
  2734. }
  2735. return {
  2736. splatArrays: newArrays,
  2737. parameters: groupingParameters
  2738. };
  2739. }
  2740. static getStandardPartitioner(partitionSize = 0, sceneCenter = new THREE.Vector3(),
  2741. blockSize = SplatBuffer.BucketBlockSize, bucketSize = SplatBuffer.BucketSize) {
  2742. const partitionGenerator = (splatArray) => {
  2743. const OFFSET_X = UncompressedSplatArray.OFFSET.X;
  2744. const OFFSET_Y = UncompressedSplatArray.OFFSET.Y;
  2745. const OFFSET_Z = UncompressedSplatArray.OFFSET.Z;
  2746. if (partitionSize <= 0) partitionSize = splatArray.splatCount;
  2747. const center = new THREE.Vector3();
  2748. const clampDistance = 0.5;
  2749. const clampPoint = (point) => {
  2750. point.x = Math.floor(point.x / clampDistance) * clampDistance;
  2751. point.y = Math.floor(point.y / clampDistance) * clampDistance;
  2752. point.z = Math.floor(point.z / clampDistance) * clampDistance;
  2753. };
  2754. splatArray.splats.forEach((splat) => {
  2755. center.set(splat[OFFSET_X], splat[OFFSET_Y], splat[OFFSET_Z]).sub(sceneCenter);
  2756. clampPoint(center);
  2757. splat.centerDist = center.lengthSq();
  2758. });
  2759. splatArray.splats.sort((a, b) => {
  2760. let centerADist = a.centerDist;
  2761. let centerBDist = b.centerDist;
  2762. if (centerADist > centerBDist) return 1;
  2763. else return -1;
  2764. });
  2765. const sectionFilters = [];
  2766. const groupingParameters = [];
  2767. partitionSize = Math.min(splatArray.splatCount, partitionSize);
  2768. const patitionCount = Math.ceil(splatArray.splatCount / partitionSize);
  2769. let currentStartSplat = 0;
  2770. for (let i = 0; i < patitionCount; i ++) {
  2771. let startSplat = currentStartSplat;
  2772. sectionFilters.push((splatIndex) => {
  2773. return splatIndex >= startSplat && splatIndex < startSplat + partitionSize;
  2774. });
  2775. groupingParameters.push({
  2776. 'blocksSize': blockSize,
  2777. 'bucketSize': bucketSize,
  2778. });
  2779. currentStartSplat += partitionSize;
  2780. }
  2781. return {
  2782. 'sectionCount': sectionFilters.length,
  2783. sectionFilters,
  2784. groupingParameters
  2785. };
  2786. };
  2787. return new SplatPartitioner(undefined, undefined, undefined, partitionGenerator);
  2788. }
  2789. }
  2790. class SplatBufferGenerator {
  2791. constructor(splatPartitioner, alphaRemovalThreshold, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize) {
  2792. this.splatPartitioner = splatPartitioner;
  2793. this.alphaRemovalThreshold = alphaRemovalThreshold;
  2794. this.compressionLevel = compressionLevel;
  2795. this.sectionSize = sectionSize;
  2796. this.sceneCenter = sceneCenter ? new THREE.Vector3().copy(sceneCenter) : undefined;
  2797. this.blockSize = blockSize;
  2798. this.bucketSize = bucketSize;
  2799. }
  2800. generateFromUncompressedSplatArray(splatArray) {
  2801. const partitionResults = this.splatPartitioner.partitionUncompressedSplatArray(splatArray);
  2802. return SplatBuffer.generateFromUncompressedSplatArrays(partitionResults.splatArrays,
  2803. this.alphaRemovalThreshold, this.compressionLevel,
  2804. this.sceneCenter, this.blockSize, this.bucketSize,
  2805. partitionResults.parameters);
  2806. }
  2807. static getStandardGenerator(alphaRemovalThreshold = 1, compressionLevel = 1, sectionSize = 0, sceneCenter = new THREE.Vector3(),
  2808. blockSize = SplatBuffer.BucketBlockSize, bucketSize = SplatBuffer.BucketSize) {
  2809. const splatPartitioner = SplatPartitioner.getStandardPartitioner(sectionSize, sceneCenter, blockSize, bucketSize);
  2810. return new SplatBufferGenerator(splatPartitioner, alphaRemovalThreshold, compressionLevel,
  2811. sectionSize, sceneCenter, blockSize, bucketSize);
  2812. }
  2813. }
  2814. const LoaderStatus = {
  2815. 'Downloading': 0,
  2816. 'Processing': 1,
  2817. 'Done': 2
  2818. };
  2819. function storeChunksInBuffer(chunks, buffer) {
  2820. let inBytes = 0;
  2821. for (let chunk of chunks) inBytes += chunk.sizeBytes;
  2822. if (!buffer || buffer.byteLength < inBytes) {
  2823. buffer = new ArrayBuffer(inBytes);
  2824. }
  2825. let offset = 0;
  2826. for (let chunk of chunks) {
  2827. new Uint8Array(buffer, offset, chunk.sizeBytes).set(chunk.data);
  2828. offset += chunk.sizeBytes;
  2829. }
  2830. return buffer;
  2831. }
  2832. class PlyLoader {
  2833. static loadFromURL(fileName, onProgress, progressiveLoad, onStreamedSectionProgress, minimumAlpha, compressionLevel,
  2834. outSphericalHarmonicsDegree = 0, sectionSize, sceneCenter, blockSize, bucketSize) {
  2835. const progressiveLoadSectionSizeBytes = Constants.ProgressiveLoadSectionSize;
  2836. const splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes;
  2837. const sectionCount = 1;
  2838. let progressiveLoadBufferIn;
  2839. let progressiveLoadBufferOut;
  2840. let progressiveLoadSplatBuffer;
  2841. let compressedPlyHeaderChunksBuffer;
  2842. let maxSplatCount = 0;
  2843. let splatCount = 0;
  2844. let headerLoaded = false;
  2845. let readyToLoadSplatData = false;
  2846. let compressed = false;
  2847. const progressiveLoadPromise = nativePromiseWithExtractedComponents();
  2848. let numBytesStreamed = 0;
  2849. let numBytesParsed = 0;
  2850. let numBytesDownloaded = 0;
  2851. let headerText = '';
  2852. let header = null;
  2853. let chunks = [];
  2854. const textDecoder = new TextDecoder();
  2855. const inriaV1PlyParser = new INRIAV1PlyParser();
  2856. const localOnProgress = (percent, percentLabel, chunkData) => {
  2857. const loadComplete = percent >= 100;
  2858. if (progressiveLoad) {
  2859. if (chunkData) {
  2860. chunks.push({
  2861. 'data': chunkData,
  2862. 'sizeBytes': chunkData.byteLength,
  2863. 'startBytes': numBytesDownloaded,
  2864. 'endBytes': numBytesDownloaded + chunkData.byteLength
  2865. });
  2866. numBytesDownloaded += chunkData.byteLength;
  2867. }
  2868. if (!headerLoaded) {
  2869. headerText += textDecoder.decode(chunkData);
  2870. if (PlyParserUtils.checkTextForEndHeader(headerText)) {
  2871. const plyFormat = PlyParserUtils.determineHeaderFormatFromHeaderText(headerText);
  2872. if (plyFormat === PlyFormat.INRIAV1) {
  2873. header = inriaV1PlyParser.decodeHeaderText(headerText);
  2874. maxSplatCount = header.splatCount;
  2875. readyToLoadSplatData = true;
  2876. compressed = false;
  2877. } else if (plyFormat === PlyFormat.PlayCanvasCompressed) {
  2878. header = PlayCanvasCompressedPlyParser.decodeHeaderText(headerText);
  2879. maxSplatCount = header.vertexElement.count;
  2880. compressed = true;
  2881. } else {
  2882. throw new Error('PlyLoader.loadFromURL() -> Selected Ply format cannot be progressively loaded.');
  2883. }
  2884. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  2885. const shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree];
  2886. const splatBufferSizeBytes = splatDataOffsetBytes + shDescriptor.BytesPerSplat * maxSplatCount;
  2887. progressiveLoadBufferOut = new ArrayBuffer(splatBufferSizeBytes);
  2888. SplatBuffer.writeHeaderToBuffer({
  2889. versionMajor: SplatBuffer.CurrentMajorVersion,
  2890. versionMinor: SplatBuffer.CurrentMinorVersion,
  2891. maxSectionCount: sectionCount,
  2892. sectionCount: sectionCount,
  2893. maxSplatCount: maxSplatCount,
  2894. splatCount: splatCount,
  2895. compressionLevel: 0,
  2896. sceneCenter: new THREE.Vector3()
  2897. }, progressiveLoadBufferOut);
  2898. numBytesStreamed = header.headerSizeBytes;
  2899. numBytesParsed = header.headerSizeBytes;
  2900. headerLoaded = true;
  2901. }
  2902. } else if (compressed && !readyToLoadSplatData) {
  2903. const sizeRequiredForHeaderAndChunks = header.headerSizeBytes + header.chunkElement.storageSizeBytes;
  2904. compressedPlyHeaderChunksBuffer = storeChunksInBuffer(chunks, compressedPlyHeaderChunksBuffer);
  2905. if (compressedPlyHeaderChunksBuffer.byteLength >= sizeRequiredForHeaderAndChunks) {
  2906. PlayCanvasCompressedPlyParser.readElementData(header.chunkElement, compressedPlyHeaderChunksBuffer,
  2907. header.headerSizeBytes);
  2908. numBytesStreamed = sizeRequiredForHeaderAndChunks;
  2909. numBytesParsed = sizeRequiredForHeaderAndChunks;
  2910. readyToLoadSplatData = true;
  2911. }
  2912. }
  2913. if (headerLoaded && readyToLoadSplatData) {
  2914. if (chunks.length > 0) {
  2915. progressiveLoadBufferIn = storeChunksInBuffer(chunks, progressiveLoadBufferIn);
  2916. const bytesLoadedSinceLastStreamedSection = numBytesDownloaded - numBytesStreamed;
  2917. if (bytesLoadedSinceLastStreamedSection > progressiveLoadSectionSizeBytes || loadComplete) {
  2918. const numBytesToProcess = numBytesDownloaded - numBytesParsed;
  2919. const addedSplatCount = Math.floor(numBytesToProcess / header.bytesPerSplat);
  2920. const numBytesToParse = addedSplatCount * header.bytesPerSplat;
  2921. const numBytesLeftOver = numBytesToProcess - numBytesToParse;
  2922. const newSplatCount = splatCount + addedSplatCount;
  2923. const parsedDataViewOffset = numBytesParsed - chunks[0].startBytes;
  2924. const dataToParse = new DataView(progressiveLoadBufferIn, parsedDataViewOffset, numBytesToParse);
  2925. const shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree];
  2926. const outOffset = splatCount * shDescriptor.BytesPerSplat + splatDataOffsetBytes;
  2927. if (compressed) {
  2928. PlayCanvasCompressedPlyParser.parseToUncompressedSplatBufferSection(header.chunkElement,
  2929. header.vertexElement, 0,
  2930. addedSplatCount - 1, splatCount,
  2931. dataToParse, 0,
  2932. progressiveLoadBufferOut, outOffset);
  2933. } else {
  2934. inriaV1PlyParser.parseToUncompressedSplatBufferSection(header, 0, addedSplatCount - 1, dataToParse,
  2935. 0, progressiveLoadBufferOut, outOffset,
  2936. outSphericalHarmonicsDegree);
  2937. }
  2938. splatCount = newSplatCount;
  2939. if (!progressiveLoadSplatBuffer) {
  2940. SplatBuffer.writeSectionHeaderToBuffer({
  2941. maxSplatCount: maxSplatCount,
  2942. splatCount: splatCount,
  2943. bucketSize: 0,
  2944. bucketCount: 0,
  2945. bucketBlockSize: 0,
  2946. compressionScaleRange: 0,
  2947. storageSizeBytes: 0,
  2948. fullBucketCount: 0,
  2949. partiallyFilledBucketCount: 0,
  2950. sphericalHarmonicsDegree: outSphericalHarmonicsDegree
  2951. }, 0, progressiveLoadBufferOut, SplatBuffer.HeaderSizeBytes);
  2952. progressiveLoadSplatBuffer = new SplatBuffer(progressiveLoadBufferOut, false);
  2953. }
  2954. progressiveLoadSplatBuffer.updateLoadedCounts(1, splatCount);
  2955. onStreamedSectionProgress(progressiveLoadSplatBuffer, loadComplete);
  2956. numBytesStreamed += progressiveLoadSectionSizeBytes;
  2957. numBytesParsed += numBytesToParse;
  2958. if (numBytesLeftOver === 0) {
  2959. chunks = [];
  2960. } else {
  2961. let keepChunks = [];
  2962. let keepSize = 0;
  2963. for (let i = chunks.length - 1; i >= 0; i--) {
  2964. const chunk = chunks[i];
  2965. keepSize += chunk.sizeBytes;
  2966. keepChunks.unshift(chunk);
  2967. if (keepSize >= numBytesLeftOver) break;
  2968. }
  2969. chunks = keepChunks;
  2970. }
  2971. }
  2972. }
  2973. if (loadComplete) {
  2974. progressiveLoadPromise.resolve(progressiveLoadSplatBuffer);
  2975. }
  2976. }
  2977. }
  2978. if (onProgress) onProgress(percent, percentLabel, LoaderStatus.Downloading);
  2979. };
  2980. return fetchWithProgress(fileName, localOnProgress, !progressiveLoad).then((plyFileData) => {
  2981. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  2982. const loadPromise = progressiveLoad ? progressiveLoadPromise.promise :
  2983. PlyLoader.loadFromFileData(plyFileData, minimumAlpha, compressionLevel, outSphericalHarmonicsDegree,
  2984. sectionSize, sceneCenter, blockSize, bucketSize);
  2985. return loadPromise.then((splatBuffer) => {
  2986. if (onProgress) onProgress(100, '100%', LoaderStatus.Done);
  2987. return splatBuffer;
  2988. });
  2989. });
  2990. }
  2991. static loadFromFileData(plyFileData, minimumAlpha, compressionLevel, outSphericalHarmonicsDegree = 0,
  2992. sectionSize, sceneCenter, blockSize, bucketSize) {
  2993. return delayedExecute(() => {
  2994. return PlyParser.parseToUncompressedSplatArray(plyFileData, outSphericalHarmonicsDegree);
  2995. })
  2996. .then((splatArray) => {
  2997. const splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel, sectionSize,
  2998. sceneCenter, blockSize, bucketSize);
  2999. return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray);
  3000. });
  3001. }
  3002. }
  3003. class SplatParser {
  3004. static RowSizeBytes = 32;
  3005. static CenterSizeBytes = 12;
  3006. static ScaleSizeBytes = 12;
  3007. static RotationSizeBytes = 4;
  3008. static ColorSizeBytes = 4;
  3009. static parseToUncompressedSplatBufferSection(fromSplat, toSplat, fromBuffer, fromOffset, toBuffer, toOffset) {
  3010. const outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter;
  3011. const outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale;
  3012. const outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation;
  3013. const outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  3014. for (let i = fromSplat; i <= toSplat; i++) {
  3015. const inBase = i * SplatParser.RowSizeBytes + fromOffset;
  3016. const inCenter = new Float32Array(fromBuffer, inBase, 3);
  3017. const inScale = new Float32Array(fromBuffer, inBase + SplatParser.CenterSizeBytes, 3);
  3018. const inColor = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4);
  3019. const inRotation = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes +
  3020. SplatParser.RotationSizeBytes, 4);
  3021. const quat = new THREE.Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128,
  3022. (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128);
  3023. quat.normalize();
  3024. const outBase = i * outBytesPerSplat + toOffset;
  3025. const outCenter = new Float32Array(toBuffer, outBase, 3);
  3026. const outScale = new Float32Array(toBuffer, outBase + outBytesPerCenter, 3);
  3027. const outRotation = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4);
  3028. const outColor = new Uint8Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4);
  3029. outCenter[0] = inCenter[0];
  3030. outCenter[1] = inCenter[1];
  3031. outCenter[2] = inCenter[2];
  3032. outScale[0] = inScale[0];
  3033. outScale[1] = inScale[1];
  3034. outScale[2] = inScale[2];
  3035. outRotation[0] = quat.w;
  3036. outRotation[1] = quat.x;
  3037. outRotation[2] = quat.y;
  3038. outRotation[3] = quat.z;
  3039. outColor[0] = inColor[0];
  3040. outColor[1] = inColor[1];
  3041. outColor[2] = inColor[2];
  3042. outColor[3] = inColor[3];
  3043. }
  3044. }
  3045. static parseStandardSplatToUncompressedSplatArray(inBuffer) {
  3046. // Standard .splat row layout:
  3047. // XYZ - Position (Float32)
  3048. // XYZ - Scale (Float32)
  3049. // RGBA - colors (uint8)
  3050. // IJKL - quaternion/rot (uint8)
  3051. const splatCount = inBuffer.byteLength / SplatParser.RowSizeBytes;
  3052. const splatArray = new UncompressedSplatArray();
  3053. for (let i = 0; i < splatCount; i++) {
  3054. const inBase = i * SplatParser.RowSizeBytes;
  3055. const inCenter = new Float32Array(inBuffer, inBase, 3);
  3056. const inScale = new Float32Array(inBuffer, inBase + SplatParser.CenterSizeBytes, 3);
  3057. const inColor = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4);
  3058. const inRotation = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes +
  3059. SplatParser.ScaleSizeBytes + SplatParser.ColorSizeBytes, 4);
  3060. const quat = new THREE.Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128,
  3061. (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128);
  3062. quat.normalize();
  3063. splatArray.addSplatFromComonents(inCenter[0], inCenter[1], inCenter[2], inScale[0], inScale[1], inScale[2],
  3064. quat.w, quat.x, quat.y, quat.z, inColor[0], inColor[1], inColor[2], inColor[3]);
  3065. }
  3066. return splatArray;
  3067. }
  3068. }
  3069. class SplatLoader {
  3070. static loadFromURL(fileName, onProgress, progressiveLoad, onStreamedSectionProgress, minimumAlpha, compressionLevel,
  3071. optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize) {
  3072. const splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes;
  3073. const progressiveLoadSectionSizeBytes = Constants.ProgressiveLoadSectionSize;
  3074. const sectionCount = 1;
  3075. let progressiveLoadBufferIn;
  3076. let progressiveLoadBufferOut;
  3077. let progressiveLoadSplatBuffer;
  3078. let maxSplatCount = 0;
  3079. let splatCount = 0;
  3080. const progressiveLoadPromise = nativePromiseWithExtractedComponents();
  3081. let numBytesStreamed = 0;
  3082. let numBytesLoaded = 0;
  3083. let chunks = [];
  3084. const localOnProgress = (percent, percentStr, chunk, fileSize) => {
  3085. const loadComplete = percent >= 100;
  3086. if (!fileSize) progressiveLoad = false;
  3087. if (progressiveLoad) {
  3088. if (!progressiveLoadBufferIn) {
  3089. maxSplatCount = fileSize / SplatParser.RowSizeBytes;
  3090. progressiveLoadBufferIn = new ArrayBuffer(fileSize);
  3091. const bytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  3092. const splatBufferSizeBytes = splatDataOffsetBytes + bytesPerSplat * maxSplatCount;
  3093. progressiveLoadBufferOut = new ArrayBuffer(splatBufferSizeBytes);
  3094. SplatBuffer.writeHeaderToBuffer({
  3095. versionMajor: SplatBuffer.CurrentMajorVersion,
  3096. versionMinor: SplatBuffer.CurrentMinorVersion,
  3097. maxSectionCount: sectionCount,
  3098. sectionCount: sectionCount,
  3099. maxSplatCount: maxSplatCount,
  3100. splatCount: splatCount,
  3101. compressionLevel: 0,
  3102. sceneCenter: new THREE.Vector3()
  3103. }, progressiveLoadBufferOut);
  3104. }
  3105. if (chunk) {
  3106. chunks.push(chunk);
  3107. new Uint8Array(progressiveLoadBufferIn, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk));
  3108. numBytesLoaded += chunk.byteLength;
  3109. const bytesLoadedSinceLastSection = numBytesLoaded - numBytesStreamed;
  3110. if (bytesLoadedSinceLastSection > progressiveLoadSectionSizeBytes || loadComplete) {
  3111. const bytesToUpdate = loadComplete ? bytesLoadedSinceLastSection : progressiveLoadSectionSizeBytes;
  3112. const addedSplatCount = bytesToUpdate / SplatParser.RowSizeBytes;
  3113. const newSplatCount = splatCount + addedSplatCount;
  3114. SplatParser.parseToUncompressedSplatBufferSection(splatCount, newSplatCount - 1, progressiveLoadBufferIn, 0,
  3115. progressiveLoadBufferOut, splatDataOffsetBytes);
  3116. splatCount = newSplatCount;
  3117. if (!progressiveLoadSplatBuffer) {
  3118. SplatBuffer.writeSectionHeaderToBuffer({
  3119. maxSplatCount: maxSplatCount,
  3120. splatCount: splatCount,
  3121. bucketSize: 0,
  3122. bucketCount: 0,
  3123. bucketBlockSize: 0,
  3124. compressionScaleRange: 0,
  3125. storageSizeBytes: 0,
  3126. fullBucketCount: 0,
  3127. partiallyFilledBucketCount: 0
  3128. }, 0, progressiveLoadBufferOut, SplatBuffer.HeaderSizeBytes);
  3129. progressiveLoadSplatBuffer = new SplatBuffer(progressiveLoadBufferOut, false);
  3130. }
  3131. progressiveLoadSplatBuffer.updateLoadedCounts(1, splatCount);
  3132. onStreamedSectionProgress(progressiveLoadSplatBuffer, loadComplete);
  3133. numBytesStreamed += progressiveLoadSectionSizeBytes;
  3134. }
  3135. }
  3136. if (loadComplete) {
  3137. progressiveLoadPromise.resolve(progressiveLoadSplatBuffer);
  3138. }
  3139. }
  3140. if (onProgress) onProgress(percent, percentStr, LoaderStatus.Downloading);
  3141. return progressiveLoad;
  3142. };
  3143. return fetchWithProgress(fileName, localOnProgress, true).then((fullBuffer) => {
  3144. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  3145. const loadPromise = progressiveLoad ? progressiveLoadPromise.promise :
  3146. SplatLoader.loadFromFileData(fullBuffer, minimumAlpha, compressionLevel, optimizeSplatData,
  3147. sectionSize, sceneCenter, blockSize, bucketSize);
  3148. return loadPromise.then((splatBuffer) => {
  3149. if (onProgress) onProgress(100, '100%', LoaderStatus.Done);
  3150. return splatBuffer;
  3151. });
  3152. });
  3153. }
  3154. static loadFromFileData(splatFileData, minimumAlpha, compressionLevel, optimizeSplatData,
  3155. sectionSize, sceneCenter, blockSize, bucketSize) {
  3156. return delayedExecute(() => {
  3157. const splatArray = SplatParser.parseStandardSplatToUncompressedSplatArray(splatFileData);
  3158. if (optimizeSplatData) {
  3159. const splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel,
  3160. sectionSize, sceneCenter, blockSize,
  3161. bucketSize);
  3162. return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray);
  3163. } else {
  3164. return SplatBuffer.generateFromUncompressedSplatArrays([splatArray], minimumAlpha, 0, new THREE.Vector3());
  3165. }
  3166. });
  3167. }
  3168. }
  3169. class KSplatLoader {
  3170. static checkVersion(buffer) {
  3171. const minVersionMajor = SplatBuffer.CurrentMajorVersion;
  3172. const minVersionMinor = SplatBuffer.CurrentMinorVersion;
  3173. const header = SplatBuffer.parseHeader(buffer);
  3174. if (header.versionMajor === minVersionMajor &&
  3175. header.versionMinor >= minVersionMinor ||
  3176. header.versionMajor > minVersionMajor) {
  3177. return true;
  3178. } else {
  3179. throw new Error(`KSplat version not supported: v${header.versionMajor}.${header.versionMinor}. ` +
  3180. `Minimum required: v${minVersionMajor}.${minVersionMinor}`);
  3181. }
  3182. };
  3183. static loadFromURL(fileName, externalOnProgress, progressiveLoad, onSectionBuilt) {
  3184. let progressiveLoadBuffer;
  3185. let progressiveLoadSplatBuffer;
  3186. let headerBuffer;
  3187. let header;
  3188. let headerLoaded = false;
  3189. let headerLoading = false;
  3190. let sectionHeadersBuffer;
  3191. let sectionHeaders = [];
  3192. let sectionHeadersLoaded = false;
  3193. let sectionHeadersLoading = false;
  3194. let numBytesLoaded = 0;
  3195. let numBytesProgressivelyLoaded = 0;
  3196. let totalBytesToDownload = 0;
  3197. let downloadComplete = false;
  3198. let loadComplete = false;
  3199. let loadSectionQueued = false;
  3200. let chunks = [];
  3201. const progressiveLoadPromise = nativePromiseWithExtractedComponents();
  3202. const checkAndLoadHeader = () => {
  3203. if (!headerLoaded && !headerLoading && numBytesLoaded >= SplatBuffer.HeaderSizeBytes) {
  3204. headerLoading = true;
  3205. const headerAssemblyPromise = new Blob(chunks).arrayBuffer();
  3206. headerAssemblyPromise.then((bufferData) => {
  3207. headerBuffer = new ArrayBuffer(SplatBuffer.HeaderSizeBytes);
  3208. new Uint8Array(headerBuffer).set(new Uint8Array(bufferData, 0, SplatBuffer.HeaderSizeBytes));
  3209. KSplatLoader.checkVersion(headerBuffer);
  3210. headerLoading = false;
  3211. headerLoaded = true;
  3212. header = SplatBuffer.parseHeader(headerBuffer);
  3213. window.setTimeout(() => {
  3214. checkAndLoadSectionHeaders();
  3215. }, 1);
  3216. });
  3217. }
  3218. };
  3219. let queuedCheckAndLoadSectionsCount = 0;
  3220. const queueCheckAndLoadSections = () => {
  3221. if (queuedCheckAndLoadSectionsCount === 0) {
  3222. queuedCheckAndLoadSectionsCount++;
  3223. window.setTimeout(() => {
  3224. queuedCheckAndLoadSectionsCount--;
  3225. checkAndLoadSections();
  3226. }, 1);
  3227. }
  3228. };
  3229. const checkAndLoadSectionHeaders = () => {
  3230. const performLoad = () => {
  3231. sectionHeadersLoading = true;
  3232. const sectionHeadersAssemblyPromise = new Blob(chunks).arrayBuffer();
  3233. sectionHeadersAssemblyPromise.then((bufferData) => {
  3234. sectionHeadersLoading = false;
  3235. sectionHeadersLoaded = true;
  3236. sectionHeadersBuffer = new ArrayBuffer(header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes);
  3237. new Uint8Array(sectionHeadersBuffer).set(new Uint8Array(bufferData, SplatBuffer.HeaderSizeBytes,
  3238. header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes));
  3239. sectionHeaders = SplatBuffer.parseSectionHeaders(header, sectionHeadersBuffer, 0, false);
  3240. let totalSectionStorageStorageByes = 0;
  3241. for (let i = 0; i < header.maxSectionCount; i++) {
  3242. totalSectionStorageStorageByes += sectionHeaders[i].storageSizeBytes;
  3243. }
  3244. const totalStorageSizeBytes = SplatBuffer.HeaderSizeBytes + header.maxSectionCount *
  3245. SplatBuffer.SectionHeaderSizeBytes + totalSectionStorageStorageByes;
  3246. if (!progressiveLoadBuffer) {
  3247. progressiveLoadBuffer = new ArrayBuffer(totalStorageSizeBytes);
  3248. let offset = 0;
  3249. for (let i = 0; i < chunks.length; i++) {
  3250. const chunk = chunks[i];
  3251. new Uint8Array(progressiveLoadBuffer, offset, chunk.byteLength).set(new Uint8Array(chunk));
  3252. offset += chunk.byteLength;
  3253. }
  3254. }
  3255. totalBytesToDownload = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount;
  3256. for (let i = 0; i <= sectionHeaders.length && i < header.maxSectionCount; i++) {
  3257. totalBytesToDownload += sectionHeaders[i].storageSizeBytes;
  3258. }
  3259. queueCheckAndLoadSections();
  3260. });
  3261. };
  3262. if (!sectionHeadersLoading && !sectionHeadersLoaded && headerLoaded &&
  3263. numBytesLoaded >= SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount) {
  3264. performLoad();
  3265. }
  3266. };
  3267. const checkAndLoadSections = () => {
  3268. if (loadSectionQueued) return;
  3269. loadSectionQueued = true;
  3270. const checkAndLoadFunc = () => {
  3271. loadSectionQueued = false;
  3272. if (sectionHeadersLoaded) {
  3273. if (loadComplete) return;
  3274. downloadComplete = numBytesLoaded >= totalBytesToDownload;
  3275. let bytesLoadedSinceLastSection = numBytesLoaded - numBytesProgressivelyLoaded;
  3276. if (bytesLoadedSinceLastSection > Constants.ProgressiveLoadSectionSize || downloadComplete) {
  3277. numBytesProgressivelyLoaded += Constants.ProgressiveLoadSectionSize;
  3278. loadComplete = numBytesProgressivelyLoaded >= totalBytesToDownload;
  3279. if (!progressiveLoadSplatBuffer) progressiveLoadSplatBuffer = new SplatBuffer(progressiveLoadBuffer, false);
  3280. const baseDataOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount;
  3281. let sectionBase = 0;
  3282. let reachedSections = 0;
  3283. let loadedSplatCount = 0;
  3284. for (let i = 0; i < header.maxSectionCount; i++) {
  3285. const sectionHeader = sectionHeaders[i];
  3286. const bucketsDataOffset = sectionBase + sectionHeader.partiallyFilledBucketCount * 4 +
  3287. sectionHeader.bucketStorageSizeBytes * sectionHeader.bucketCount;
  3288. const bytesRequiredToReachSectionSplatData = baseDataOffset + bucketsDataOffset;
  3289. if (numBytesProgressivelyLoaded >= bytesRequiredToReachSectionSplatData) {
  3290. reachedSections++;
  3291. const bytesPastSSectionSplatDataStart = numBytesProgressivelyLoaded - bytesRequiredToReachSectionSplatData;
  3292. const baseDescriptor = SplatBuffer.CompressionLevels[header.compressionLevel];
  3293. const shDesc = baseDescriptor.SphericalHarmonicsDegrees[sectionHeader.sphericalHarmonicsDegree];
  3294. const bytesPerSplat = shDesc.BytesPerSplat;
  3295. let loadedSplatsForSection = Math.floor(bytesPastSSectionSplatDataStart / bytesPerSplat);
  3296. loadedSplatsForSection = Math.min(loadedSplatsForSection, sectionHeader.maxSplatCount);
  3297. loadedSplatCount += loadedSplatsForSection;
  3298. progressiveLoadSplatBuffer.updateLoadedCounts(reachedSections, loadedSplatCount);
  3299. progressiveLoadSplatBuffer.updateSectionLoadedCounts(i, loadedSplatsForSection);
  3300. } else {
  3301. break;
  3302. }
  3303. sectionBase += sectionHeader.storageSizeBytes;
  3304. }
  3305. onSectionBuilt(progressiveLoadSplatBuffer, loadComplete);
  3306. const percentComplete = numBytesProgressivelyLoaded / totalBytesToDownload * 100;
  3307. const percentLabel = (percentComplete).toFixed(2) + '%';
  3308. if (externalOnProgress) externalOnProgress(percentComplete, percentLabel, LoaderStatus.Downloading);
  3309. if (loadComplete) {
  3310. progressiveLoadPromise.resolve(progressiveLoadSplatBuffer);
  3311. } else {
  3312. checkAndLoadSections();
  3313. }
  3314. }
  3315. }
  3316. };
  3317. window.setTimeout(checkAndLoadFunc, Constants.ProgressiveLoadSectionDelayDuration);
  3318. };
  3319. const localOnProgress = (percent, percentStr, chunk) => {
  3320. if (chunk) {
  3321. chunks.push(chunk);
  3322. if (progressiveLoadBuffer) {
  3323. new Uint8Array(progressiveLoadBuffer, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk));
  3324. }
  3325. numBytesLoaded += chunk.byteLength;
  3326. }
  3327. if (progressiveLoad) {
  3328. checkAndLoadHeader();
  3329. checkAndLoadSectionHeaders();
  3330. checkAndLoadSections();
  3331. } else {
  3332. if (externalOnProgress) externalOnProgress(percent, percentStr, LoaderStatus.Downloading);
  3333. }
  3334. };
  3335. return fetchWithProgress(fileName, localOnProgress, !progressiveLoad).then((fullBuffer) => {
  3336. if (externalOnProgress) externalOnProgress(0, '0%', LoaderStatus.Processing);
  3337. const loadPromise = progressiveLoad ? progressiveLoadPromise.promise : KSplatLoader.loadFromFileData(fullBuffer);
  3338. return loadPromise.then((splatBuffer) => {
  3339. if (externalOnProgress) externalOnProgress(100, '100%', LoaderStatus.Done);
  3340. return splatBuffer;
  3341. });
  3342. });
  3343. }
  3344. static loadFromFileData(fileData) {
  3345. return delayedExecute(() => {
  3346. KSplatLoader.checkVersion(fileData);
  3347. return new SplatBuffer(fileData);
  3348. });
  3349. }
  3350. static downloadFile = function() {
  3351. let downLoadLink;
  3352. return function(splatBuffer, fileName) {
  3353. const blob = new Blob([splatBuffer.bufferData], {
  3354. type: 'application/octet-stream',
  3355. });
  3356. if (!downLoadLink) {
  3357. downLoadLink = document.createElement('a');
  3358. document.body.appendChild(downLoadLink);
  3359. }
  3360. downLoadLink.download = fileName;
  3361. downLoadLink.href = URL.createObjectURL(blob);
  3362. downLoadLink.click();
  3363. };
  3364. }();
  3365. }
  3366. const SceneFormat = {
  3367. 'Splat': 0,
  3368. 'KSplat': 1,
  3369. 'Ply': 2
  3370. };
  3371. const sceneFormatFromPath = (path) => {
  3372. if (path.endsWith('.ply')) return SceneFormat.Ply;
  3373. else if (path.endsWith('.splat')) return SceneFormat.Splat;
  3374. else if (path.endsWith('.ksplat')) return SceneFormat.KSplat;
  3375. return null;
  3376. };
  3377. var Utils = /*#__PURE__*/Object.freeze({
  3378. __proto__: null,
  3379. sceneFormatFromPath: sceneFormatFromPath
  3380. });
  3381. /*
  3382. Copyright © 2010-2024 three.js authors & Mark Kellogg
  3383. Permission is hereby granted, free of charge, to any person obtaining a copy
  3384. of this software and associated documentation files (the "Software"), to deal
  3385. in the Software without restriction, including without limitation the rights
  3386. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3387. copies of the Software, and to permit persons to whom the Software is
  3388. furnished to do so, subject to the following conditions:
  3389. The above copyright notice and this permission notice shall be included in
  3390. all copies or substantial portions of the Software.
  3391. */
  3392. // OrbitControls performs orbiting, dollying (zooming), and panning.
  3393. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  3394. //
  3395. // Orbit - left mouse / touch: one-finger move
  3396. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  3397. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  3398. const _changeEvent = { type: 'change' };
  3399. const _startEvent = { type: 'start' };
  3400. const _endEvent = { type: 'end' };
  3401. const _ray = new Ray$1();
  3402. const _plane = new Plane();
  3403. const TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
  3404. class OrbitControls extends EventDispatcher {
  3405. constructor( object, domElement ) {
  3406. super();
  3407. this.object = object;
  3408. this.domElement = domElement;
  3409. this.domElement.style.touchAction = 'none'; // disable touch scroll
  3410. // Set to false to disable this control
  3411. this.enabled = true;
  3412. // "target" sets the location of focus, where the object orbits around
  3413. this.target = new Vector3();
  3414. // How far you can dolly in and out ( PerspectiveCamera only )
  3415. this.minDistance = 0;
  3416. this.maxDistance = Infinity;
  3417. // How far you can zoom in and out ( OrthographicCamera only )
  3418. this.minZoom = 0;
  3419. this.maxZoom = Infinity;
  3420. // How far you can orbit vertically, upper and lower limits.
  3421. // Range is 0 to Math.PI radians.
  3422. this.minPolarAngle = 0; // radians
  3423. this.maxPolarAngle = Math.PI; // radians
  3424. // How far you can orbit horizontally, upper and lower limits.
  3425. // If set, the interval [min, max] must be a sub-interval of [- 2 PI, 2 PI], with ( max - min < 2 PI )
  3426. this.minAzimuthAngle = - Infinity; // radians
  3427. this.maxAzimuthAngle = Infinity; // radians
  3428. // Set to true to enable damping (inertia)
  3429. // If damping is enabled, you must call controls.update() in your animation loop
  3430. this.enableDamping = false;
  3431. this.dampingFactor = 0.05;
  3432. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  3433. // Set to false to disable zooming
  3434. this.enableZoom = true;
  3435. this.zoomSpeed = 1.0;
  3436. // Set to false to disable rotating
  3437. this.enableRotate = true;
  3438. this.rotateSpeed = 1.0;
  3439. // Set to false to disable panning
  3440. this.enablePan = true;
  3441. this.panSpeed = 1.0;
  3442. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  3443. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  3444. this.zoomToCursor = false;
  3445. // Set to true to automatically rotate around the target
  3446. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  3447. this.autoRotate = false;
  3448. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  3449. // The four arrow keys
  3450. //this.keys = { LEFT: 'KeyA', UP: 'KeyW', RIGHT: 'KeyD', BOTTOM: 'KeyS' };
  3451. this.keys = { LEFT: 'KeyA', UP: 'KeyE', RIGHT: 'KeyD', BOTTOM: 'KeyQ', Forward:'KeyW', Backward:'KeyS' };
  3452. // Mouse buttons
  3453. this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
  3454. // Touch fingers
  3455. this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
  3456. // for reset
  3457. this.target0 = this.target.clone();
  3458. this.position0 = this.object.position.clone();
  3459. this.zoom0 = this.object.zoom;
  3460. // the target DOM element for key events
  3461. this._domElementKeyEvents = null;
  3462. //
  3463. // public methods
  3464. //
  3465. this.getPolarAngle = function() {
  3466. return spherical.phi;
  3467. };
  3468. this.getAzimuthalAngle = function() {
  3469. return spherical.theta;
  3470. };
  3471. this.getDistance = function() {
  3472. return this.object.position.distanceTo( this.target );
  3473. };
  3474. this.listenToKeyEvents = function( domElement ) {
  3475. domElement.addEventListener( 'keydown', onKeyDown );
  3476. this._domElementKeyEvents = domElement;
  3477. };
  3478. this.stopListenToKeyEvents = function() {
  3479. this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  3480. this._domElementKeyEvents = null;
  3481. };
  3482. this.saveState = function() {
  3483. scope.target0.copy( scope.target );
  3484. scope.position0.copy( scope.object.position );
  3485. scope.zoom0 = scope.object.zoom;
  3486. };
  3487. this.reset = function() {
  3488. scope.target.copy( scope.target0 );
  3489. scope.object.position.copy( scope.position0 );
  3490. scope.object.zoom = scope.zoom0;
  3491. this.clearDampedRotation();
  3492. this.clearDampedPan();
  3493. scope.object.updateProjectionMatrix();
  3494. scope.dispatchEvent( _changeEvent );
  3495. scope.update();
  3496. state = STATE.NONE;
  3497. };
  3498. this.clearDampedRotation = function() {
  3499. sphericalDelta.theta = 0.0;
  3500. sphericalDelta.phi = 0.0;
  3501. };
  3502. this.clearDampedPan = function() {
  3503. panOffset.set(0, 0, 0);
  3504. };
  3505. // this method is exposed, but perhaps it would be better if we can make it private...
  3506. this.update = function() {
  3507. const offset = new Vector3();
  3508. // so camera.up is the orbit axis
  3509. const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
  3510. const quatInverse = quat.clone().invert();
  3511. const lastPosition = new Vector3();
  3512. const lastQuaternion = new Quaternion();
  3513. const lastTargetPosition = new Vector3();
  3514. const twoPI = 2 * Math.PI;
  3515. return function update() {
  3516. quat.setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
  3517. quatInverse.copy(quat).invert();
  3518. const position = scope.object.position;
  3519. offset.copy( position ).sub( scope.target );
  3520. // rotate offset to "y-axis-is-up" space
  3521. offset.applyQuaternion( quat );
  3522. // angle from z-axis around y-axis
  3523. spherical.setFromVector3( offset );
  3524. if ( scope.autoRotate && state === STATE.NONE ) {
  3525. rotateLeft( getAutoRotationAngle() );
  3526. }
  3527. if ( scope.enableDamping ) {
  3528. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  3529. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  3530. } else {
  3531. spherical.theta += sphericalDelta.theta;
  3532. spherical.phi += sphericalDelta.phi;
  3533. }
  3534. // restrict theta to be between desired limits
  3535. let min = scope.minAzimuthAngle;
  3536. let max = scope.maxAzimuthAngle;
  3537. if ( isFinite( min ) && isFinite( max ) ) {
  3538. if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
  3539. if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
  3540. if ( min <= max ) {
  3541. spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
  3542. } else {
  3543. spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
  3544. Math.max( min, spherical.theta ) :
  3545. Math.min( max, spherical.theta );
  3546. }
  3547. }
  3548. // restrict phi to be between desired limits
  3549. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  3550. spherical.makeSafe();
  3551. // move target to panned location
  3552. if ( scope.enableDamping === true ) {
  3553. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  3554. } else {
  3555. scope.target.add( panOffset );
  3556. }
  3557. // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
  3558. // we adjust zoom later in these cases
  3559. if ( scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera ) {
  3560. spherical.radius = clampDistance( spherical.radius );
  3561. } else {
  3562. spherical.radius = clampDistance( spherical.radius * scale );
  3563. }
  3564. offset.setFromSpherical( spherical );
  3565. // rotate offset back to "camera-up-vector-is-up" space
  3566. offset.applyQuaternion( quatInverse );
  3567. position.copy( scope.target ).add( offset );
  3568. //xzw 到达中心点后还能继续向前移动,也就是能推进中心点
  3569. const minRadius = 2;
  3570. if(offset.length() < minRadius){
  3571. let offsetNew = offset.clone().normalize().multiplyScalar(minRadius);
  3572. scope.target.copy(position).sub(offsetNew);
  3573. }
  3574. scope.object.lookAt( scope.target );
  3575. if ( scope.enableDamping === true ) {
  3576. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  3577. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  3578. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  3579. } else {
  3580. sphericalDelta.set( 0, 0, 0 );
  3581. panOffset.set( 0, 0, 0 );
  3582. }
  3583. // adjust camera position
  3584. let zoomChanged = false;
  3585. if ( scope.zoomToCursor && performCursorZoom ) {
  3586. let newRadius = null;
  3587. if ( scope.object.isPerspectiveCamera ) {
  3588. // move the camera down the pointer ray
  3589. // this method avoids floating point error
  3590. const prevRadius = offset.length();
  3591. newRadius = clampDistance( prevRadius * scale );
  3592. const radiusDelta = prevRadius - newRadius;
  3593. scope.object.position.addScaledVector( dollyDirection, radiusDelta );
  3594. scope.object.updateMatrixWorld();
  3595. } else if ( scope.object.isOrthographicCamera ) {
  3596. // adjust the ortho camera position based on zoom changes
  3597. const mouseBefore = new Vector3( mouse.x, mouse.y, 0 );
  3598. mouseBefore.unproject( scope.object );
  3599. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  3600. scope.object.updateProjectionMatrix();
  3601. zoomChanged = true;
  3602. const mouseAfter = new Vector3( mouse.x, mouse.y, 0 );
  3603. mouseAfter.unproject( scope.object );
  3604. scope.object.position.sub( mouseAfter ).add( mouseBefore );
  3605. scope.object.updateMatrixWorld();
  3606. newRadius = offset.length();
  3607. } else {
  3608. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
  3609. scope.zoomToCursor = false;
  3610. }
  3611. // handle the placement of the target
  3612. if ( newRadius !== null ) {
  3613. if ( this.screenSpacePanning ) {
  3614. // position the orbit target in front of the new camera position
  3615. scope.target.set( 0, 0, - 1 )
  3616. .transformDirection( scope.object.matrix )
  3617. .multiplyScalar( newRadius )
  3618. .add( scope.object.position );
  3619. } else {
  3620. // get the ray and translation plane to compute target
  3621. _ray.origin.copy( scope.object.position );
  3622. _ray.direction.set( 0, 0, - 1 ).transformDirection( scope.object.matrix );
  3623. // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
  3624. // extremely large values
  3625. if ( Math.abs( scope.object.up.dot( _ray.direction ) ) < TILT_LIMIT ) {
  3626. object.lookAt( scope.target );
  3627. } else {
  3628. _plane.setFromNormalAndCoplanarPoint( scope.object.up, scope.target );
  3629. _ray.intersectPlane( _plane, scope.target );
  3630. }
  3631. }
  3632. }
  3633. } else if ( scope.object.isOrthographicCamera ) {
  3634. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  3635. scope.object.updateProjectionMatrix();
  3636. zoomChanged = true;
  3637. }
  3638. scale = 1;
  3639. performCursorZoom = false;
  3640. // update condition is:
  3641. // min(camera displacement, camera rotation in radians)^2 > EPS
  3642. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  3643. if ( zoomChanged ||
  3644. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  3645. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ||
  3646. lastTargetPosition.distanceToSquared( scope.target ) > 0 ) {
  3647. scope.dispatchEvent( _changeEvent );
  3648. lastPosition.copy( scope.object.position );
  3649. lastQuaternion.copy( scope.object.quaternion );
  3650. lastTargetPosition.copy( scope.target );
  3651. zoomChanged = false;
  3652. return true;
  3653. }
  3654. return false;
  3655. };
  3656. }();
  3657. this.dispose = function() {
  3658. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  3659. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  3660. scope.domElement.removeEventListener( 'pointercancel', onPointerUp );
  3661. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  3662. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  3663. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  3664. if ( scope._domElementKeyEvents !== null ) {
  3665. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  3666. scope._domElementKeyEvents = null;
  3667. }
  3668. };
  3669. //
  3670. // internals
  3671. //
  3672. const scope = this;
  3673. const STATE = {
  3674. NONE: - 1,
  3675. ROTATE: 0,
  3676. DOLLY: 1,
  3677. PAN: 2,
  3678. TOUCH_ROTATE: 3,
  3679. TOUCH_PAN: 4,
  3680. TOUCH_DOLLY_PAN: 5,
  3681. TOUCH_DOLLY_ROTATE: 6
  3682. };
  3683. let state = STATE.NONE;
  3684. const EPS = 0.000001;
  3685. // current position in spherical coordinates
  3686. const spherical = new Spherical();
  3687. const sphericalDelta = new Spherical();
  3688. let scale = 1;
  3689. const panOffset = new Vector3();
  3690. const rotateStart = new Vector2();
  3691. const rotateEnd = new Vector2();
  3692. const rotateDelta = new Vector2();
  3693. const panStart = new Vector2();
  3694. const panEnd = new Vector2();
  3695. const panDelta = new Vector2();
  3696. const dollyStart = new Vector2();
  3697. const dollyEnd = new Vector2();
  3698. const dollyDelta = new Vector2();
  3699. const dollyDirection = new Vector3();
  3700. const mouse = new Vector2();
  3701. let performCursorZoom = false;
  3702. const pointers = [];
  3703. const pointerPositions = {};
  3704. function getAutoRotationAngle() {
  3705. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  3706. }
  3707. function getZoomScale() {
  3708. return Math.pow( 0.95, scope.zoomSpeed );
  3709. }
  3710. function rotateLeft( angle ) {
  3711. sphericalDelta.theta -= angle;
  3712. }
  3713. function rotateUp( angle ) {
  3714. sphericalDelta.phi -= angle;
  3715. }
  3716. const panLeft = function() {
  3717. const v = new Vector3();
  3718. return function panLeft( distance, objectMatrix ) {
  3719. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  3720. v.multiplyScalar( - distance );
  3721. panOffset.add( v );
  3722. };
  3723. }();
  3724. const panUp = function() {
  3725. const v = new Vector3();
  3726. return function panUp( distance, objectMatrix ) {
  3727. if ( scope.screenSpacePanning === true ) {
  3728. v.setFromMatrixColumn( objectMatrix, 1 );
  3729. } else {
  3730. v.setFromMatrixColumn( objectMatrix, 0 );
  3731. v.crossVectors( scope.object.up, v );
  3732. }
  3733. v.multiplyScalar( distance );
  3734. panOffset.add( v );
  3735. };
  3736. }();
  3737. // deltaX and deltaY are in pixels; right and down are positive
  3738. const pan = function() {
  3739. const offset = new Vector3();
  3740. return function pan( deltaX, deltaY ) {
  3741. const element = scope.domElement;
  3742. if ( scope.object.isPerspectiveCamera ) {
  3743. // perspective
  3744. const position = scope.object.position;
  3745. offset.copy( position ).sub( scope.target );
  3746. let targetDistance = offset.length();
  3747. // half of the fov is center to top of screen
  3748. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  3749. // we use only clientHeight here so aspect ratio does not distort speed
  3750. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  3751. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  3752. } else if ( scope.object.isOrthographicCamera ) {
  3753. // orthographic
  3754. panLeft( deltaX * ( scope.object.right - scope.object.left ) /
  3755. scope.object.zoom / element.clientWidth, scope.object.matrix );
  3756. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom /
  3757. element.clientHeight, scope.object.matrix );
  3758. } else {
  3759. // camera neither orthographic nor perspective
  3760. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  3761. scope.enablePan = false;
  3762. }
  3763. };
  3764. }();
  3765. function dollyOut( dollyScale ) {
  3766. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  3767. scale /= dollyScale;
  3768. } else {
  3769. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  3770. scope.enableZoom = false;
  3771. }
  3772. }
  3773. function dollyIn( dollyScale ) {
  3774. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  3775. scale *= dollyScale;
  3776. } else {
  3777. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  3778. scope.enableZoom = false;
  3779. }
  3780. }
  3781. function updateMouseParameters( event ) {
  3782. if ( ! scope.zoomToCursor ) {
  3783. return;
  3784. }
  3785. performCursorZoom = true;
  3786. const rect = scope.domElement.getBoundingClientRect();
  3787. const x = event.clientX - rect.left;
  3788. const y = event.clientY - rect.top;
  3789. const w = rect.width;
  3790. const h = rect.height;
  3791. mouse.x = ( x / w ) * 2 - 1;
  3792. mouse.y = - ( y / h ) * 2 + 1;
  3793. dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( object ).sub( object.position ).normalize();
  3794. }
  3795. function clampDistance( dist ) {
  3796. return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) );
  3797. }
  3798. //
  3799. // event callbacks - update the object state
  3800. //
  3801. function handleMouseDownRotate( event ) {
  3802. rotateStart.set( event.clientX, event.clientY );
  3803. }
  3804. function handleMouseDownDolly( event ) {
  3805. updateMouseParameters( event );
  3806. dollyStart.set( event.clientX, event.clientY );
  3807. }
  3808. function handleMouseDownPan( event ) {
  3809. panStart.set( event.clientX, event.clientY );
  3810. }
  3811. function handleMouseMoveRotate( event ) {
  3812. rotateEnd.set( event.clientX, event.clientY );
  3813. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  3814. const element = scope.domElement;
  3815. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  3816. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  3817. rotateStart.copy( rotateEnd );
  3818. scope.update();
  3819. }
  3820. function handleMouseMoveDolly( event ) {
  3821. dollyEnd.set( event.clientX, event.clientY );
  3822. dollyDelta.subVectors( dollyEnd, dollyStart );
  3823. if ( dollyDelta.y > 0 ) {
  3824. dollyOut( getZoomScale() );
  3825. } else if ( dollyDelta.y < 0 ) {
  3826. dollyIn( getZoomScale() );
  3827. }
  3828. dollyStart.copy( dollyEnd );
  3829. scope.update();
  3830. }
  3831. function handleMouseMovePan( event ) {
  3832. panEnd.set( event.clientX, event.clientY );
  3833. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  3834. pan( panDelta.x, panDelta.y );
  3835. panStart.copy( panEnd );
  3836. scope.update();
  3837. }
  3838. function handleMouseWheel( event ) {
  3839. updateMouseParameters( event );
  3840. if ( event.deltaY < 0 ) {
  3841. dollyIn( getZoomScale() );
  3842. } else if ( event.deltaY > 0 ) {
  3843. dollyOut( getZoomScale() );
  3844. }
  3845. scope.update();
  3846. }
  3847. function handleKeyDown( event ) {
  3848. let needsUpdate = false;
  3849. switch ( event.code ) {
  3850. case scope.keys.UP:
  3851. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  3852. rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  3853. } else {
  3854. pan( 0, scope.keyPanSpeed );
  3855. }
  3856. needsUpdate = true;
  3857. break;
  3858. case scope.keys.BOTTOM:
  3859. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  3860. rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  3861. } else {
  3862. pan( 0, - scope.keyPanSpeed );
  3863. }
  3864. needsUpdate = true;
  3865. break;
  3866. //xzw add: 应要求把WS改为前进后退------
  3867. case scope.keys.Forward:
  3868. dollyIn( getZoomScale() );
  3869. //state = STATE.DOLLY;
  3870. break;
  3871. case scope.keys.Backward:
  3872. dollyOut( getZoomScale() );
  3873. //state = STATE.DOLLY;
  3874. break
  3875. //--------------------------------------
  3876. case scope.keys.LEFT:
  3877. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  3878. rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  3879. } else {
  3880. pan( scope.keyPanSpeed, 0 );
  3881. }
  3882. needsUpdate = true;
  3883. break;
  3884. case scope.keys.RIGHT:
  3885. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  3886. rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  3887. } else {
  3888. pan( - scope.keyPanSpeed, 0 );
  3889. }
  3890. needsUpdate = true;
  3891. break;
  3892. }
  3893. if ( needsUpdate ) {
  3894. // prevent the browser from scrolling on cursor keys
  3895. event.preventDefault();
  3896. scope.update();
  3897. }
  3898. }
  3899. function handleTouchStartRotate() {
  3900. if ( pointers.length === 1 ) {
  3901. rotateStart.set( pointers[0].pageX, pointers[0].pageY );
  3902. } else {
  3903. const x = 0.5 * ( pointers[0].pageX + pointers[1].pageX );
  3904. const y = 0.5 * ( pointers[0].pageY + pointers[1].pageY );
  3905. rotateStart.set( x, y );
  3906. }
  3907. }
  3908. function handleTouchStartPan() {
  3909. if ( pointers.length === 1 ) {
  3910. panStart.set( pointers[0].pageX, pointers[0].pageY );
  3911. } else {
  3912. const x = 0.5 * ( pointers[0].pageX + pointers[1].pageX );
  3913. const y = 0.5 * ( pointers[0].pageY + pointers[1].pageY );
  3914. panStart.set( x, y );
  3915. }
  3916. }
  3917. function handleTouchStartDolly() {
  3918. const dx = pointers[0].pageX - pointers[1].pageX;
  3919. const dy = pointers[0].pageY - pointers[1].pageY;
  3920. const distance = Math.sqrt( dx * dx + dy * dy );
  3921. dollyStart.set( 0, distance );
  3922. }
  3923. function handleTouchStartDollyPan() {
  3924. if ( scope.enableZoom ) handleTouchStartDolly();
  3925. if ( scope.enablePan ) handleTouchStartPan();
  3926. }
  3927. function handleTouchStartDollyRotate() {
  3928. if ( scope.enableZoom ) handleTouchStartDolly();
  3929. if ( scope.enableRotate ) handleTouchStartRotate();
  3930. }
  3931. function handleTouchMoveRotate( event ) {
  3932. if ( pointers.length == 1 ) {
  3933. rotateEnd.set( event.pageX, event.pageY );
  3934. } else {
  3935. const position = getSecondPointerPosition( event );
  3936. const x = 0.5 * ( event.pageX + position.x );
  3937. const y = 0.5 * ( event.pageY + position.y );
  3938. rotateEnd.set( x, y );
  3939. }
  3940. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  3941. const element = scope.domElement;
  3942. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  3943. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  3944. rotateStart.copy( rotateEnd );
  3945. }
  3946. function handleTouchMovePan( event ) {
  3947. if ( pointers.length === 1 ) {
  3948. panEnd.set( event.pageX, event.pageY );
  3949. } else {
  3950. const position = getSecondPointerPosition( event );
  3951. const x = 0.5 * ( event.pageX + position.x );
  3952. const y = 0.5 * ( event.pageY + position.y );
  3953. panEnd.set( x, y );
  3954. }
  3955. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  3956. pan( panDelta.x, panDelta.y );
  3957. panStart.copy( panEnd );
  3958. }
  3959. function handleTouchMoveDolly( event ) {
  3960. const position = getSecondPointerPosition( event );
  3961. const dx = event.pageX - position.x;
  3962. const dy = event.pageY - position.y;
  3963. const distance = Math.sqrt( dx * dx + dy * dy );
  3964. dollyEnd.set( 0, distance );
  3965. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  3966. dollyOut( dollyDelta.y );
  3967. dollyStart.copy( dollyEnd );
  3968. }
  3969. function handleTouchMoveDollyPan( event ) {
  3970. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  3971. if ( scope.enablePan ) handleTouchMovePan( event );
  3972. }
  3973. function handleTouchMoveDollyRotate( event ) {
  3974. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  3975. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  3976. }
  3977. //
  3978. // event handlers - FSM: listen for events and reset state
  3979. //
  3980. function onPointerDown( event ) {
  3981. if ( scope.enabled === false ) return;
  3982. if ( pointers.length === 0 ) {
  3983. scope.domElement.setPointerCapture( event.pointerId );
  3984. scope.domElement.addEventListener( 'pointermove', onPointerMove );
  3985. scope.domElement.addEventListener( 'pointerup', onPointerUp );
  3986. }
  3987. //
  3988. addPointer( event );
  3989. if ( event.pointerType === 'touch' ) {
  3990. onTouchStart( event );
  3991. } else {
  3992. onMouseDown( event );
  3993. }
  3994. }
  3995. function onPointerMove( event ) {
  3996. if ( scope.enabled === false ) return;
  3997. if ( event.pointerType === 'touch' ) {
  3998. onTouchMove( event );
  3999. } else {
  4000. onMouseMove( event );
  4001. }
  4002. }
  4003. function onPointerUp( event ) {
  4004. removePointer( event );
  4005. if ( pointers.length === 0 ) {
  4006. scope.domElement.releasePointerCapture( event.pointerId );
  4007. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  4008. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  4009. }
  4010. scope.dispatchEvent( _endEvent );
  4011. state = STATE.NONE;
  4012. }
  4013. function onMouseDown( event ) {
  4014. let mouseAction;
  4015. switch ( event.button ) {
  4016. case 0:
  4017. mouseAction = scope.mouseButtons.LEFT;
  4018. break;
  4019. case 1:
  4020. mouseAction = scope.mouseButtons.MIDDLE;
  4021. break;
  4022. case 2:
  4023. mouseAction = scope.mouseButtons.RIGHT;
  4024. break;
  4025. default:
  4026. mouseAction = - 1;
  4027. }
  4028. switch ( mouseAction ) {
  4029. case MOUSE.DOLLY:
  4030. if ( scope.enableZoom === false ) return;
  4031. handleMouseDownDolly( event );
  4032. state = STATE.DOLLY;
  4033. break;
  4034. case MOUSE.ROTATE:
  4035. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  4036. if ( scope.enablePan === false ) return;
  4037. handleMouseDownPan( event );
  4038. state = STATE.PAN;
  4039. } else {
  4040. if ( scope.enableRotate === false ) return;
  4041. handleMouseDownRotate( event );
  4042. state = STATE.ROTATE;
  4043. }
  4044. break;
  4045. case MOUSE.PAN:
  4046. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  4047. if ( scope.enableRotate === false ) return;
  4048. handleMouseDownRotate( event );
  4049. state = STATE.ROTATE;
  4050. } else {
  4051. if ( scope.enablePan === false ) return;
  4052. handleMouseDownPan( event );
  4053. state = STATE.PAN;
  4054. }
  4055. break;
  4056. default:
  4057. state = STATE.NONE;
  4058. }
  4059. if ( state !== STATE.NONE ) {
  4060. scope.dispatchEvent( _startEvent );
  4061. }
  4062. }
  4063. function onMouseMove( event ) {
  4064. switch ( state ) {
  4065. case STATE.ROTATE:
  4066. if ( scope.enableRotate === false ) return;
  4067. handleMouseMoveRotate( event );
  4068. break;
  4069. case STATE.DOLLY:
  4070. if ( scope.enableZoom === false ) return;
  4071. handleMouseMoveDolly( event );
  4072. break;
  4073. case STATE.PAN:
  4074. if ( scope.enablePan === false ) return;
  4075. handleMouseMovePan( event );
  4076. break;
  4077. }
  4078. }
  4079. function onMouseWheel( event ) {
  4080. if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
  4081. event.preventDefault();
  4082. scope.dispatchEvent( _startEvent );
  4083. handleMouseWheel( event );
  4084. scope.dispatchEvent( _endEvent );
  4085. }
  4086. function onKeyDown( event ) {
  4087. if ( scope.enabled === false || scope.enablePan === false ) return;
  4088. handleKeyDown( event );
  4089. }
  4090. function onTouchStart( event ) {
  4091. trackPointer( event );
  4092. switch ( pointers.length ) {
  4093. case 1:
  4094. switch ( scope.touches.ONE ) {
  4095. case TOUCH.ROTATE:
  4096. if ( scope.enableRotate === false ) return;
  4097. handleTouchStartRotate();
  4098. state = STATE.TOUCH_ROTATE;
  4099. break;
  4100. case TOUCH.PAN:
  4101. if ( scope.enablePan === false ) return;
  4102. handleTouchStartPan();
  4103. state = STATE.TOUCH_PAN;
  4104. break;
  4105. default:
  4106. state = STATE.NONE;
  4107. }
  4108. break;
  4109. case 2:
  4110. switch ( scope.touches.TWO ) {
  4111. case TOUCH.DOLLY_PAN:
  4112. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  4113. handleTouchStartDollyPan();
  4114. state = STATE.TOUCH_DOLLY_PAN;
  4115. break;
  4116. case TOUCH.DOLLY_ROTATE:
  4117. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  4118. handleTouchStartDollyRotate();
  4119. state = STATE.TOUCH_DOLLY_ROTATE;
  4120. break;
  4121. default:
  4122. state = STATE.NONE;
  4123. }
  4124. break;
  4125. default:
  4126. state = STATE.NONE;
  4127. }
  4128. if ( state !== STATE.NONE ) {
  4129. scope.dispatchEvent( _startEvent );
  4130. }
  4131. }
  4132. function onTouchMove( event ) {
  4133. trackPointer( event );
  4134. switch ( state ) {
  4135. case STATE.TOUCH_ROTATE:
  4136. if ( scope.enableRotate === false ) return;
  4137. handleTouchMoveRotate( event );
  4138. scope.update();
  4139. break;
  4140. case STATE.TOUCH_PAN:
  4141. if ( scope.enablePan === false ) return;
  4142. handleTouchMovePan( event );
  4143. scope.update();
  4144. break;
  4145. case STATE.TOUCH_DOLLY_PAN:
  4146. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  4147. handleTouchMoveDollyPan( event );
  4148. scope.update();
  4149. break;
  4150. case STATE.TOUCH_DOLLY_ROTATE:
  4151. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  4152. handleTouchMoveDollyRotate( event );
  4153. scope.update();
  4154. break;
  4155. default:
  4156. state = STATE.NONE;
  4157. }
  4158. }
  4159. function onContextMenu( event ) {
  4160. if ( scope.enabled === false ) return;
  4161. event.preventDefault();
  4162. }
  4163. function addPointer( event ) {
  4164. pointers.push( event );
  4165. }
  4166. function removePointer( event ) {
  4167. delete pointerPositions[event.pointerId];
  4168. for ( let i = 0; i < pointers.length; i ++ ) {
  4169. if ( pointers[i].pointerId == event.pointerId ) {
  4170. pointers.splice( i, 1 );
  4171. return;
  4172. }
  4173. }
  4174. }
  4175. function trackPointer( event ) {
  4176. let position = pointerPositions[event.pointerId];
  4177. if ( position === undefined ) {
  4178. position = new Vector2();
  4179. pointerPositions[event.pointerId] = position;
  4180. }
  4181. position.set( event.pageX, event.pageY );
  4182. }
  4183. function getSecondPointerPosition( event ) {
  4184. const pointer = ( event.pointerId === pointers[0].pointerId ) ? pointers[1] : pointers[0];
  4185. return pointerPositions[pointer.pointerId];
  4186. }
  4187. //
  4188. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  4189. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  4190. scope.domElement.addEventListener( 'pointercancel', onPointerUp );
  4191. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  4192. // force an update at start
  4193. this.update();
  4194. }
  4195. }
  4196. const fadeElement = (element, out, displayStyle, duration, onComplete) => {
  4197. const startTime = performance.now();
  4198. let startOpacity = element.style.display === 'none' ? 0 : parseFloat(element.style.opacity);
  4199. if (isNaN(startOpacity)) startOpacity = 1;
  4200. const interval = window.setInterval(() => {
  4201. const currentTime = performance.now();
  4202. const elapsed = currentTime - startTime;
  4203. let t = Math.min(elapsed / duration, 1.0);
  4204. if (t > 0.999) t = 1;
  4205. let opacity;
  4206. if (out) {
  4207. opacity = (1.0 - t) * startOpacity;
  4208. if (opacity < 0.0001) opacity = 0;
  4209. } else {
  4210. opacity = (1.0 - startOpacity) * t + startOpacity;
  4211. }
  4212. if (opacity > 0) {
  4213. element.style.display = displayStyle;
  4214. element.style.opacity = opacity;
  4215. } else {
  4216. element.style.display = 'none';
  4217. }
  4218. if (t >= 1) {
  4219. if (onComplete) onComplete();
  4220. window.clearInterval(interval);
  4221. }
  4222. }, 16);
  4223. return interval;
  4224. };
  4225. const cancelFade = (interval) => {
  4226. window.clearInterval(interval);
  4227. };
  4228. const STANDARD_FADE_DURATION = 500;
  4229. class LoadingSpinner {
  4230. static elementIDGen = 0;
  4231. constructor(message, container) {
  4232. this.taskIDGen = 0;
  4233. this.elementID = LoadingSpinner.elementIDGen++;
  4234. this.tasks = [];
  4235. this.message = message || 'Loading...';
  4236. this.container = container || document.body;
  4237. this.spinnerContainerOuter = document.createElement('div');
  4238. this.spinnerContainerOuter.className = `spinnerOuterContainer${this.elementID}`;
  4239. this.spinnerContainerOuter.style.display = 'none';
  4240. this.spinnerContainerPrimary = document.createElement('div');
  4241. this.spinnerContainerPrimary.className = `spinnerContainerPrimary${this.elementID}`;
  4242. this.spinnerPrimary = document.createElement('div');
  4243. this.spinnerPrimary.classList.add(`spinner${this.elementID}`, `spinnerPrimary${this.elementID}`);
  4244. this.messageContainerPrimary = document.createElement('div');
  4245. this.messageContainerPrimary.classList.add(`messageContainer${this.elementID}`, `messageContainerPrimary${this.elementID}`);
  4246. this.messageContainerPrimary.innerHTML = this.message;
  4247. this.spinnerContainerMin = document.createElement('div');
  4248. this.spinnerContainerMin.className = `spinnerContainerMin${this.elementID}`;
  4249. this.spinnerMin = document.createElement('div');
  4250. this.spinnerMin.classList.add(`spinner${this.elementID}`, `spinnerMin${this.elementID}`);
  4251. this.messageContainerMin = document.createElement('div');
  4252. this.messageContainerMin.classList.add(`messageContainer${this.elementID}`, `messageContainerMin${this.elementID}`);
  4253. this.messageContainerMin.innerHTML = this.message;
  4254. this.spinnerContainerPrimary.appendChild(this.spinnerPrimary);
  4255. this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary);
  4256. this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary);
  4257. this.spinnerContainerMin.appendChild(this.spinnerMin);
  4258. this.spinnerContainerMin.appendChild(this.messageContainerMin);
  4259. this.spinnerContainerOuter.appendChild(this.spinnerContainerMin);
  4260. const style = document.createElement('style');
  4261. style.innerHTML = `
  4262. .spinnerOuterContainer${this.elementID} {
  4263. width: 100%;
  4264. height: 100%;
  4265. margin: 0;
  4266. top: 0;
  4267. left: 0;
  4268. position: absolute;
  4269. pointer-events: none;
  4270. }
  4271. .messageContainer${this.elementID} {
  4272. height: 20px;
  4273. font-family: arial;
  4274. font-size: 12pt;
  4275. color: #ffffff;
  4276. text-align: center;
  4277. vertical-align: middle;
  4278. }
  4279. .spinner${this.elementID} {
  4280. padding: 15px;
  4281. background: #07e8d6;
  4282. z-index:99999;
  4283. aspect-ratio: 1;
  4284. border-radius: 50%;
  4285. --_m:
  4286. conic-gradient(#0000,#000),
  4287. linear-gradient(#000 0 0) content-box;
  4288. -webkit-mask: var(--_m);
  4289. mask: var(--_m);
  4290. -webkit-mask-composite: source-out;
  4291. mask-composite: subtract;
  4292. box-sizing: border-box;
  4293. animation: load 1s linear infinite;
  4294. }
  4295. .spinnerContainerPrimary${this.elementID} {
  4296. z-index:99999;
  4297. background-color: rgba(128, 128, 128, 0.75);
  4298. border: #666666 1px solid;
  4299. border-radius: 5px;
  4300. padding-top: 20px;
  4301. padding-bottom: 10px;
  4302. margin: 0;
  4303. position: absolute;
  4304. top: 50%;
  4305. left: 50%;
  4306. transform: translate(-80px, -80px);
  4307. width: 180px;
  4308. pointer-events: auto;
  4309. }
  4310. .spinnerPrimary${this.elementID} {
  4311. width: 120px;
  4312. margin-left: 30px;
  4313. }
  4314. .messageContainerPrimary${this.elementID} {
  4315. padding-top: 15px;
  4316. }
  4317. .spinnerContainerMin${this.elementID} {
  4318. z-index:99999;
  4319. background-color: rgba(128, 128, 128, 0.75);
  4320. border: #666666 1px solid;
  4321. border-radius: 5px;
  4322. padding-top: 20px;
  4323. padding-bottom: 15px;
  4324. margin: 0;
  4325. position: absolute;
  4326. bottom: 50px;
  4327. left: 50%;
  4328. transform: translate(-50%, 0);
  4329. display: flex;
  4330. flex-direction: left;
  4331. pointer-events: auto;
  4332. min-width: 250px;
  4333. }
  4334. .messageContainerMin${this.elementID} {
  4335. margin-right: 15px;
  4336. }
  4337. .spinnerMin${this.elementID} {
  4338. width: 50px;
  4339. height: 50px;
  4340. margin-left: 15px;
  4341. margin-right: 25px;
  4342. }
  4343. .messageContainerMin${this.elementID} {
  4344. padding-top: 15px;
  4345. }
  4346. @keyframes load {
  4347. to{transform: rotate(1turn)}
  4348. }
  4349. `;
  4350. this.spinnerContainerOuter.appendChild(style);
  4351. this.container.appendChild(this.spinnerContainerOuter);
  4352. this.setMinimized(false, true);
  4353. this.fadeTransitions = [];
  4354. }
  4355. addTask(message) {
  4356. const newTask = {
  4357. 'message': message,
  4358. 'id': this.taskIDGen++
  4359. };
  4360. this.tasks.push(newTask);
  4361. this.update();
  4362. return newTask.id;
  4363. }
  4364. removeTask(id) {
  4365. let index = 0;
  4366. for (let task of this.tasks) {
  4367. if (task.id === id) {
  4368. this.tasks.splice(index, 1);
  4369. break;
  4370. }
  4371. index++;
  4372. }
  4373. this.update();
  4374. }
  4375. removeAllTasks() {
  4376. this.tasks = [];
  4377. this.update();
  4378. }
  4379. setMessageForTask(id, message) {
  4380. for (let task of this.tasks) {
  4381. if (task.id === id) {
  4382. task.message = message;
  4383. break;
  4384. }
  4385. }
  4386. this.update();
  4387. }
  4388. update() {
  4389. if (this.tasks.length > 0) {
  4390. this.show();
  4391. this.setMessage(this.tasks[this.tasks.length - 1].message);
  4392. } else {
  4393. this.hide();
  4394. }
  4395. }
  4396. show() {
  4397. this.spinnerContainerOuter.style.display = 'block';
  4398. this.visible = true;
  4399. }
  4400. hide() {
  4401. this.spinnerContainerOuter.style.display = 'none';
  4402. this.visible = false;
  4403. }
  4404. setContainer(container) {
  4405. if (this.container && this.spinnerContainerOuter.parentElement === this.container) {
  4406. this.container.removeChild(this.spinnerContainerOuter);
  4407. }
  4408. if (container) {
  4409. this.container = container;
  4410. this.container.appendChild(this.spinnerContainerOuter);
  4411. this.spinnerContainerOuter.style.zIndex = this.container.style.zIndex + 1;
  4412. }
  4413. }
  4414. setMinimized(minimized, instant) {
  4415. const showHideSpinner = (element, show, instant, displayStyle, fadeTransitionsIndex) => {
  4416. if (instant) {
  4417. element.style.display = show ? displayStyle : 'none';
  4418. } else {
  4419. this.fadeTransitions[fadeTransitionsIndex] = fadeElement(element, !show, displayStyle, STANDARD_FADE_DURATION, () => {
  4420. this.fadeTransitions[fadeTransitionsIndex] = null;
  4421. });
  4422. }
  4423. };
  4424. showHideSpinner(this.spinnerContainerPrimary, !minimized, instant, 'block', 0);
  4425. showHideSpinner(this.spinnerContainerMin, minimized, instant, 'flex', 1);
  4426. this.minimized = minimized;
  4427. }
  4428. setMessage(msg) {
  4429. this.messageContainerPrimary.innerHTML = msg;
  4430. this.messageContainerMin.innerHTML = msg;
  4431. }
  4432. }
  4433. class LoadingProgressBar {
  4434. constructor(container) {
  4435. this.idGen = 0;
  4436. this.tasks = [];
  4437. this.container = container || document.body;
  4438. this.progressBarContainerOuter = document.createElement('div');
  4439. this.progressBarContainerOuter.className = 'progressBarOuterContainer';
  4440. this.progressBarContainerOuter.style.display = 'none';
  4441. this.progressBarBox = document.createElement('div');
  4442. this.progressBarBox.className = 'progressBarBox';
  4443. this.progressBarBackground = document.createElement('div');
  4444. this.progressBarBackground.className = 'progressBarBackground';
  4445. this.progressBar = document.createElement('div');
  4446. this.progressBar.className = 'progressBar';
  4447. this.progressBarBackground.appendChild(this.progressBar);
  4448. this.progressBarBox.appendChild(this.progressBarBackground);
  4449. this.progressBarContainerOuter.appendChild(this.progressBarBox);
  4450. const style = document.createElement('style');
  4451. style.innerHTML = `
  4452. .progressBarOuterContainer {
  4453. width: 100%;
  4454. height: 100%;
  4455. margin: 0;
  4456. top: 0;
  4457. left: 0;
  4458. position: absolute;
  4459. pointer-events: none;
  4460. }
  4461. .progressBarBox {
  4462. z-index:99999;
  4463. padding: 7px 9px 5px 7px;
  4464. background-color: rgba(190, 190, 190, 0.75);
  4465. border: #555555 1px solid;
  4466. border-radius: 15px;
  4467. margin: 0;
  4468. position: absolute;
  4469. bottom: 50px;
  4470. left: 50%;
  4471. transform: translate(-50%, 0);
  4472. width: 180px;
  4473. height: 30px;
  4474. pointer-events: auto;
  4475. }
  4476. .progressBarBackground {
  4477. width: 100%;
  4478. height: 25px;
  4479. border-radius:10px;
  4480. background-color: rgba(128, 128, 128, 0.75);
  4481. border: #444444 1px solid;
  4482. box-shadow: inset 0 0 10px #333333;
  4483. }
  4484. .progressBar {
  4485. height: 25px;
  4486. width: 0px;
  4487. border-radius:10px;
  4488. background-color: rgba(0, 200, 0, 0.75);
  4489. box-shadow: inset 0 0 10px #003300;
  4490. }
  4491. `;
  4492. this.progressBarContainerOuter.appendChild(style);
  4493. this.container.appendChild(this.progressBarContainerOuter);
  4494. }
  4495. show() {
  4496. this.progressBarContainerOuter.style.display = 'block';
  4497. }
  4498. hide() {
  4499. this.progressBarContainerOuter.style.display = 'none';
  4500. }
  4501. setProgress(progress) {
  4502. this.progressBar.style.width = progress + '%';
  4503. }
  4504. setContainer(container) {
  4505. if (this.container && this.progressBarContainerOuter.parentElement === this.container) {
  4506. this.container.removeChild(this.progressBarContainerOuter);
  4507. }
  4508. if (container) {
  4509. this.container = container;
  4510. this.container.appendChild(this.progressBarContainerOuter);
  4511. this.progressBarContainerOuter.style.zIndex = this.container.style.zIndex + 1;
  4512. }
  4513. }
  4514. }
  4515. class InfoPanel {
  4516. constructor(container) {
  4517. this.container = container || document.body;
  4518. this.infoCells = {};
  4519. const layout = [
  4520. ['Camera position', 'cameraPosition'],
  4521. ['Camera look-at', 'cameraLookAt'],
  4522. ['Camera up', 'cameraUp'],
  4523. ['Camera mode', 'orthographicCamera'],
  4524. ['Cursor position', 'cursorPosition'],
  4525. ['FPS', 'fps'],
  4526. ['Rendering:', 'renderSplatCount'],
  4527. ['Sort time', 'sortTime'],
  4528. ['Render window', 'renderWindow'],
  4529. ['Focal adjustment', 'focalAdjustment'],
  4530. ['Splat scale', 'splatScale'],
  4531. ['Point cloud mode', 'pointCloudMode']
  4532. ];
  4533. this.infoPanelContainer = document.createElement('div');
  4534. const style = document.createElement('style');
  4535. style.innerHTML = `
  4536. .infoPanel {
  4537. width: 430px;
  4538. padding: 10px;
  4539. background-color: rgba(50, 50, 50, 0.85);
  4540. border: #555555 2px solid;
  4541. color: #dddddd;
  4542. border-radius: 10px;
  4543. z-index: 9999;
  4544. font-family: arial;
  4545. font-size: 11pt;
  4546. text-align: left;
  4547. margin: 0;
  4548. top: 10px;
  4549. left:10px;
  4550. position: absolute;
  4551. pointer-events: auto;
  4552. }
  4553. .info-panel-cell {
  4554. margin-bottom: 5px;
  4555. padding-bottom: 2px;
  4556. }
  4557. .label-cell {
  4558. font-weight: bold;
  4559. font-size: 12pt;
  4560. width: 140px;
  4561. }
  4562. `;
  4563. this.infoPanelContainer.append(style);
  4564. this.infoPanel = document.createElement('div');
  4565. this.infoPanel.className = 'infoPanel';
  4566. const infoTable = document.createElement('div');
  4567. infoTable.style.display = 'table';
  4568. for (let layoutEntry of layout) {
  4569. const row = document.createElement('div');
  4570. row.style.display = 'table-row';
  4571. row.className = 'info-panel-row';
  4572. const labelCell = document.createElement('div');
  4573. labelCell.style.display = 'table-cell';
  4574. labelCell.innerHTML = `${layoutEntry[0]}: `;
  4575. labelCell.classList.add('info-panel-cell', 'label-cell');
  4576. const spacerCell = document.createElement('div');
  4577. spacerCell.style.display = 'table-cell';
  4578. spacerCell.style.width = '10px';
  4579. spacerCell.innerHTML = ' ';
  4580. spacerCell.className = 'info-panel-cell';
  4581. const infoCell = document.createElement('div');
  4582. infoCell.style.display = 'table-cell';
  4583. infoCell.innerHTML = '';
  4584. infoCell.className = 'info-panel-cell';
  4585. this.infoCells[layoutEntry[1]] = infoCell;
  4586. row.appendChild(labelCell);
  4587. row.appendChild(spacerCell);
  4588. row.appendChild(infoCell);
  4589. infoTable.appendChild(row);
  4590. }
  4591. this.infoPanel.appendChild(infoTable);
  4592. this.infoPanelContainer.append(this.infoPanel);
  4593. this.infoPanelContainer.style.display = 'none';
  4594. this.container.appendChild(this.infoPanelContainer);
  4595. this.visible = false;
  4596. }
  4597. update = function(renderDimensions, cameraPosition, cameraLookAtPosition, cameraUp, orthographicCamera,
  4598. meshCursorPosition, currentFPS, splatCount, splatRenderCount,
  4599. splatRenderCountPct, lastSortTime, focalAdjustment, splatScale, pointCloudMode) {
  4600. const cameraPosString = `${cameraPosition.x.toFixed(5)}, ${cameraPosition.y.toFixed(5)}, ${cameraPosition.z.toFixed(5)}`;
  4601. if (this.infoCells.cameraPosition.innerHTML !== cameraPosString) {
  4602. this.infoCells.cameraPosition.innerHTML = cameraPosString;
  4603. }
  4604. if (cameraLookAtPosition) {
  4605. const cla = cameraLookAtPosition;
  4606. const cameraLookAtString = `${cla.x.toFixed(5)}, ${cla.y.toFixed(5)}, ${cla.z.toFixed(5)}`;
  4607. if (this.infoCells.cameraLookAt.innerHTML !== cameraLookAtString) {
  4608. this.infoCells.cameraLookAt.innerHTML = cameraLookAtString;
  4609. }
  4610. }
  4611. const cameraUpString = `${cameraUp.x.toFixed(5)}, ${cameraUp.y.toFixed(5)}, ${cameraUp.z.toFixed(5)}`;
  4612. if (this.infoCells.cameraUp.innerHTML !== cameraUpString) {
  4613. this.infoCells.cameraUp.innerHTML = cameraUpString;
  4614. }
  4615. this.infoCells.orthographicCamera.innerHTML = orthographicCamera ? 'Orthographic' : 'Perspective';
  4616. if (meshCursorPosition) {
  4617. const cursPos = meshCursorPosition;
  4618. const cursorPosString = `${cursPos.x.toFixed(5)}, ${cursPos.y.toFixed(5)}, ${cursPos.z.toFixed(5)}`;
  4619. this.infoCells.cursorPosition.innerHTML = cursorPosString;
  4620. } else {
  4621. this.infoCells.cursorPosition.innerHTML = 'N/A';
  4622. }
  4623. this.infoCells.fps.innerHTML = currentFPS;
  4624. this.infoCells.renderWindow.innerHTML = `${renderDimensions.x} x ${renderDimensions.y}`;
  4625. this.infoCells.renderSplatCount.innerHTML =
  4626. `${splatRenderCount} splats out of ${splatCount} (${splatRenderCountPct.toFixed(2)}%)`;
  4627. this.infoCells.sortTime.innerHTML = `${lastSortTime.toFixed(3)} ms`;
  4628. this.infoCells.focalAdjustment.innerHTML = `${focalAdjustment.toFixed(3)}`;
  4629. this.infoCells.splatScale.innerHTML = `${splatScale.toFixed(3)}`;
  4630. this.infoCells.pointCloudMode.innerHTML = `${pointCloudMode}`;
  4631. };
  4632. setContainer(container) {
  4633. if (this.container && this.infoPanelContainer.parentElement === this.container) {
  4634. this.container.removeChild(this.infoPanelContainer);
  4635. }
  4636. if (container) {
  4637. this.container = container;
  4638. this.container.appendChild(this.infoPanelContainer);
  4639. this.infoPanelContainer.style.zIndex = this.container.style.zIndex + 1;
  4640. }
  4641. }
  4642. show() {
  4643. this.infoPanelContainer.style.display = 'block';
  4644. this.visible = true;
  4645. }
  4646. hide() {
  4647. this.infoPanelContainer.style.display = 'none';
  4648. this.visible = false;
  4649. }
  4650. }
  4651. class ArrowHelper extends THREE.Object3D {
  4652. constructor(dir = new THREE.Vector3(0, 0, 1), origin = new THREE.Vector3(0, 0, 0), length = 1,
  4653. radius = 0.1, color = 0xffff00, headLength = length * 0.2, headRadius = headLength * 0.2) {
  4654. super();
  4655. this.type = 'ArrowHelper';
  4656. const lineGeometry = new THREE.CylinderGeometry(radius, radius, length, 32);
  4657. lineGeometry.translate(0, length / 2.0, 0);
  4658. const coneGeometry = new THREE.CylinderGeometry( 0, headRadius, headLength, 32);
  4659. coneGeometry.translate(0, length, 0);
  4660. this.position.copy( origin );
  4661. this.line = new THREE.Mesh(lineGeometry, new THREE.MeshBasicMaterial({color: color, toneMapped: false}));
  4662. this.line.matrixAutoUpdate = false;
  4663. this.add(this.line);
  4664. this.cone = new THREE.Mesh(coneGeometry, new THREE.MeshBasicMaterial({color: color, toneMapped: false}));
  4665. this.cone.matrixAutoUpdate = false;
  4666. this.add(this.cone);
  4667. this.setDirection(dir);
  4668. }
  4669. setDirection( dir ) {
  4670. if (dir.y > 0.99999) {
  4671. this.quaternion.set(0, 0, 0, 1);
  4672. } else if (dir.y < - 0.99999) {
  4673. this.quaternion.set(1, 0, 0, 0);
  4674. } else {
  4675. _axis.set(dir.z, 0, -dir.x).normalize();
  4676. const radians = Math.acos(dir.y);
  4677. this.quaternion.setFromAxisAngle(_axis, radians);
  4678. }
  4679. }
  4680. setColor( color ) {
  4681. this.line.material.color.set(color);
  4682. this.cone.material.color.set(color);
  4683. }
  4684. copy(source) {
  4685. super.copy(source, false);
  4686. this.line.copy(source.line);
  4687. this.cone.copy(source.cone);
  4688. return this;
  4689. }
  4690. dispose() {
  4691. this.line.geometry.dispose();
  4692. this.line.material.dispose();
  4693. this.cone.geometry.dispose();
  4694. this.cone.material.dispose();
  4695. }
  4696. }
  4697. class SceneHelper {
  4698. constructor(threeScene) {
  4699. this.threeScene = threeScene;
  4700. this.splatRenderTarget = null;
  4701. this.renderTargetCopyQuad = null;
  4702. this.renderTargetCopyCamera = null;
  4703. this.meshCursor = null;
  4704. this.focusMarker = null;
  4705. this.controlPlane = null;
  4706. this.debugRoot = null;
  4707. this.secondaryDebugRoot = null;
  4708. }
  4709. updateSplatRenderTargetForRenderDimensions(width, height) {
  4710. this.destroySplatRendertarget();
  4711. this.splatRenderTarget = new THREE.WebGLRenderTarget(width, height, {
  4712. format: THREE.RGBAFormat,
  4713. stencilBuffer: false,
  4714. depthBuffer: true,
  4715. });
  4716. this.splatRenderTarget.depthTexture = new THREE.DepthTexture(width, height);
  4717. this.splatRenderTarget.depthTexture.format = THREE.DepthFormat;
  4718. this.splatRenderTarget.depthTexture.type = THREE.UnsignedIntType;
  4719. }
  4720. destroySplatRendertarget() {
  4721. if (this.splatRenderTarget) {
  4722. this.splatRenderTarget = null;
  4723. }
  4724. }
  4725. setupRenderTargetCopyObjects() {
  4726. const uniforms = {
  4727. 'sourceColorTexture': {
  4728. 'type': 't',
  4729. 'value': null
  4730. },
  4731. 'sourceDepthTexture': {
  4732. 'type': 't',
  4733. 'value': null
  4734. },
  4735. };
  4736. const renderTargetCopyMaterial = new THREE.ShaderMaterial({
  4737. vertexShader: `
  4738. varying vec2 vUv;
  4739. void main() {
  4740. vUv = uv;
  4741. gl_Position = vec4( position.xy, 0.0, 1.0 );
  4742. }
  4743. `,
  4744. fragmentShader: `
  4745. #include <common>
  4746. #include <packing>
  4747. varying vec2 vUv;
  4748. uniform sampler2D sourceColorTexture;
  4749. uniform sampler2D sourceDepthTexture;
  4750. void main() {
  4751. vec4 color = texture2D(sourceColorTexture, vUv);
  4752. float fragDepth = texture2D(sourceDepthTexture, vUv).x;
  4753. gl_FragDepth = fragDepth;
  4754. gl_FragColor = vec4(color.rgb, color.a * 2.0);
  4755. }
  4756. `,
  4757. uniforms: uniforms,
  4758. depthWrite: false,
  4759. depthTest: false,
  4760. transparent: true,
  4761. blending: THREE.CustomBlending,
  4762. blendSrc: THREE.SrcAlphaFactor,
  4763. blendSrcAlpha: THREE.SrcAlphaFactor,
  4764. blendDst: THREE.OneMinusSrcAlphaFactor,
  4765. blendDstAlpha: THREE.OneMinusSrcAlphaFactor
  4766. });
  4767. renderTargetCopyMaterial.extensions.fragDepth = true;
  4768. this.renderTargetCopyQuad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), renderTargetCopyMaterial);
  4769. this.renderTargetCopyCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  4770. }
  4771. destroyRenderTargetCopyObjects() {
  4772. if (this.renderTargetCopyQuad) {
  4773. disposeAllMeshes(this.renderTargetCopyQuad);
  4774. this.renderTargetCopyQuad = null;
  4775. }
  4776. }
  4777. setupMeshCursor() {
  4778. if (!this.meshCursor) {
  4779. const coneGeometry = new THREE.ConeGeometry(0.5, 1.5, 32);
  4780. const coneMaterial = new THREE.MeshBasicMaterial({color: 0xFFFFFF});
  4781. const downArrow = new THREE.Mesh(coneGeometry, coneMaterial);
  4782. downArrow.rotation.set(0, 0, Math.PI);
  4783. downArrow.position.set(0, 1, 0);
  4784. const upArrow = new THREE.Mesh(coneGeometry, coneMaterial);
  4785. upArrow.position.set(0, -1, 0);
  4786. const leftArrow = new THREE.Mesh(coneGeometry, coneMaterial);
  4787. leftArrow.rotation.set(0, 0, Math.PI / 2.0);
  4788. leftArrow.position.set(1, 0, 0);
  4789. const rightArrow = new THREE.Mesh(coneGeometry, coneMaterial);
  4790. rightArrow.rotation.set(0, 0, -Math.PI / 2.0);
  4791. rightArrow.position.set(-1, 0, 0);
  4792. this.meshCursor = new THREE.Object3D();
  4793. this.meshCursor.add(downArrow);
  4794. this.meshCursor.add(upArrow);
  4795. this.meshCursor.add(leftArrow);
  4796. this.meshCursor.add(rightArrow);
  4797. this.meshCursor.scale.set(0.1, 0.1, 0.1);
  4798. this.threeScene.add(this.meshCursor);
  4799. this.meshCursor.visible = false;
  4800. }
  4801. }
  4802. destroyMeshCursor() {
  4803. if (this.meshCursor) {
  4804. disposeAllMeshes(this.meshCursor);
  4805. this.threeScene.remove(this.meshCursor);
  4806. this.meshCursor = null;
  4807. }
  4808. }
  4809. setMeshCursorVisibility(visible) {
  4810. this.meshCursor.visible = visible;
  4811. }
  4812. getMeschCursorVisibility() {
  4813. return this.meshCursor.visible;
  4814. }
  4815. setMeshCursorPosition(position) {
  4816. this.meshCursor.position.copy(position);
  4817. }
  4818. positionAndOrientMeshCursor(position, camera) {
  4819. this.meshCursor.position.copy(position);
  4820. this.meshCursor.up.copy(camera.up);
  4821. this.meshCursor.lookAt(camera.position);
  4822. }
  4823. setupFocusMarker() {
  4824. if (!this.focusMarker) {
  4825. const sphereGeometry = new THREE.SphereGeometry(.5, 32, 32);
  4826. const focusMarkerMaterial = SceneHelper.buildFocusMarkerMaterial();
  4827. focusMarkerMaterial.depthTest = false;
  4828. focusMarkerMaterial.depthWrite = false;
  4829. focusMarkerMaterial.transparent = true;
  4830. this.focusMarker = new THREE.Mesh(sphereGeometry, focusMarkerMaterial);
  4831. }
  4832. }
  4833. destroyFocusMarker() {
  4834. if (this.focusMarker) {
  4835. disposeAllMeshes(this.focusMarker);
  4836. this.focusMarker = null;
  4837. }
  4838. }
  4839. updateFocusMarker = function() {
  4840. const tempPosition = new THREE.Vector3();
  4841. const tempMatrix = new THREE.Matrix4();
  4842. const toCamera = new THREE.Vector3();
  4843. return function(position, camera, viewport) {
  4844. tempMatrix.copy(camera.matrixWorld).invert();
  4845. tempPosition.copy(position).applyMatrix4(tempMatrix);
  4846. tempPosition.normalize().multiplyScalar(10);
  4847. tempPosition.applyMatrix4(camera.matrixWorld);
  4848. toCamera.copy(camera.position).sub(position);
  4849. const toCameraDistance = toCamera.length();
  4850. this.focusMarker.position.copy(position);
  4851. this.focusMarker.scale.set(toCameraDistance, toCameraDistance, toCameraDistance);
  4852. this.focusMarker.material.uniforms.realFocusPosition.value.copy(position);
  4853. this.focusMarker.material.uniforms.viewport.value.copy(viewport);
  4854. this.focusMarker.material.uniformsNeedUpdate = true;
  4855. };
  4856. }();
  4857. setFocusMarkerVisibility(visible) {
  4858. this.focusMarker.visible = visible;
  4859. }
  4860. setFocusMarkerOpacity(opacity) {
  4861. this.focusMarker.material.uniforms.opacity.value = opacity;
  4862. this.focusMarker.material.uniformsNeedUpdate = true;
  4863. }
  4864. getFocusMarkerOpacity() {
  4865. return this.focusMarker.material.uniforms.opacity.value;
  4866. }
  4867. setupControlPlane() {
  4868. if (!this.controlPlane) {
  4869. const planeGeometry = new THREE.PlaneGeometry(1, 1);
  4870. planeGeometry.rotateX(-Math.PI / 2);
  4871. const planeMaterial = new THREE.MeshBasicMaterial({color: 0xffffff});
  4872. planeMaterial.transparent = true;
  4873. planeMaterial.opacity = 0.6;
  4874. planeMaterial.depthTest = false;
  4875. planeMaterial.depthWrite = false;
  4876. planeMaterial.side = THREE.DoubleSide;
  4877. const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);
  4878. const arrowDir = new THREE.Vector3(0, 1, 0);
  4879. arrowDir.normalize();
  4880. const arrowOrigin = new THREE.Vector3(0, 0, 0);
  4881. const arrowLength = 0.5;
  4882. const arrowRadius = 0.01;
  4883. const arrowColor = 0x00dd00;
  4884. const arrowHelper = new ArrowHelper(arrowDir, arrowOrigin, arrowLength, arrowRadius, arrowColor, 0.1, 0.03);
  4885. this.controlPlane = new THREE.Object3D();
  4886. this.controlPlane.add(planeMesh);
  4887. this.controlPlane.add(arrowHelper);
  4888. }
  4889. }
  4890. destroyControlPlane() {
  4891. if (this.controlPlane) {
  4892. disposeAllMeshes(this.controlPlane);
  4893. this.controlPlane = null;
  4894. }
  4895. }
  4896. setControlPlaneVisibility(visible) {
  4897. this.controlPlane.visible = visible;
  4898. }
  4899. positionAndOrientControlPlane = function() {
  4900. const tempQuaternion = new THREE.Quaternion();
  4901. const defaultUp = new THREE.Vector3(0, 1, 0);
  4902. return function(position, up) {
  4903. tempQuaternion.setFromUnitVectors(defaultUp, up);
  4904. this.controlPlane.position.copy(position);
  4905. this.controlPlane.quaternion.copy(tempQuaternion);
  4906. };
  4907. }();
  4908. addDebugMeshes() {
  4909. this.debugRoot = this.createDebugMeshes();
  4910. this.secondaryDebugRoot = this.createSecondaryDebugMeshes();
  4911. this.threeScene.add(this.debugRoot);
  4912. this.threeScene.add(this.secondaryDebugRoot);
  4913. }
  4914. destroyDebugMeshes() {
  4915. for (let debugRoot of [this.debugRoot, this.secondaryDebugRoot]) {
  4916. if (debugRoot) {
  4917. disposeAllMeshes(debugRoot);
  4918. this.threeScene.remove(debugRoot);
  4919. }
  4920. }
  4921. this.debugRoot = null;
  4922. this.secondaryDebugRoot = null;
  4923. }
  4924. createDebugMeshes(renderOrder) {
  4925. const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
  4926. const debugMeshRoot = new THREE.Object3D();
  4927. const createMesh = (color, position) => {
  4928. let sphereMesh = new THREE.Mesh(sphereGeometry, SceneHelper.buildDebugMaterial(color));
  4929. sphereMesh.renderOrder = renderOrder;
  4930. debugMeshRoot.add(sphereMesh);
  4931. sphereMesh.position.fromArray(position);
  4932. };
  4933. createMesh(0xff0000, [-50, 0, 0]);
  4934. createMesh(0xff0000, [50, 0, 0]);
  4935. createMesh(0x00ff00, [0, 0, -50]);
  4936. createMesh(0x00ff00, [0, 0, 50]);
  4937. createMesh(0xffaa00, [5, 0, 5]);
  4938. return debugMeshRoot;
  4939. }
  4940. createSecondaryDebugMeshes(renderOrder) {
  4941. const boxGeometry = new THREE.BoxGeometry(3, 3, 3);
  4942. const debugMeshRoot = new THREE.Object3D();
  4943. let boxColor = 0xBBBBBB;
  4944. const createMesh = (position) => {
  4945. let boxMesh = new THREE.Mesh(boxGeometry, SceneHelper.buildDebugMaterial(boxColor));
  4946. boxMesh.renderOrder = renderOrder;
  4947. debugMeshRoot.add(boxMesh);
  4948. boxMesh.position.fromArray(position);
  4949. };
  4950. let separation = 10;
  4951. createMesh([-separation, 0, -separation]);
  4952. createMesh([-separation, 0, separation]);
  4953. createMesh([separation, 0, -separation]);
  4954. createMesh([separation, 0, separation]);
  4955. return debugMeshRoot;
  4956. }
  4957. static buildDebugMaterial(color) {
  4958. const vertexShaderSource = `
  4959. #include <common>
  4960. varying float ndcDepth;
  4961. void main() {
  4962. gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);
  4963. ndcDepth = gl_Position.z / gl_Position.w;
  4964. gl_Position.x = gl_Position.x / gl_Position.w;
  4965. gl_Position.y = gl_Position.y / gl_Position.w;
  4966. gl_Position.z = 0.0;
  4967. gl_Position.w = 1.0;
  4968. }
  4969. `;
  4970. const fragmentShaderSource = `
  4971. #include <common>
  4972. uniform vec3 color;
  4973. varying float ndcDepth;
  4974. void main() {
  4975. gl_FragDepth = (ndcDepth + 1.0) / 2.0;
  4976. gl_FragColor = vec4(color.rgb, 0.0);
  4977. }
  4978. `;
  4979. const uniforms = {
  4980. 'color': {
  4981. 'type': 'v3',
  4982. 'value': new THREE.Color(color)
  4983. },
  4984. };
  4985. const material = new THREE.ShaderMaterial({
  4986. uniforms: uniforms,
  4987. vertexShader: vertexShaderSource,
  4988. fragmentShader: fragmentShaderSource,
  4989. transparent: false,
  4990. depthTest: true,
  4991. depthWrite: true,
  4992. side: THREE.FrontSide
  4993. });
  4994. material.extensions.fragDepth = true;
  4995. return material;
  4996. }
  4997. static buildFocusMarkerMaterial(color) {
  4998. const vertexShaderSource = `
  4999. #include <common>
  5000. uniform vec2 viewport;
  5001. uniform vec3 realFocusPosition;
  5002. varying vec4 ndcPosition;
  5003. varying vec4 ndcCenter;
  5004. varying vec4 ndcFocusPosition;
  5005. void main() {
  5006. float radius = 0.01;
  5007. vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);
  5008. vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);
  5009. vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);
  5010. ndcPosition = projectionMatrix * viewPosition;
  5011. ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);
  5012. ndcCenter = projectionMatrix * viewCenter;
  5013. ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);
  5014. ndcFocusPosition = projectionMatrix * viewFocusPosition;
  5015. ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);
  5016. gl_Position = projectionMatrix * viewPosition;
  5017. }
  5018. `;
  5019. const fragmentShaderSource = `
  5020. #include <common>
  5021. uniform vec3 color;
  5022. uniform vec2 viewport;
  5023. uniform float opacity;
  5024. varying vec4 ndcPosition;
  5025. varying vec4 ndcCenter;
  5026. varying vec4 ndcFocusPosition;
  5027. void main() {
  5028. vec2 screenPosition = vec2(ndcPosition) * viewport;
  5029. vec2 screenCenter = vec2(ndcCenter) * viewport;
  5030. vec2 screenVec = screenPosition - screenCenter;
  5031. float projectedRadius = length(screenVec);
  5032. float lineWidth = 0.0005 * viewport.y;
  5033. float aaRange = 0.0025 * viewport.y;
  5034. float radius = 0.06 * viewport.y;
  5035. float radDiff = abs(projectedRadius - radius) - lineWidth;
  5036. float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0);
  5037. gl_FragColor = vec4(color.rgb, alpha * opacity);
  5038. }
  5039. `;
  5040. const uniforms = {
  5041. 'color': {
  5042. 'type': 'v3',
  5043. 'value': new THREE.Color(color)
  5044. },
  5045. 'realFocusPosition': {
  5046. 'type': 'v3',
  5047. 'value': new THREE.Vector3()
  5048. },
  5049. 'viewport': {
  5050. 'type': 'v2',
  5051. 'value': new THREE.Vector2()
  5052. },
  5053. 'opacity': {
  5054. 'value': 0.0
  5055. }
  5056. };
  5057. const material = new THREE.ShaderMaterial({
  5058. uniforms: uniforms,
  5059. vertexShader: vertexShaderSource,
  5060. fragmentShader: fragmentShaderSource,
  5061. transparent: true,
  5062. depthTest: false,
  5063. depthWrite: false,
  5064. side: THREE.FrontSide
  5065. });
  5066. return material;
  5067. }
  5068. dispose() {
  5069. this.destroyMeshCursor();
  5070. this.destroyFocusMarker();
  5071. this.destroyDebugMeshes();
  5072. this.destroyControlPlane();
  5073. this.destroyRenderTargetCopyObjects();
  5074. this.destroySplatRendertarget();
  5075. }
  5076. }
  5077. const VectorRight = new THREE.Vector3(1, 0, 0);
  5078. const VectorUp = new THREE.Vector3(0, 1, 0);
  5079. const VectorBackward = new THREE.Vector3(0, 0, 1);
  5080. class Ray {
  5081. constructor(origin = new THREE.Vector3(), direction = new THREE.Vector3()) {
  5082. this.origin = new THREE.Vector3();
  5083. this.direction = new THREE.Vector3();
  5084. this.setParameters(origin, direction);
  5085. }
  5086. setParameters(origin, direction) {
  5087. this.origin.copy(origin);
  5088. this.direction.copy(direction).normalize();
  5089. }
  5090. boxContainsPoint(box, point, epsilon) {
  5091. return point.x < box.min.x - epsilon || point.x > box.max.x + epsilon ||
  5092. point.y < box.min.y - epsilon || point.y > box.max.y + epsilon ||
  5093. point.z < box.min.z - epsilon || point.z > box.max.z + epsilon ? false : true;
  5094. }
  5095. intersectBox = function() {
  5096. const planeIntersectionPoint = new THREE.Vector3();
  5097. const planeIntersectionPointArray = [];
  5098. const originArray = [];
  5099. const directionArray = [];
  5100. return function(box, outHit) {
  5101. originArray[0] = this.origin.x;
  5102. originArray[1] = this.origin.y;
  5103. originArray[2] = this.origin.z;
  5104. directionArray[0] = this.direction.x;
  5105. directionArray[1] = this.direction.y;
  5106. directionArray[2] = this.direction.z;
  5107. if (this.boxContainsPoint(box, this.origin, 0.0001)) {
  5108. if (outHit) {
  5109. outHit.origin.copy(this.origin);
  5110. outHit.normal.set(0, 0, 0);
  5111. outHit.distance = -1;
  5112. }
  5113. return true;
  5114. }
  5115. for (let i = 0; i < 3; i++) {
  5116. if (directionArray[i] == 0.0) continue;
  5117. const hitNormal = i == 0 ? VectorRight : i == 1 ? VectorUp : VectorBackward;
  5118. const extremeVec = directionArray[i] < 0 ? box.max : box.min;
  5119. let multiplier = -Math.sign(directionArray[i]);
  5120. planeIntersectionPointArray[0] = i == 0 ? extremeVec.x : i == 1 ? extremeVec.y : extremeVec.z;
  5121. let toSide = planeIntersectionPointArray[0] - originArray[i];
  5122. if (toSide * multiplier < 0) {
  5123. const idx1 = (i + 1) % 3;
  5124. const idx2 = (i + 2) % 3;
  5125. planeIntersectionPointArray[2] = directionArray[idx1] / directionArray[i] * toSide + originArray[idx1];
  5126. planeIntersectionPointArray[1] = directionArray[idx2] / directionArray[i] * toSide + originArray[idx2];
  5127. planeIntersectionPoint.set(planeIntersectionPointArray[i],
  5128. planeIntersectionPointArray[idx2],
  5129. planeIntersectionPointArray[idx1]);
  5130. if (this.boxContainsPoint(box, planeIntersectionPoint, 0.0001)) {
  5131. if (outHit) {
  5132. outHit.origin.copy(planeIntersectionPoint);
  5133. outHit.normal.copy(hitNormal).multiplyScalar(multiplier);
  5134. outHit.distance = planeIntersectionPoint.sub(this.origin).length();
  5135. }
  5136. return true;
  5137. }
  5138. }
  5139. }
  5140. return false;
  5141. };
  5142. }();
  5143. intersectSphere = function() {
  5144. const toSphereCenterVec = new THREE.Vector3();
  5145. return function(center, radius, outHit) {
  5146. toSphereCenterVec.copy(center).sub(this.origin);
  5147. const toClosestApproach = toSphereCenterVec.dot(this.direction);
  5148. const toClosestApproachSq = toClosestApproach * toClosestApproach;
  5149. const toSphereCenterSq = toSphereCenterVec.dot(toSphereCenterVec);
  5150. const diffSq = toSphereCenterSq - toClosestApproachSq;
  5151. const radiusSq = radius * radius;
  5152. if (diffSq > radiusSq) return false;
  5153. const thc = Math.sqrt(radiusSq - diffSq);
  5154. const t0 = toClosestApproach - thc;
  5155. const t1 = toClosestApproach + thc;
  5156. if (t1 < 0) return false;
  5157. let t = t0 < 0 ? t1 : t0;
  5158. if (outHit) {
  5159. outHit.origin.copy(this.origin).addScaledVector(this.direction, t);
  5160. outHit.normal.copy(outHit.origin).sub(center).normalize();
  5161. outHit.distance = t;
  5162. }
  5163. return true;
  5164. };
  5165. }();
  5166. }
  5167. class Hit {
  5168. constructor() {
  5169. this.origin = new THREE.Vector3();
  5170. this.normal = new THREE.Vector3();
  5171. this.distance = 0;
  5172. this.splatIndex = 0;
  5173. }
  5174. set(origin, normal, distance, splatIndex) {
  5175. this.origin.copy(origin);
  5176. this.normal.copy(normal);
  5177. this.distance = distance;
  5178. this.splatIndex = splatIndex;
  5179. }
  5180. clone() {
  5181. const hitClone = new Hit();
  5182. hitClone.origin.copy(this.origin);
  5183. hitClone.normal.copy(this.normal);
  5184. hitClone.distance = this.distance;
  5185. hitClone.splatIndex = this.splatIndex;
  5186. return hitClone;
  5187. }
  5188. }
  5189. const SplatRenderMode = {
  5190. ThreeD: 0,
  5191. TwoD: 1
  5192. };
  5193. class Raycaster {
  5194. constructor(origin, direction, raycastAgainstTrueSplatEllipsoid = false) {
  5195. this.ray = new Ray(origin, direction);
  5196. this.raycastAgainstTrueSplatEllipsoid = raycastAgainstTrueSplatEllipsoid;
  5197. }
  5198. setFromCameraAndScreenPosition = function() {
  5199. const ndcCoords = new THREE.Vector2();
  5200. return function(camera, screenPosition, screenDimensions) {
  5201. ndcCoords.x = screenPosition.x / screenDimensions.x * 2.0 - 1.0;
  5202. ndcCoords.y = (screenDimensions.y - screenPosition.y) / screenDimensions.y * 2.0 - 1.0;
  5203. if (camera.isPerspectiveCamera) {
  5204. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  5205. this.ray.direction.set(ndcCoords.x, ndcCoords.y, 0.5 ).unproject(camera).sub(this.ray.origin).normalize();
  5206. this.camera = camera;
  5207. } else if (camera.isOrthographicCamera) {
  5208. this.ray.origin.set(ndcCoords.x, ndcCoords.y,
  5209. (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera);
  5210. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  5211. this.camera = camera;
  5212. } else {
  5213. throw new Error('Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type');
  5214. }
  5215. };
  5216. }();
  5217. intersectSplatMesh = function() {
  5218. const toLocal = new THREE.Matrix4();
  5219. const fromLocal = new THREE.Matrix4();
  5220. const sceneTransform = new THREE.Matrix4();
  5221. const localRay = new Ray();
  5222. const tempPoint = new THREE.Vector3();
  5223. return function(splatMesh, outHits = []) {
  5224. const splatTree = splatMesh.getSplatTree();
  5225. if (!splatTree) return;
  5226. for (let s = 0; s < splatTree.subTrees.length; s++) {
  5227. const subTree = splatTree.subTrees[s];
  5228. fromLocal.copy(splatMesh.matrixWorld);
  5229. if (splatMesh.dynamicMode) {
  5230. splatMesh.getSceneTransform(s, sceneTransform);
  5231. fromLocal.multiply(sceneTransform);
  5232. }
  5233. toLocal.copy(fromLocal).invert();
  5234. localRay.origin.copy(this.ray.origin).applyMatrix4(toLocal);
  5235. localRay.direction.copy(this.ray.origin).add(this.ray.direction);
  5236. localRay.direction.applyMatrix4(toLocal).sub(localRay.origin).normalize();
  5237. const outHitsForSubTree = [];
  5238. if (subTree.rootNode) {
  5239. this.castRayAtSplatTreeNode(localRay, splatTree, subTree.rootNode, outHitsForSubTree);
  5240. }
  5241. outHitsForSubTree.forEach((hit) => {
  5242. hit.origin.applyMatrix4(fromLocal);
  5243. hit.normal.applyMatrix4(fromLocal).normalize();
  5244. hit.distance = tempPoint.copy(hit.origin).sub(this.ray.origin).length();
  5245. });
  5246. outHits.push(...outHitsForSubTree);
  5247. }
  5248. outHits.sort((a, b) => {
  5249. if (a.distance > b.distance) return 1;
  5250. else return -1;
  5251. });
  5252. return outHits;
  5253. };
  5254. }();
  5255. castRayAtSplatTreeNode = function() {
  5256. const tempColor = new THREE.Vector4();
  5257. const tempCenter = new THREE.Vector3();
  5258. const tempScale = new THREE.Vector3();
  5259. const tempRotation = new THREE.Quaternion();
  5260. const tempHit = new Hit();
  5261. const scaleEpsilon = 0.0000001;
  5262. const origin = new THREE.Vector3(0, 0, 0);
  5263. const uniformScaleMatrix = new THREE.Matrix4();
  5264. const scaleMatrix = new THREE.Matrix4();
  5265. const rotationMatrix = new THREE.Matrix4();
  5266. const toSphereSpace = new THREE.Matrix4();
  5267. const fromSphereSpace = new THREE.Matrix4();
  5268. const tempRay = new Ray();
  5269. return function(ray, splatTree, node, outHits = []) {
  5270. if (!ray.intersectBox(node.boundingBox)) {
  5271. return;
  5272. }
  5273. if (node.data && node.data.indexes && node.data.indexes.length > 0) {
  5274. for (let i = 0; i < node.data.indexes.length; i++) {
  5275. const splatGlobalIndex = node.data.indexes[i];
  5276. const splatSceneIndex = splatTree.splatMesh.getSceneIndexForSplat(splatGlobalIndex);
  5277. const splatScene = splatTree.splatMesh.getScene(splatSceneIndex);
  5278. if (!splatScene.visible) continue;
  5279. splatTree.splatMesh.getSplatColor(splatGlobalIndex, tempColor);
  5280. splatTree.splatMesh.getSplatCenter(splatGlobalIndex, tempCenter);
  5281. splatTree.splatMesh.getSplatScaleAndRotation(splatGlobalIndex, tempScale, tempRotation);
  5282. /* if (tempScale.x <= scaleEpsilon || tempScale.y <= scaleEpsilon ||
  5283. splatTree.splatMesh.splatRenderMode === SplatRenderMode.ThreeD && tempScale.z <= scaleEpsilon) {
  5284. continue;
  5285. } */ //xzw改。 不知道为何有一个模型dynamic时tempScale.是0。导致无法pick。所以这段先注释 (0829)
  5286. if (!this.raycastAgainstTrueSplatEllipsoid) {
  5287. let radius = (tempScale.x + tempScale.y);
  5288. let componentCount = 2;
  5289. if (splatTree.splatMesh.splatRenderMode === SplatRenderMode.ThreeD) {
  5290. radius += tempScale.z;
  5291. componentCount = 3;
  5292. }
  5293. radius = radius / componentCount;
  5294. if (ray.intersectSphere(tempCenter, radius, tempHit)) {
  5295. const hitClone = tempHit.clone();
  5296. hitClone.splatIndex = splatGlobalIndex;
  5297. outHits.push(hitClone);
  5298. }
  5299. } else {
  5300. scaleMatrix.makeScale(tempScale.x, tempScale.y, tempScale.z);
  5301. rotationMatrix.makeRotationFromQuaternion(tempRotation);
  5302. const uniformScale = Math.log10(tempColor.w) * 2.0;
  5303. uniformScaleMatrix.makeScale(uniformScale, uniformScale, uniformScale);
  5304. fromSphereSpace.copy(uniformScaleMatrix).multiply(rotationMatrix).multiply(scaleMatrix);
  5305. toSphereSpace.copy(fromSphereSpace).invert();
  5306. tempRay.origin.copy(ray.origin).sub(tempCenter).applyMatrix4(toSphereSpace);
  5307. tempRay.direction.copy(ray.origin).add(ray.direction).sub(tempCenter);
  5308. tempRay.direction.applyMatrix4(toSphereSpace).sub(tempRay.origin).normalize();
  5309. if (tempRay.intersectSphere(origin, 1.0, tempHit)) {
  5310. const hitClone = tempHit.clone();
  5311. hitClone.splatIndex = splatGlobalIndex;
  5312. hitClone.origin.applyMatrix4(fromSphereSpace).add(tempCenter);
  5313. outHits.push(hitClone);
  5314. }
  5315. }
  5316. }
  5317. }
  5318. if (node.children && node.children.length > 0) {
  5319. for (let child of node.children) {
  5320. this.castRayAtSplatTreeNode(ray, splatTree, child, outHits);
  5321. }
  5322. }
  5323. return outHits;
  5324. };
  5325. }();
  5326. }
  5327. class SplatMaterial {
  5328. static buildVertexShaderBase(dynamicMode = false, enableOptionalEffects = false, maxSphericalHarmonicsDegree = 0, customVars = '') {
  5329. let vertexShaderSource = `
  5330. precision highp float;
  5331. #include <common>
  5332. attribute uint splatIndex;
  5333. uniform highp usampler2D centersColorsTexture;
  5334. uniform highp sampler2D sphericalHarmonicsTexture;
  5335. uniform highp sampler2D sphericalHarmonicsTextureR;
  5336. uniform highp sampler2D sphericalHarmonicsTextureG;
  5337. uniform highp sampler2D sphericalHarmonicsTextureB;
  5338. uniform highp usampler2D sceneIndexesTexture;
  5339. uniform vec2 sceneIndexesTextureSize;
  5340. uniform int sceneCount;
  5341. `;
  5342. if (enableOptionalEffects) {
  5343. vertexShaderSource += `
  5344. uniform float sceneOpacity[${Constants.MaxScenes}];
  5345. uniform int sceneVisibility[${Constants.MaxScenes}];
  5346. `;
  5347. }
  5348. if (dynamicMode) {
  5349. vertexShaderSource += `
  5350. uniform highp mat4 transforms[${Constants.MaxScenes}];
  5351. `;
  5352. }
  5353. vertexShaderSource += `
  5354. ${customVars}
  5355. uniform vec2 focal;
  5356. uniform float orthoZoom;
  5357. uniform int orthographicMode;
  5358. uniform int pointCloudModeEnabled;
  5359. uniform float inverseFocalAdjustment;
  5360. uniform vec2 viewport;
  5361. uniform vec2 basisViewport;
  5362. uniform vec2 centersColorsTextureSize;
  5363. uniform int sphericalHarmonicsDegree;
  5364. uniform vec2 sphericalHarmonicsTextureSize;
  5365. uniform int sphericalHarmonics8BitMode;
  5366. uniform int sphericalHarmonicsMultiTextureMode;
  5367. uniform float visibleRegionRadius;
  5368. uniform float visibleRegionFadeStartRadius;
  5369. uniform float firstRenderTime;
  5370. uniform float currentTime;
  5371. uniform int fadeInComplete;
  5372. uniform vec3 sceneCenter;
  5373. uniform float splatScale;
  5374. uniform float sphericalHarmonics8BitCompressionRangeMin[${Constants.MaxScenes}];
  5375. uniform float sphericalHarmonics8BitCompressionRangeMax[${Constants.MaxScenes}];
  5376. varying vec4 vColor;
  5377. varying vec2 vUv;
  5378. varying vec2 vPosition;
  5379. mat3 quaternionToRotationMatrix(float x, float y, float z, float w) {
  5380. float s = 1.0 / sqrt(w * w + x * x + y * y + z * z);
  5381. return mat3(
  5382. 1. - 2. * (y * y + z * z),
  5383. 2. * (x * y + w * z),
  5384. 2. * (x * z - w * y),
  5385. 2. * (x * y - w * z),
  5386. 1. - 2. * (x * x + z * z),
  5387. 2. * (y * z + w * x),
  5388. 2. * (x * z + w * y),
  5389. 2. * (y * z - w * x),
  5390. 1. - 2. * (x * x + y * y)
  5391. );
  5392. }
  5393. const float sqrt8 = sqrt(8.0);
  5394. const float minAlpha = 1.0 / 255.0;
  5395. const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);
  5396. const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));
  5397. const uvec4 shift4 = uvec4(0, 8, 16, 24);
  5398. vec4 uintToRGBAVec (uint u) {
  5399. uvec4 urgba = mask4 & u;
  5400. urgba = urgba >> shift4;
  5401. vec4 rgba = vec4(urgba) * encodeNorm4;
  5402. return rgba;
  5403. }
  5404. vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {
  5405. vec2 samplerUV = vec2(0.0, 0.0);
  5406. float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;
  5407. samplerUV.y = float(floor(d)) / dimensions.y;
  5408. samplerUV.x = fract(d);
  5409. return samplerUV;
  5410. }
  5411. vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {
  5412. vec2 samplerUV = vec2(0.0, 0.0);
  5413. float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;
  5414. samplerUV.y = float(floor(d)) / dimensions.y;
  5415. samplerUV.x = fract(d);
  5416. return samplerUV;
  5417. }
  5418. const float SH_C1 = 0.4886025119029199f;
  5419. const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);
  5420. void main () {
  5421. uint oddOffset = splatIndex & uint(0x00000001);
  5422. uint doubleOddOffset = oddOffset * uint(2);
  5423. bool isEven = oddOffset == uint(0);
  5424. uint nearestEvenIndex = splatIndex - oddOffset;
  5425. float fOddOffset = float(oddOffset);
  5426. uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));
  5427. vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));
  5428. uint sceneIndex = uint(0);
  5429. if (sceneCount > 1) {
  5430. sceneIndex = texture(sceneIndexesTexture, getDataUV(1, 0, sceneIndexesTextureSize)).r;
  5431. }
  5432. `;
  5433. if (enableOptionalEffects) {
  5434. vertexShaderSource += `
  5435. float splatOpacityFromScene = sceneOpacity[sceneIndex];
  5436. int sceneVisible = sceneVisibility[sceneIndex];
  5437. if (splatOpacityFromScene <= 0.01 || sceneVisible == 0) {
  5438. gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
  5439. return;
  5440. }
  5441. `;
  5442. }
  5443. if (dynamicMode) {
  5444. vertexShaderSource += `
  5445. mat4 transform = transforms[sceneIndex];
  5446. //mat4 transformModelViewMatrix = modelViewMatrix * transform;
  5447. mat4 transformModelViewMatrix = modelViewMatrix; //xzw改 直接用最外层的matrixWorld
  5448. `;
  5449. } else {
  5450. vertexShaderSource += `mat4 transformModelViewMatrix = modelViewMatrix;`;
  5451. }
  5452. vertexShaderSource += `
  5453. float sh8BitCompressionRangeMinForScene = sphericalHarmonics8BitCompressionRangeMin[sceneIndex];
  5454. float sh8BitCompressionRangeMaxForScene = sphericalHarmonics8BitCompressionRangeMax[sceneIndex];
  5455. float sh8BitCompressionRangeForScene = sh8BitCompressionRangeMaxForScene - sh8BitCompressionRangeMinForScene;
  5456. float sh8BitCompressionHalfRangeForScene = sh8BitCompressionRangeForScene / 2.0;
  5457. vec3 vec8BitSHShift = vec3(sh8BitCompressionRangeMinForScene);
  5458. vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);
  5459. vec4 clipCenter = projectionMatrix * viewCenter;
  5460. float clip = 1.2 * clipCenter.w;
  5461. if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {
  5462. gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
  5463. return;
  5464. }
  5465. vec3 ndcCenter = clipCenter.xyz / clipCenter.w;
  5466. vPosition = position.xy;
  5467. vColor = uintToRGBAVec(sampledCenterColor.r);
  5468. `;
  5469. // Proceed to sampling and rendering 1st degree spherical harmonics
  5470. if (maxSphericalHarmonicsDegree >= 1) {
  5471. vertexShaderSource += `
  5472. if (sphericalHarmonicsDegree >= 1) {
  5473. `;
  5474. if (dynamicMode) {
  5475. vertexShaderSource += `
  5476. //vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));
  5477. vec3 worldViewDir = normalize(splatCenter - vec3(inverse(modelMatrix) * vec4(cameraPosition, 1.0))); //xzw改 直接用最外层的matrixWorld
  5478. `;
  5479. } else {
  5480. vertexShaderSource += `
  5481. vec3 worldViewDir = normalize(splatCenter - cameraPosition);
  5482. `;
  5483. }
  5484. vertexShaderSource += `
  5485. vec3 sh1;
  5486. vec3 sh2;
  5487. vec3 sh3;
  5488. `;
  5489. if (maxSphericalHarmonicsDegree >= 2) {
  5490. vertexShaderSource += `
  5491. vec3 sh4;
  5492. vec3 sh5;
  5493. vec3 sh6;
  5494. vec3 sh7;
  5495. vec3 sh8;
  5496. `;
  5497. }
  5498. // Determining how to sample spherical harmonics textures to get the coefficients for calculations for a given degree
  5499. // depends on how many total degrees (maxSphericalHarmonicsDegree) are present in the textures. This is because that
  5500. // number affects how they are packed in the textures, and therefore the offset & stride required to access them.
  5501. // Sample spherical harmonics textures with 1 degree worth of data for 1st degree calculations, and store in sh1, sh2, and sh3
  5502. if (maxSphericalHarmonicsDegree === 1) {
  5503. vertexShaderSource += `
  5504. if (sphericalHarmonicsMultiTextureMode == 0) {
  5505. vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);
  5506. vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);
  5507. shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);
  5508. vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);
  5509. shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);
  5510. vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);
  5511. sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;
  5512. sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;
  5513. sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;
  5514. } else {
  5515. vec2 sampledSH01R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
  5516. vec2 sampledSH23R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
  5517. vec2 sampledSH01G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
  5518. vec2 sampledSH23G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
  5519. vec2 sampledSH01B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
  5520. vec2 sampledSH23B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
  5521. sh1 = vec3(sampledSH01R.rg, sampledSH23R.r);
  5522. sh2 = vec3(sampledSH01G.rg, sampledSH23G.r);
  5523. sh3 = vec3(sampledSH01B.rg, sampledSH23B.r);
  5524. }
  5525. `;
  5526. // Sample spherical harmonics textures with 2 degrees worth of data for 1st degree calculations, and store in sh1, sh2, and sh3
  5527. } else if (maxSphericalHarmonicsDegree === 2) {
  5528. vertexShaderSource += `
  5529. vec4 sampledSH0123;
  5530. vec4 sampledSH4567;
  5531. vec4 sampledSH891011;
  5532. vec4 sampledSH0123R;
  5533. vec4 sampledSH0123G;
  5534. vec4 sampledSH0123B;
  5535. if (sphericalHarmonicsMultiTextureMode == 0) {
  5536. sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));
  5537. sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));
  5538. sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));
  5539. sh1 = sampledSH0123.rgb;
  5540. sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);
  5541. sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);
  5542. } else {
  5543. sampledSH0123R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize));
  5544. sampledSH0123G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize));
  5545. sampledSH0123B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize));
  5546. sh1 = vec3(sampledSH0123R.rgb);
  5547. sh2 = vec3(sampledSH0123G.rgb);
  5548. sh3 = vec3(sampledSH0123B.rgb);
  5549. }
  5550. `;
  5551. }
  5552. // Perform 1st degree spherical harmonics calculations
  5553. vertexShaderSource += `
  5554. if (sphericalHarmonics8BitMode == 1) {
  5555. sh1 = sh1 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5556. sh2 = sh2 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5557. sh3 = sh3 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5558. }
  5559. float x = worldViewDir.x;
  5560. float y = worldViewDir.y;
  5561. float z = worldViewDir.z;
  5562. vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);
  5563. `;
  5564. // Proceed to sampling and rendering 2nd degree spherical harmonics
  5565. if (maxSphericalHarmonicsDegree >= 2) {
  5566. vertexShaderSource += `
  5567. if (sphericalHarmonicsDegree >= 2) {
  5568. float xx = x * x;
  5569. float yy = y * y;
  5570. float zz = z * z;
  5571. float xy = x * y;
  5572. float yz = y * z;
  5573. float xz = x * z;
  5574. `;
  5575. // Sample spherical harmonics textures with 2 degrees worth of data for 2nd degree calculations,
  5576. // and store in sh4, sh5, sh6, sh7, and sh8
  5577. if (maxSphericalHarmonicsDegree === 2) {
  5578. vertexShaderSource += `
  5579. if (sphericalHarmonicsMultiTextureMode == 0) {
  5580. vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));
  5581. vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));
  5582. vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));
  5583. sh4 = sampledSH891011.gba;
  5584. sh5 = sampledSH12131415.rgb;
  5585. sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);
  5586. sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);
  5587. sh8 = sampledSH20212223.gba;
  5588. } else {
  5589. vec4 sampledSH4567R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize));
  5590. vec4 sampledSH4567G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize));
  5591. vec4 sampledSH4567B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize));
  5592. sh4 = vec3(sampledSH0123R.a, sampledSH4567R.rg);
  5593. sh5 = vec3(sampledSH4567R.ba, sampledSH0123G.a);
  5594. sh6 = vec3(sampledSH4567G.rgb);
  5595. sh7 = vec3(sampledSH4567G.a, sampledSH0123B.a, sampledSH4567B.r);
  5596. sh8 = vec3(sampledSH4567B.gba);
  5597. }
  5598. `;
  5599. }
  5600. // Perform 2nd degree spherical harmonics calculations
  5601. vertexShaderSource += `
  5602. if (sphericalHarmonics8BitMode == 1) {
  5603. sh4 = sh4 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5604. sh5 = sh5 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5605. sh6 = sh6 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5606. sh7 = sh7 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5607. sh8 = sh8 * sh8BitCompressionRangeForScene + vec8BitSHShift;
  5608. }
  5609. vColor.rgb +=
  5610. (SH_C2[0] * xy) * sh4 +
  5611. (SH_C2[1] * yz) * sh5 +
  5612. (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +
  5613. (SH_C2[3] * xz) * sh7 +
  5614. (SH_C2[4] * (xx - yy)) * sh8;
  5615. }
  5616. `;
  5617. }
  5618. vertexShaderSource += `
  5619. vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));
  5620. }
  5621. `;
  5622. }
  5623. return vertexShaderSource;
  5624. }
  5625. static getVertexShaderFadeIn() {
  5626. return `
  5627. if (fadeInComplete == 0) {
  5628. float opacityAdjust = 1.0;
  5629. float centerDist = length(splatCenter - sceneCenter);
  5630. float renderTime = max(currentTime - firstRenderTime, 0.0);
  5631. float fadeDistance = 0.75;
  5632. float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);
  5633. distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +
  5634. (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *
  5635. distanceLoadFadeInFactor;
  5636. opacityAdjust *= distanceLoadFadeInFactor;
  5637. vColor.a *= opacityAdjust;
  5638. }
  5639. `;
  5640. }
  5641. static getUniforms(dynamicMode = false, enableOptionalEffects = false, maxSphericalHarmonicsDegree = 0,
  5642. splatScale = 1.0, pointCloudModeEnabled = false) {
  5643. const uniforms = {
  5644. 'sceneCenter': {
  5645. 'type': 'v3',
  5646. 'value': new THREE.Vector3()
  5647. },
  5648. 'fadeInComplete': {
  5649. 'type': 'i',
  5650. 'value': 0
  5651. },
  5652. 'orthographicMode': {
  5653. 'type': 'i',
  5654. 'value': 0
  5655. },
  5656. 'visibleRegionFadeStartRadius': {
  5657. 'type': 'f',
  5658. 'value': 0.0
  5659. },
  5660. 'visibleRegionRadius': {
  5661. 'type': 'f',
  5662. 'value': 0.0
  5663. },
  5664. 'currentTime': {
  5665. 'type': 'f',
  5666. 'value': 0.0
  5667. },
  5668. 'firstRenderTime': {
  5669. 'type': 'f',
  5670. 'value': 0.0
  5671. },
  5672. 'centersColorsTexture': {
  5673. 'type': 't',
  5674. 'value': null
  5675. },
  5676. 'sphericalHarmonicsTexture': {
  5677. 'type': 't',
  5678. 'value': null
  5679. },
  5680. 'sphericalHarmonicsTextureR': {
  5681. 'type': 't',
  5682. 'value': null
  5683. },
  5684. 'sphericalHarmonicsTextureG': {
  5685. 'type': 't',
  5686. 'value': null
  5687. },
  5688. 'sphericalHarmonicsTextureB': {
  5689. 'type': 't',
  5690. 'value': null
  5691. },
  5692. 'sphericalHarmonics8BitCompressionRangeMin': {
  5693. 'type': 'f',
  5694. 'value': []
  5695. },
  5696. 'sphericalHarmonics8BitCompressionRangeMax': {
  5697. 'type': 'f',
  5698. 'value': []
  5699. },
  5700. 'focal': {
  5701. 'type': 'v2',
  5702. 'value': new THREE.Vector2()
  5703. },
  5704. 'orthoZoom': {
  5705. 'type': 'f',
  5706. 'value': 1.0
  5707. },
  5708. 'inverseFocalAdjustment': {
  5709. 'type': 'f',
  5710. 'value': 1.0
  5711. },
  5712. 'viewport': {
  5713. 'type': 'v2',
  5714. 'value': new THREE.Vector2()
  5715. },
  5716. 'basisViewport': {
  5717. 'type': 'v2',
  5718. 'value': new THREE.Vector2()
  5719. },
  5720. 'debugColor': {
  5721. 'type': 'v3',
  5722. 'value': new THREE.Color()
  5723. },
  5724. 'centersColorsTextureSize': {
  5725. 'type': 'v2',
  5726. 'value': new THREE.Vector2(1024, 1024)
  5727. },
  5728. 'sphericalHarmonicsDegree': {
  5729. 'type': 'i',
  5730. 'value': maxSphericalHarmonicsDegree
  5731. },
  5732. 'sphericalHarmonicsTextureSize': {
  5733. 'type': 'v2',
  5734. 'value': new THREE.Vector2(1024, 1024)
  5735. },
  5736. 'sphericalHarmonics8BitMode': {
  5737. 'type': 'i',
  5738. 'value': 0
  5739. },
  5740. 'sphericalHarmonicsMultiTextureMode': {
  5741. 'type': 'i',
  5742. 'value': 0
  5743. },
  5744. 'splatScale': {
  5745. 'type': 'f',
  5746. 'value': splatScale
  5747. },
  5748. 'pointCloudModeEnabled': {
  5749. 'type': 'i',
  5750. 'value': pointCloudModeEnabled ? 1 : 0
  5751. },
  5752. 'sceneIndexesTexture': {
  5753. 'type': 't',
  5754. 'value': null
  5755. },
  5756. 'sceneIndexesTextureSize': {
  5757. 'type': 'v2',
  5758. 'value': new THREE.Vector2(1024, 1024)
  5759. },
  5760. 'sceneCount': {
  5761. 'type': 'i',
  5762. 'value': 1
  5763. }
  5764. };
  5765. for (let i = 0; i < Constants.MaxScenes; i++) {
  5766. uniforms.sphericalHarmonics8BitCompressionRangeMin.value.push(-Constants.SphericalHarmonics8BitCompressionRange / 2.0);
  5767. uniforms.sphericalHarmonics8BitCompressionRangeMax.value.push(Constants.SphericalHarmonics8BitCompressionRange / 2.0);
  5768. }
  5769. if (enableOptionalEffects) {
  5770. const sceneOpacity = [];
  5771. for (let i = 0; i < Constants.MaxScenes; i++) {
  5772. sceneOpacity.push(1.0);
  5773. }
  5774. uniforms['sceneOpacity'] ={
  5775. 'type': 'f',
  5776. 'value': sceneOpacity
  5777. };
  5778. const sceneVisibility = [];
  5779. for (let i = 0; i < Constants.MaxScenes; i++) {
  5780. sceneVisibility.push(1);
  5781. }
  5782. uniforms['sceneVisibility'] ={
  5783. 'type': 'i',
  5784. 'value': sceneVisibility
  5785. };
  5786. }
  5787. if (dynamicMode) {
  5788. const transformMatrices = [];
  5789. for (let i = 0; i < Constants.MaxScenes; i++) {
  5790. transformMatrices.push(new THREE.Matrix4());
  5791. }
  5792. uniforms['transforms'] = {
  5793. 'type': 'mat4',
  5794. 'value': transformMatrices
  5795. };
  5796. }
  5797. return uniforms;
  5798. }
  5799. }
  5800. class SplatMaterial3D {
  5801. /**
  5802. * Build the Three.js material that is used to render the splats.
  5803. * @param {number} dynamicMode If true, it means the scene geometry represented by this splat mesh is not stationary or
  5804. * that the splat count might change
  5805. * @param {boolean} enableOptionalEffects When true, allows for usage of extra properties and attributes in the shader for effects
  5806. * such as opacity adjustment. Default is false for performance reasons.
  5807. * @param {boolean} antialiased If true, calculate compensation factor to deal with gaussians being rendered at a significantly
  5808. * different resolution than that of their training
  5809. * @param {number} maxScreenSpaceSplatSize The maximum clip space splat size
  5810. * @param {number} splatScale Value by which all splats are scaled in screen-space (default is 1.0)
  5811. * @param {number} pointCloudModeEnabled Render all splats as screen-space circles
  5812. * @param {number} maxSphericalHarmonicsDegree Degree of spherical harmonics to utilize in rendering splats
  5813. * @return {THREE.ShaderMaterial}
  5814. */
  5815. static build(dynamicMode = false, enableOptionalEffects = false, antialiased = false,
  5816. maxScreenSpaceSplatSize = 2048, splatScale = 1.0, pointCloudModeEnabled = false, maxSphericalHarmonicsDegree = 0) {
  5817. const customVertexVars = `
  5818. uniform vec2 covariancesTextureSize;
  5819. uniform highp sampler2D covariancesTexture;
  5820. uniform highp usampler2D covariancesTextureHalfFloat;
  5821. uniform int covariancesAreHalfFloat;
  5822. void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {
  5823. vec2 r = unpackHalf2x16(val.r);
  5824. vec2 g = unpackHalf2x16(val.g);
  5825. vec2 b = unpackHalf2x16(val.b);
  5826. first = vec4(r.x, r.y, g.x, g.y);
  5827. second = vec4(b.x, b.y, 0.0, 0.0);
  5828. }
  5829. `;
  5830. let vertexShaderSource = SplatMaterial.buildVertexShaderBase(dynamicMode, enableOptionalEffects,
  5831. maxSphericalHarmonicsDegree, customVertexVars);
  5832. vertexShaderSource += SplatMaterial3D.buildVertexShaderProjection(antialiased, enableOptionalEffects, maxScreenSpaceSplatSize);
  5833. const fragmentShaderSource = SplatMaterial3D.buildFragmentShader();
  5834. const uniforms = SplatMaterial.getUniforms(dynamicMode, enableOptionalEffects,
  5835. maxSphericalHarmonicsDegree, splatScale, pointCloudModeEnabled);
  5836. uniforms['covariancesTextureSize'] = {
  5837. 'type': 'v2',
  5838. 'value': new THREE.Vector2(1024, 1024)
  5839. };
  5840. uniforms['covariancesTexture'] = {
  5841. 'type': 't',
  5842. 'value': null
  5843. };
  5844. uniforms['covariancesTextureHalfFloat'] = {
  5845. 'type': 't',
  5846. 'value': null
  5847. };
  5848. uniforms['covariancesAreHalfFloat'] = {
  5849. 'type': 'i',
  5850. 'value': 0
  5851. };
  5852. const material = new THREE.ShaderMaterial({
  5853. uniforms: uniforms,
  5854. vertexShader: vertexShaderSource,
  5855. fragmentShader: fragmentShaderSource,
  5856. transparent: true,
  5857. alphaTest: 1.0,
  5858. blending: THREE.NormalBlending,
  5859. depthTest: true,
  5860. depthWrite: false,
  5861. side: THREE.DoubleSide
  5862. });
  5863. return material;
  5864. }
  5865. static buildVertexShaderProjection(antialiased, enableOptionalEffects, maxScreenSpaceSplatSize) {
  5866. let vertexShaderSource = `
  5867. vec4 sampledCovarianceA;
  5868. vec4 sampledCovarianceB;
  5869. vec3 cov3D_M11_M12_M13;
  5870. vec3 cov3D_M22_M23_M33;
  5871. if (covariancesAreHalfFloat == 0) {
  5872. sampledCovarianceA = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset,
  5873. covariancesTextureSize));
  5874. sampledCovarianceB = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1),
  5875. covariancesTextureSize));
  5876. cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +
  5877. vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;
  5878. cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +
  5879. vec3(sampledCovarianceB.gba) * fOddOffset;
  5880. } else {
  5881. uvec4 sampledCovarianceU = texture(covariancesTextureHalfFloat, getDataUV(1, 0, covariancesTextureSize));
  5882. fromCovarianceHalfFloatV4(sampledCovarianceU, sampledCovarianceA, sampledCovarianceB);
  5883. cov3D_M11_M12_M13 = sampledCovarianceA.rgb;
  5884. cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg);
  5885. }
  5886. // Construct the 3D covariance matrix
  5887. mat3 Vrk = mat3(
  5888. cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,
  5889. cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,
  5890. cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z
  5891. );
  5892. mat3 J;
  5893. if (orthographicMode == 1) {
  5894. // Since the projection is linear, we don't need an approximation
  5895. J = transpose(mat3(orthoZoom, 0.0, 0.0,
  5896. 0.0, orthoZoom, 0.0,
  5897. 0.0, 0.0, 0.0));
  5898. } else {
  5899. // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the
  5900. // 3D covariance matrix instead of using the actual projection matrix because that transformation would
  5901. // require a non-linear component (perspective division) which would yield a non-gaussian result.
  5902. float s = 1.0 / (viewCenter.z * viewCenter.z);
  5903. J = mat3(
  5904. focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,
  5905. 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,
  5906. 0., 0., 0.
  5907. );
  5908. }
  5909. // Concatenate the projection approximation with the model-view transformation
  5910. mat3 W = transpose(mat3(transformModelViewMatrix));
  5911. mat3 T = W * J;
  5912. // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix
  5913. mat3 cov2Dm = transpose(T) * Vrk * T;
  5914. `;
  5915. if (antialiased) {
  5916. vertexShaderSource += `
  5917. // (mip-slpatting:https://niujinshuchong.github.io/mip-splatting/)
  5918. // compute the coef of alpha based on the detemintant
  5919. // float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];
  5920. // cov2Dm[0][0] += 0.3;
  5921. // cov2Dm[1][1] += 0.3;
  5922. // float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];
  5923. // vColor.a *= sqrt(max(detOrig / detBlur, 0.0));
  5924. // if (vColor.a < minAlpha) return;
  5925. float kernel_size_2D_mip_filter = 0.1;
  5926. float det_0 = max(1e-6, cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1]);
  5927. cov2Dm[0][0] += kernel_size_2D_mip_filter;
  5928. cov2Dm[1][1] += kernel_size_2D_mip_filter;
  5929. float det_1 = max(1e-6, cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1]);
  5930. float coef = sqrt(det_0 / (det_1+1e-6) + 1e-6);
  5931. if (det_0 <= 1e-6 || det_1 <= 1e-6){
  5932. coef = 0.0f;
  5933. }
  5934. vColor.a *= coef;
  5935. if (vColor.a < minAlpha) return;
  5936. `;
  5937. } else {
  5938. vertexShaderSource += `
  5939. cov2Dm[0][0] += 0.3;
  5940. cov2Dm[1][1] += 0.3;
  5941. `;
  5942. }
  5943. vertexShaderSource += `
  5944. // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because
  5945. // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],
  5946. // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't
  5947. // need cov2Dm[1][0] because it is a symetric matrix.
  5948. vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);
  5949. // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix
  5950. // so that we can determine the 2D basis for the splat. This is done using the method described
  5951. // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html
  5952. // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat
  5953. // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * sqrt(eigen-value)), which is
  5954. // equal to scaling them by sqrt(8) standard deviations.
  5955. //
  5956. // This is a different approach than in the original work at INRIA. In that work they compute the
  5957. // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle
  5958. // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0
  5959. // times the square root of the maximum eigen-value, or 3 standard deviations. They then use the inverse
  5960. // 2D covariance matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by
  5961. // calculating the full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity
  5962. float a = cov2Dv.x;
  5963. float d = cov2Dv.z;
  5964. float b = cov2Dv.y;
  5965. float D = a * d - b * b;
  5966. float trace = a + d;
  5967. float traceOver2 = 0.5 * trace;
  5968. float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));
  5969. float eigenValue1 = traceOver2 + term2;
  5970. float eigenValue2 = traceOver2 - term2;
  5971. if (pointCloudModeEnabled == 1) {
  5972. eigenValue1 = eigenValue2 = 0.2;
  5973. }
  5974. if (eigenValue2 <= 0.0) return;
  5975. vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));
  5976. // since the eigen vectors are orthogonal, we derive the second one from the first
  5977. vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);
  5978. // We use sqrt(8) standard deviations instead of 3 to eliminate more of the splat with a very low opacity.
  5979. vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ${parseInt(maxScreenSpaceSplatSize)}.0);
  5980. vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(maxScreenSpaceSplatSize)}.0);
  5981. `;
  5982. if (enableOptionalEffects) {
  5983. vertexShaderSource += `
  5984. vColor.a *= splatOpacityFromScene;
  5985. `;
  5986. }
  5987. vertexShaderSource += `
  5988. vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *
  5989. basisViewport * 2.0 * inverseFocalAdjustment;
  5990. vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
  5991. gl_Position = quadPos;
  5992. // Scale the position data we send to the fragment shader
  5993. vPosition *= sqrt8;
  5994. `;
  5995. vertexShaderSource += SplatMaterial.getVertexShaderFadeIn();
  5996. vertexShaderSource += `}`;
  5997. return vertexShaderSource;
  5998. }
  5999. static buildFragmentShader() {
  6000. let fragmentShaderSource = `
  6001. precision highp float;
  6002. #include <common>
  6003. uniform vec3 debugColor;
  6004. varying vec4 vColor;
  6005. varying vec2 vUv;
  6006. varying vec2 vPosition;
  6007. `;
  6008. fragmentShaderSource += `
  6009. void main () {
  6010. // Compute the positional squared distance from the center of the splat to the current fragment.
  6011. float A = dot(vPosition, vPosition);
  6012. // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be
  6013. // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse
  6014. // defined by the rectangle formed by vPosition. It also means it's farther
  6015. // away than sqrt(8) standard deviations from the mean.
  6016. if (A > 8.0) discard;
  6017. vec3 color = vColor.rgb;
  6018. // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of
  6019. // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),
  6020. // and since 'mean' is zero, we have X * X, which is the same as A:
  6021. float opacity = exp(-0.5 * A) * vColor.a;
  6022. gl_FragColor = vec4(color.rgb, opacity);
  6023. }
  6024. `;
  6025. return fragmentShaderSource;
  6026. }
  6027. }
  6028. class SplatMaterial2D {
  6029. /**
  6030. * Build the Three.js material that is used to render the splats.
  6031. * @param {number} dynamicMode If true, it means the scene geometry represented by this splat mesh is not stationary or
  6032. * that the splat count might change
  6033. * @param {boolean} enableOptionalEffects When true, allows for usage of extra properties and attributes in the shader for effects
  6034. * such as opacity adjustment. Default is false for performance reasons.
  6035. * @param {number} splatScale Value by which all splats are scaled in screen-space (default is 1.0)
  6036. * @param {number} pointCloudModeEnabled Render all splats as screen-space circles
  6037. * @param {number} maxSphericalHarmonicsDegree Degree of spherical harmonics to utilize in rendering splats
  6038. * @return {THREE.ShaderMaterial}
  6039. */
  6040. static build(dynamicMode = false, enableOptionalEffects = false, splatScale = 1.0,
  6041. pointCloudModeEnabled = false, maxSphericalHarmonicsDegree = 0) {
  6042. const customVertexVars = `
  6043. uniform vec2 scaleRotationsTextureSize;
  6044. uniform highp sampler2D scaleRotationsTexture;
  6045. varying mat3 vT;
  6046. varying vec2 vQuadCenter;
  6047. varying vec2 vFragCoord;
  6048. `;
  6049. let vertexShaderSource = SplatMaterial.buildVertexShaderBase(dynamicMode, enableOptionalEffects,
  6050. maxSphericalHarmonicsDegree, customVertexVars);
  6051. vertexShaderSource += SplatMaterial2D.buildVertexShaderProjection();
  6052. const fragmentShaderSource = SplatMaterial2D.buildFragmentShader();
  6053. const uniforms = SplatMaterial.getUniforms(dynamicMode, enableOptionalEffects,
  6054. maxSphericalHarmonicsDegree, splatScale, pointCloudModeEnabled);
  6055. uniforms['scaleRotationsTexture'] = {
  6056. 'type': 't',
  6057. 'value': null
  6058. };
  6059. uniforms['scaleRotationsTextureSize'] = {
  6060. 'type': 'v2',
  6061. 'value': new THREE.Vector2(1024, 1024)
  6062. };
  6063. const material = new THREE.ShaderMaterial({
  6064. uniforms: uniforms,
  6065. vertexShader: vertexShaderSource,
  6066. fragmentShader: fragmentShaderSource,
  6067. transparent: true,
  6068. alphaTest: 1.0,
  6069. blending: THREE.NormalBlending,
  6070. depthTest: true,
  6071. depthWrite: false,
  6072. side: THREE.DoubleSide
  6073. });
  6074. return material;
  6075. }
  6076. static buildVertexShaderProjection() {
  6077. // Original CUDA code for calculating splat-to-screen transformation, for reference
  6078. /*
  6079. glm::mat3 R = quat_to_rotmat(rot);
  6080. glm::mat3 S = scale_to_mat(scale, mod);
  6081. glm::mat3 L = R * S;
  6082. // center of Gaussians in the camera coordinate
  6083. glm::mat3x4 splat2world = glm::mat3x4(
  6084. glm::vec4(L[0], 0.0),
  6085. glm::vec4(L[1], 0.0),
  6086. glm::vec4(p_orig.x, p_orig.y, p_orig.z, 1)
  6087. );
  6088. glm::mat4 world2ndc = glm::mat4(
  6089. projmatrix[0], projmatrix[4], projmatrix[8], projmatrix[12],
  6090. projmatrix[1], projmatrix[5], projmatrix[9], projmatrix[13],
  6091. projmatrix[2], projmatrix[6], projmatrix[10], projmatrix[14],
  6092. projmatrix[3], projmatrix[7], projmatrix[11], projmatrix[15]
  6093. );
  6094. glm::mat3x4 ndc2pix = glm::mat3x4(
  6095. glm::vec4(float(W) / 2.0, 0.0, 0.0, float(W-1) / 2.0),
  6096. glm::vec4(0.0, float(H) / 2.0, 0.0, float(H-1) / 2.0),
  6097. glm::vec4(0.0, 0.0, 0.0, 1.0)
  6098. );
  6099. T = glm::transpose(splat2world) * world2ndc * ndc2pix;
  6100. normal = transformVec4x3({L[2].x, L[2].y, L[2].z}, viewmatrix);
  6101. */
  6102. // Compute a 2D-to-2D mapping matrix from a tangent plane into a image plane
  6103. // given a 2D gaussian parameters. T = WH (from the paper: https://arxiv.org/pdf/2403.17888)
  6104. let vertexShaderSource = `
  6105. vec4 scaleRotationA = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,
  6106. oddOffset, scaleRotationsTextureSize));
  6107. vec4 scaleRotationB = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,
  6108. oddOffset + uint(1), scaleRotationsTextureSize));
  6109. vec3 scaleRotation123 = vec3(scaleRotationA.rgb) * (1.0 - fOddOffset) +
  6110. vec3(scaleRotationA.ba, scaleRotationB.r) * fOddOffset;
  6111. vec3 scaleRotation456 = vec3(scaleRotationA.a, scaleRotationB.rg) * (1.0 - fOddOffset) +
  6112. vec3(scaleRotationB.gba) * fOddOffset;
  6113. float missingW = sqrt(1.0 - scaleRotation456.x * scaleRotation456.x - scaleRotation456.y *
  6114. scaleRotation456.y - scaleRotation456.z * scaleRotation456.z);
  6115. mat3 R = quaternionToRotationMatrix(scaleRotation456.r, scaleRotation456.g, scaleRotation456.b, missingW);
  6116. mat3 S = mat3(scaleRotation123.r, 0.0, 0.0,
  6117. 0.0, scaleRotation123.g, 0.0,
  6118. 0.0, 0.0, scaleRotation123.b);
  6119. mat3 L = R * S;
  6120. mat3x4 splat2World = mat3x4(vec4(L[0], 0.0),
  6121. vec4(L[1], 0.0),
  6122. vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));
  6123. mat4 world2ndc = transpose(projectionMatrix * transformModelViewMatrix);
  6124. mat3x4 ndc2pix = mat3x4(vec4(viewport.x / 2.0, 0.0, 0.0, (viewport.x - 1.0) / 2.0),
  6125. vec4(0.0, viewport.y / 2.0, 0.0, (viewport.y - 1.0) / 2.0),
  6126. vec4(0.0, 0.0, 0.0, 1.0));
  6127. mat3 T = transpose(splat2World) * world2ndc * ndc2pix;
  6128. vec3 normal = vec3(viewMatrix * vec4(L[0][2], L[1][2], L[2][2], 0.0));
  6129. `;
  6130. // Original CUDA code for projection to 2D, for reference
  6131. /*
  6132. float3 T0 = {T[0][0], T[0][1], T[0][2]};
  6133. float3 T1 = {T[1][0], T[1][1], T[1][2]};
  6134. float3 T3 = {T[2][0], T[2][1], T[2][2]};
  6135. // Compute AABB
  6136. float3 temp_point = {1.0f, 1.0f, -1.0f};
  6137. float distance = sumf3(T3 * T3 * temp_point);
  6138. float3 f = (1 / distance) * temp_point;
  6139. if (distance == 0.0) return false;
  6140. point_image = {
  6141. sumf3(f * T0 * T3),
  6142. sumf3(f * T1 * T3)
  6143. };
  6144. float2 temp = {
  6145. sumf3(f * T0 * T0),
  6146. sumf3(f * T1 * T1)
  6147. };
  6148. float2 half_extend = point_image * point_image - temp;
  6149. extent = sqrtf2(maxf2(1e-4, half_extend));
  6150. return true;
  6151. */
  6152. // Computing the bounding box of the 2D Gaussian and its center
  6153. // The center of the bounding box is used to create a low pass filter.
  6154. // This code is based off the reference implementation and creates an AABB aligned
  6155. // with the screen for the quad to be rendered.
  6156. const referenceQuadGeneration = `
  6157. vec3 T0 = vec3(T[0][0], T[0][1], T[0][2]);
  6158. vec3 T1 = vec3(T[1][0], T[1][1], T[1][2]);
  6159. vec3 T3 = vec3(T[2][0], T[2][1], T[2][2]);
  6160. vec3 tempPoint = vec3(1.0, 1.0, -1.0);
  6161. float distance = (T3.x * T3.x * tempPoint.x) + (T3.y * T3.y * tempPoint.y) + (T3.z * T3.z * tempPoint.z);
  6162. vec3 f = (1.0 / distance) * tempPoint;
  6163. if (abs(distance) < 0.00001) return;
  6164. float pointImageX = (T0.x * T3.x * f.x) + (T0.y * T3.y * f.y) + (T0.z * T3.z * f.z);
  6165. float pointImageY = (T1.x * T3.x * f.x) + (T1.y * T3.y * f.y) + (T1.z * T3.z * f.z);
  6166. vec2 pointImage = vec2(pointImageX, pointImageY);
  6167. float tempX = (T0.x * T0.x * f.x) + (T0.y * T0.y * f.y) + (T0.z * T0.z * f.z);
  6168. float tempY = (T1.x * T1.x * f.x) + (T1.y * T1.y * f.y) + (T1.z * T1.z * f.z);
  6169. vec2 temp = vec2(tempX, tempY);
  6170. vec2 halfExtend = pointImage * pointImage - temp;
  6171. vec2 extent = sqrt(max(vec2(0.0001), halfExtend));
  6172. float radius = max(extent.x, extent.y);
  6173. vec2 ndcOffset = ((position.xy * radius * 3.0) * basisViewport * 2.0);
  6174. vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
  6175. gl_Position = quadPos;
  6176. vT = T;
  6177. vQuadCenter = pointImage;
  6178. vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;
  6179. `;
  6180. const useRefImplementation = false;
  6181. if (useRefImplementation) {
  6182. vertexShaderSource += referenceQuadGeneration;
  6183. } else {
  6184. // Create a quad that is aligned with the eigen vectors of the projected gaussian for rendering.
  6185. // This is a different approach than the reference implementation, similar to how the rendering of
  6186. // 3D gaussians in this viewer differs from the reference implementation. If the quad is too small
  6187. // (smaller than a pixel), then revert to the reference implementation.
  6188. vertexShaderSource += `
  6189. mat4 splat2World4 = mat4(vec4(L[0], 0.0),
  6190. vec4(L[1], 0.0),
  6191. vec4(L[2], 0.0),
  6192. vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));
  6193. mat4 Tt = transpose(transpose(splat2World4) * world2ndc);
  6194. vec4 tempPoint1 = Tt * vec4(1.0, 0.0, 0.0, 1.0);
  6195. tempPoint1 /= tempPoint1.w;
  6196. vec4 tempPoint2 = Tt * vec4(0.0, 1.0, 0.0, 1.0);
  6197. tempPoint2 /= tempPoint2.w;
  6198. vec4 center = Tt * vec4(0.0, 0.0, 0.0, 1.0);
  6199. center /= center.w;
  6200. vec2 basisVector1 = tempPoint1.xy - center.xy;
  6201. vec2 basisVector2 = tempPoint2.xy - center.xy;
  6202. vec2 basisVector1Screen = basisVector1 * 0.5 * viewport;
  6203. vec2 basisVector2Screen = basisVector2 * 0.5 * viewport;
  6204. const float minPix = 1.;
  6205. if (length(basisVector1Screen) < minPix || length(basisVector2Screen) < minPix) {
  6206. ${referenceQuadGeneration}
  6207. } else {
  6208. vec2 ndcOffset = vec2(position.x * basisVector1 + position.y * basisVector2) * 3.0 * inverseFocalAdjustment;
  6209. vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
  6210. gl_Position = quadPos;
  6211. vT = T;
  6212. vQuadCenter = center.xy;
  6213. vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;
  6214. }
  6215. `;
  6216. }
  6217. vertexShaderSource += SplatMaterial.getVertexShaderFadeIn();
  6218. vertexShaderSource += `}`;
  6219. return vertexShaderSource;
  6220. }
  6221. static buildFragmentShader() {
  6222. // Original CUDA code for splat intersection, for reference
  6223. /*
  6224. const float2 xy = collected_xy[j];
  6225. const float3 Tu = collected_Tu[j];
  6226. const float3 Tv = collected_Tv[j];
  6227. const float3 Tw = collected_Tw[j];
  6228. float3 k = pix.x * Tw - Tu;
  6229. float3 l = pix.y * Tw - Tv;
  6230. float3 p = cross(k, l);
  6231. if (p.z == 0.0) continue;
  6232. float2 s = {p.x / p.z, p.y / p.z};
  6233. float rho3d = (s.x * s.x + s.y * s.y);
  6234. float2 d = {xy.x - pixf.x, xy.y - pixf.y};
  6235. float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y);
  6236. // compute intersection and depth
  6237. float rho = min(rho3d, rho2d);
  6238. float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z;
  6239. if (depth < near_n) continue;
  6240. float4 nor_o = collected_normal_opacity[j];
  6241. float normal[3] = {nor_o.x, nor_o.y, nor_o.z};
  6242. float opa = nor_o.w;
  6243. float power = -0.5f * rho;
  6244. if (power > 0.0f)
  6245. continue;
  6246. // Eq. (2) from 3D Gaussian splatting paper.
  6247. // Obtain alpha by multiplying with Gaussian opacity
  6248. // and its exponential falloff from mean.
  6249. // Avoid numerical instabilities (see paper appendix).
  6250. float alpha = min(0.99f, opa * exp(power));
  6251. if (alpha < 1.0f / 255.0f)
  6252. continue;
  6253. float test_T = T * (1 - alpha);
  6254. if (test_T < 0.0001f)
  6255. {
  6256. done = true;
  6257. continue;
  6258. }
  6259. float w = alpha * T;
  6260. */
  6261. let fragmentShaderSource = `
  6262. precision highp float;
  6263. #include <common>
  6264. uniform vec3 debugColor;
  6265. varying vec4 vColor;
  6266. varying vec2 vUv;
  6267. varying vec2 vPosition;
  6268. varying mat3 vT;
  6269. varying vec2 vQuadCenter;
  6270. varying vec2 vFragCoord;
  6271. void main () {
  6272. const float FilterInvSquare = 2.0;
  6273. const float near_n = 0.2;
  6274. const float T = 1.0;
  6275. vec2 xy = vQuadCenter;
  6276. vec3 Tu = vT[0];
  6277. vec3 Tv = vT[1];
  6278. vec3 Tw = vT[2];
  6279. vec3 k = vFragCoord.x * Tw - Tu;
  6280. vec3 l = vFragCoord.y * Tw - Tv;
  6281. vec3 p = cross(k, l);
  6282. if (p.z == 0.0) discard;
  6283. vec2 s = vec2(p.x / p.z, p.y / p.z);
  6284. float rho3d = (s.x * s.x + s.y * s.y);
  6285. vec2 d = vec2(xy.x - vFragCoord.x, xy.y - vFragCoord.y);
  6286. float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y);
  6287. // compute intersection and depth
  6288. float rho = min(rho3d, rho2d);
  6289. float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z;
  6290. if (depth < near_n) discard;
  6291. // vec4 nor_o = collected_normal_opacity[j];
  6292. // float normal[3] = {nor_o.x, nor_o.y, nor_o.z};
  6293. float opa = vColor.a;
  6294. float power = -0.5f * rho;
  6295. if (power > 0.0f) discard;
  6296. // Eq. (2) from 3D Gaussian splatting paper.
  6297. // Obtain alpha by multiplying with Gaussian opacity
  6298. // and its exponential falloff from mean.
  6299. // Avoid numerical instabilities (see paper appendix).
  6300. float alpha = min(0.99f, opa * exp(power));
  6301. if (alpha < 1.0f / 255.0f) discard;
  6302. float test_T = T * (1.0 - alpha);
  6303. if (test_T < 0.0001)discard;
  6304. float w = alpha * T;
  6305. gl_FragColor = vec4(vColor.rgb, w);
  6306. }
  6307. `;
  6308. return fragmentShaderSource;
  6309. }
  6310. }
  6311. class SplatGeometry {
  6312. /**
  6313. * Build the Three.js geometry that will be used to render the splats. The geometry is instanced and is made up of
  6314. * vertices for a single quad as well as an attribute buffer for the splat indexes.
  6315. * @param {number} maxSplatCount The maximum number of splats that the geometry will need to accomodate
  6316. * @return {THREE.InstancedBufferGeometry}
  6317. */
  6318. static build(maxSplatCount) {
  6319. const baseGeometry = new THREE.BufferGeometry();
  6320. baseGeometry.setIndex([0, 1, 2, 0, 2, 3]);
  6321. // Vertices for the instanced quad
  6322. const positionsArray = new Float32Array(4 * 3);
  6323. const positions = new THREE.BufferAttribute(positionsArray, 3);
  6324. baseGeometry.setAttribute('position', positions);
  6325. positions.setXYZ(0, -1.0, -1.0, 0.0);
  6326. positions.setXYZ(1, -1.0, 1.0, 0.0);
  6327. positions.setXYZ(2, 1.0, 1.0, 0.0);
  6328. positions.setXYZ(3, 1.0, -1.0, 0.0);
  6329. positions.needsUpdate = true;
  6330. const geometry = new THREE.InstancedBufferGeometry().copy(baseGeometry);
  6331. // Splat index buffer
  6332. const splatIndexArray = new Uint32Array(maxSplatCount);
  6333. const splatIndexes = new THREE.InstancedBufferAttribute(splatIndexArray, 1, false);
  6334. splatIndexes.setUsage(THREE.DynamicDrawUsage);
  6335. geometry.setAttribute('splatIndex', splatIndexes);
  6336. geometry.instanceCount = 0;
  6337. return geometry;
  6338. }
  6339. }
  6340. /**
  6341. * SplatScene: Descriptor for a single splat scene managed by an instance of SplatMesh.
  6342. */
  6343. class SplatScene extends THREE.Object3D {
  6344. constructor(splatBuffer, position = new THREE.Vector3(), quaternion = new THREE.Quaternion(),
  6345. scale = new THREE.Vector3(1, 1, 1), minimumAlpha = 1, opacity = 1.0, visible = true) {
  6346. super();
  6347. this.splatBuffer = splatBuffer;
  6348. this.position.copy(position);
  6349. this.quaternion.copy(quaternion);
  6350. this.scale.copy(scale);
  6351. this.transform = new THREE.Matrix4();
  6352. this.minimumAlpha = minimumAlpha;
  6353. this.opacity = opacity;
  6354. this.visible = visible;
  6355. }
  6356. copyTransformData(otherScene) {
  6357. this.position.copy(otherScene.position);
  6358. this.quaternion.copy(otherScene.quaternion);
  6359. this.scale.copy(otherScene.scale);
  6360. this.transform.copy(otherScene.transform);
  6361. }
  6362. updateTransform(dynamicMode) {
  6363. /* if (dynamicMode) {
  6364. if (this.matrixWorldAutoUpdate) this.updateWorldMatrix(true, false);
  6365. this.transform.copy(this.matrixWorld);
  6366. } else { */
  6367. if (this.matrixAutoUpdate) this.updateMatrix();
  6368. this.transform.copy(this.matrix);
  6369. //}
  6370. }
  6371. }
  6372. class SplatTreeNode {
  6373. static idGen = 0;
  6374. constructor(min, max, depth, id) {
  6375. this.min = new THREE.Vector3().copy(min);
  6376. this.max = new THREE.Vector3().copy(max);
  6377. this.boundingBox = new THREE.Box3(this.min, this.max);
  6378. this.center = new THREE.Vector3().copy(this.max).sub(this.min).multiplyScalar(0.5).add(this.min);
  6379. this.depth = depth;
  6380. this.children = [];
  6381. this.data = null;
  6382. this.id = id || SplatTreeNode.idGen++;
  6383. }
  6384. }
  6385. class SplatSubTree {
  6386. constructor(maxDepth, maxCentersPerNode) {
  6387. this.maxDepth = maxDepth;
  6388. this.maxCentersPerNode = maxCentersPerNode;
  6389. this.sceneDimensions = new THREE.Vector3();
  6390. this.sceneMin = new THREE.Vector3();
  6391. this.sceneMax = new THREE.Vector3();
  6392. this.rootNode = null;
  6393. this.nodesWithIndexes = [];
  6394. this.splatMesh = null;
  6395. }
  6396. static convertWorkerSubTreeNode(workerSubTreeNode) {
  6397. const minVector = new THREE.Vector3().fromArray(workerSubTreeNode.min);
  6398. const maxVector = new THREE.Vector3().fromArray(workerSubTreeNode.max);
  6399. const convertedNode = new SplatTreeNode(minVector, maxVector, workerSubTreeNode.depth, workerSubTreeNode.id);
  6400. if (workerSubTreeNode.data.indexes) {
  6401. convertedNode.data = {
  6402. 'indexes': []
  6403. };
  6404. for (let index of workerSubTreeNode.data.indexes) {
  6405. convertedNode.data.indexes.push(index);
  6406. }
  6407. }
  6408. if (workerSubTreeNode.children) {
  6409. for (let child of workerSubTreeNode.children) {
  6410. convertedNode.children.push(SplatSubTree.convertWorkerSubTreeNode(child));
  6411. }
  6412. }
  6413. return convertedNode;
  6414. }
  6415. static convertWorkerSubTree(workerSubTree, splatMesh) {
  6416. const convertedSubTree = new SplatSubTree(workerSubTree.maxDepth, workerSubTree.maxCentersPerNode);
  6417. convertedSubTree.sceneMin = new THREE.Vector3().fromArray(workerSubTree.sceneMin);
  6418. convertedSubTree.sceneMax = new THREE.Vector3().fromArray(workerSubTree.sceneMax);
  6419. convertedSubTree.splatMesh = splatMesh;
  6420. convertedSubTree.rootNode = SplatSubTree.convertWorkerSubTreeNode(workerSubTree.rootNode);
  6421. const visitLeavesFromNode = (node, visitFunc) => {
  6422. if (node.children.length === 0) visitFunc(node);
  6423. for (let child of node.children) {
  6424. visitLeavesFromNode(child, visitFunc);
  6425. }
  6426. };
  6427. convertedSubTree.nodesWithIndexes = [];
  6428. visitLeavesFromNode(convertedSubTree.rootNode, (node) => {
  6429. if (node.data && node.data.indexes && node.data.indexes.length > 0) {
  6430. convertedSubTree.nodesWithIndexes.push(node);
  6431. }
  6432. });
  6433. return convertedSubTree;
  6434. }
  6435. }
  6436. function createSplatTreeWorker(self) {
  6437. let WorkerSplatTreeNodeIDGen = 0;
  6438. class WorkerBox3 {
  6439. constructor(min, max) {
  6440. this.min = [min[0], min[1], min[2]];
  6441. this.max = [max[0], max[1], max[2]];
  6442. }
  6443. containsPoint(point) {
  6444. return point[0] >= this.min[0] && point[0] <= this.max[0] &&
  6445. point[1] >= this.min[1] && point[1] <= this.max[1] &&
  6446. point[2] >= this.min[2] && point[2] <= this.max[2];
  6447. }
  6448. }
  6449. class WorkerSplatSubTree {
  6450. constructor(maxDepth, maxCentersPerNode) {
  6451. this.maxDepth = maxDepth;
  6452. this.maxCentersPerNode = maxCentersPerNode;
  6453. this.sceneDimensions = [];
  6454. this.sceneMin = [];
  6455. this.sceneMax = [];
  6456. this.rootNode = null;
  6457. this.addedIndexes = {};
  6458. this.nodesWithIndexes = [];
  6459. this.splatMesh = null;
  6460. this.disposed = false;
  6461. }
  6462. }
  6463. class WorkerSplatTreeNode {
  6464. constructor(min, max, depth, id) {
  6465. this.min = [min[0], min[1], min[2]];
  6466. this.max = [max[0], max[1], max[2]];
  6467. this.center = [(max[0] - min[0]) * 0.5 + min[0],
  6468. (max[1] - min[1]) * 0.5 + min[1],
  6469. (max[2] - min[2]) * 0.5 + min[2]];
  6470. this.depth = depth;
  6471. this.children = [];
  6472. this.data = null;
  6473. this.id = id || WorkerSplatTreeNodeIDGen++;
  6474. }
  6475. }
  6476. processSplatTreeNode = function(tree, node, indexToCenter, sceneCenters) {
  6477. const splatCount = node.data.indexes.length;
  6478. if (splatCount < tree.maxCentersPerNode || node.depth > tree.maxDepth) {
  6479. const newIndexes = [];
  6480. for (let i = 0; i < node.data.indexes.length; i++) {
  6481. if (!tree.addedIndexes[node.data.indexes[i]]) {
  6482. newIndexes.push(node.data.indexes[i]);
  6483. tree.addedIndexes[node.data.indexes[i]] = true;
  6484. }
  6485. }
  6486. node.data.indexes = newIndexes;
  6487. node.data.indexes.sort((a, b) => {
  6488. if (a > b) return 1;
  6489. else return -1;
  6490. });
  6491. tree.nodesWithIndexes.push(node);
  6492. return;
  6493. }
  6494. const nodeDimensions = [node.max[0] - node.min[0],
  6495. node.max[1] - node.min[1],
  6496. node.max[2] - node.min[2]];
  6497. const halfDimensions = [nodeDimensions[0] * 0.5,
  6498. nodeDimensions[1] * 0.5,
  6499. nodeDimensions[2] * 0.5];
  6500. const nodeCenter = [node.min[0] + halfDimensions[0],
  6501. node.min[1] + halfDimensions[1],
  6502. node.min[2] + halfDimensions[2]];
  6503. const childrenBounds = [
  6504. // top section, clockwise from upper-left (looking from above, +Y)
  6505. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]],
  6506. [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]),
  6507. new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]],
  6508. [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]),
  6509. new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2]],
  6510. [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]),
  6511. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2]],
  6512. [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]),
  6513. // bottom section, clockwise from lower-left (looking from above, +Y)
  6514. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]],
  6515. [nodeCenter[0], nodeCenter[1], nodeCenter[2]]),
  6516. new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]],
  6517. [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2]]),
  6518. new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]],
  6519. [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]]),
  6520. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]],
  6521. [nodeCenter[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]]),
  6522. ];
  6523. const splatCounts = [];
  6524. const baseIndexes = [];
  6525. for (let i = 0; i < childrenBounds.length; i++) {
  6526. splatCounts[i] = 0;
  6527. baseIndexes[i] = [];
  6528. }
  6529. const center = [0, 0, 0];
  6530. for (let i = 0; i < splatCount; i++) {
  6531. const splatGlobalIndex = node.data.indexes[i];
  6532. const centerBase = indexToCenter[splatGlobalIndex];
  6533. center[0] = sceneCenters[centerBase];
  6534. center[1] = sceneCenters[centerBase + 1];
  6535. center[2] = sceneCenters[centerBase + 2];
  6536. for (let j = 0; j < childrenBounds.length; j++) {
  6537. if (childrenBounds[j].containsPoint(center)) {
  6538. splatCounts[j]++;
  6539. baseIndexes[j].push(splatGlobalIndex);
  6540. }
  6541. }
  6542. }
  6543. for (let i = 0; i < childrenBounds.length; i++) {
  6544. const childNode = new WorkerSplatTreeNode(childrenBounds[i].min, childrenBounds[i].max, node.depth + 1);
  6545. childNode.data = {
  6546. 'indexes': baseIndexes[i]
  6547. };
  6548. node.children.push(childNode);
  6549. }
  6550. node.data = {};
  6551. for (let child of node.children) {
  6552. processSplatTreeNode(tree, child, indexToCenter, sceneCenters);
  6553. }
  6554. return;
  6555. };
  6556. const buildSubTree = (sceneCenters, maxDepth, maxCentersPerNode) => {
  6557. const sceneMin = [0, 0, 0];
  6558. const sceneMax = [0, 0, 0];
  6559. const indexes = [];
  6560. const centerCount = Math.floor(sceneCenters.length / 4);
  6561. for ( let i = 0; i < centerCount; i ++) {
  6562. const base = i * 4;
  6563. const x = sceneCenters[base];
  6564. const y = sceneCenters[base + 1];
  6565. const z = sceneCenters[base + 2];
  6566. const index = Math.round(sceneCenters[base + 3]);
  6567. if (i === 0 || x < sceneMin[0]) sceneMin[0] = x;
  6568. if (i === 0 || x > sceneMax[0]) sceneMax[0] = x;
  6569. if (i === 0 || y < sceneMin[1]) sceneMin[1] = y;
  6570. if (i === 0 || y > sceneMax[1]) sceneMax[1] = y;
  6571. if (i === 0 || z < sceneMin[2]) sceneMin[2] = z;
  6572. if (i === 0 || z > sceneMax[2]) sceneMax[2] = z;
  6573. indexes.push(index);
  6574. }
  6575. const subTree = new WorkerSplatSubTree(maxDepth, maxCentersPerNode);
  6576. subTree.sceneMin = sceneMin;
  6577. subTree.sceneMax = sceneMax;
  6578. subTree.rootNode = new WorkerSplatTreeNode(subTree.sceneMin, subTree.sceneMax, 0);
  6579. subTree.rootNode.data = {
  6580. 'indexes': indexes
  6581. };
  6582. return subTree;
  6583. };
  6584. function createSplatTree(allCenters, maxDepth, maxCentersPerNode) {
  6585. const indexToCenter = [];
  6586. for (let sceneCenters of allCenters) {
  6587. const centerCount = Math.floor(sceneCenters.length / 4);
  6588. for ( let i = 0; i < centerCount; i ++) {
  6589. const base = i * 4;
  6590. const index = Math.round(sceneCenters[base + 3]);
  6591. indexToCenter[index] = base;
  6592. }
  6593. }
  6594. const subTrees = [];
  6595. for (let sceneCenters of allCenters) {
  6596. const subTree = buildSubTree(sceneCenters, maxDepth, maxCentersPerNode);
  6597. subTrees.push(subTree);
  6598. processSplatTreeNode(subTree, subTree.rootNode, indexToCenter, sceneCenters);
  6599. }
  6600. self.postMessage({
  6601. 'subTrees': subTrees
  6602. });
  6603. }
  6604. self.onmessage = (e) => {
  6605. if (e.data.process) {
  6606. createSplatTree(e.data.process.centers, e.data.process.maxDepth, e.data.process.maxCentersPerNode);
  6607. }
  6608. };
  6609. }
  6610. function workerProcessCenters(splatTreeWorker, centers, transferBuffers, maxDepth, maxCentersPerNode) {
  6611. splatTreeWorker.postMessage({
  6612. 'process': {
  6613. 'centers': centers,
  6614. 'maxDepth': maxDepth,
  6615. 'maxCentersPerNode': maxCentersPerNode
  6616. }
  6617. }, transferBuffers);
  6618. }
  6619. function checkAndCreateWorker() {
  6620. const splatTreeWorker = new Worker(
  6621. URL.createObjectURL(
  6622. new Blob(['(', createSplatTreeWorker.toString(), ')(self)'], {
  6623. type: 'application/javascript',
  6624. }),
  6625. ),
  6626. );
  6627. return splatTreeWorker;
  6628. }
  6629. /**
  6630. * SplatTree: Octree tailored to splat data from a SplatMesh instance
  6631. */
  6632. class SplatTree {
  6633. constructor(maxDepth, maxCentersPerNode) {
  6634. this.maxDepth = maxDepth;
  6635. this.maxCentersPerNode = maxCentersPerNode;
  6636. this.subTrees = [];
  6637. this.splatMesh = null;
  6638. }
  6639. dispose() {
  6640. this.diposeSplatTreeWorker();
  6641. this.disposed = true;
  6642. }
  6643. diposeSplatTreeWorker() {
  6644. if (this.splatTreeWorker) this.splatTreeWorker.terminate();
  6645. this.splatTreeWorker = null;
  6646. };
  6647. /**
  6648. * Construct this instance of SplatTree from an instance of SplatMesh.
  6649. *
  6650. * @param {SplatMesh} splatMesh The instance of SplatMesh from which to construct this splat tree.
  6651. * @param {function} filterFunc Optional function to filter out unwanted splats.
  6652. * @param {function} onIndexesUpload Function to be called when the upload of splat centers to the splat tree
  6653. * builder worker starts and finishes.
  6654. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  6655. * the format produced by the splat tree builder worker starts and ends.
  6656. * @return {undefined}
  6657. */
  6658. processSplatMesh = function(splatMesh, filterFunc = () => true, onIndexesUpload, onSplatTreeConstruction) {
  6659. if (!this.splatTreeWorker) this.splatTreeWorker = checkAndCreateWorker();
  6660. this.splatMesh = splatMesh;
  6661. this.subTrees = [];
  6662. const center = new THREE.Vector3();
  6663. const addCentersForScene = (splatOffset, splatCount) => {
  6664. const sceneCenters = new Float32Array(splatCount * 4);
  6665. let addedCount = 0;
  6666. for (let i = 0; i < splatCount; i++) {
  6667. const globalSplatIndex = i + splatOffset;
  6668. if (filterFunc(globalSplatIndex)) {
  6669. splatMesh.getSplatCenter(globalSplatIndex, center);
  6670. const addBase = addedCount * 4;
  6671. sceneCenters[addBase] = center.x;
  6672. sceneCenters[addBase + 1] = center.y;
  6673. sceneCenters[addBase + 2] = center.z;
  6674. sceneCenters[addBase + 3] = globalSplatIndex;
  6675. addedCount++;
  6676. }
  6677. }
  6678. return sceneCenters;
  6679. };
  6680. return new Promise((resolve) => {
  6681. const checkForEarlyExit = () => {
  6682. if (this.disposed) {
  6683. this.diposeSplatTreeWorker();
  6684. resolve();
  6685. return true;
  6686. }
  6687. return false;
  6688. };
  6689. if (onIndexesUpload) onIndexesUpload(false);
  6690. delayedExecute(() => {
  6691. if (checkForEarlyExit()) return;
  6692. const allCenters = [];
  6693. if (splatMesh.dynamicMode) {
  6694. let splatOffset = 0;
  6695. for (let s = 0; s < splatMesh.scenes.length; s++) {
  6696. const scene = splatMesh.getScene(s);
  6697. const splatCount = scene.splatBuffer.getSplatCount();
  6698. const sceneCenters = addCentersForScene(splatOffset, splatCount);
  6699. allCenters.push(sceneCenters);
  6700. splatOffset += splatCount;
  6701. }
  6702. } else {
  6703. const sceneCenters = addCentersForScene(0, splatMesh.getSplatCount());
  6704. allCenters.push(sceneCenters);
  6705. }
  6706. this.splatTreeWorker.onmessage = (e) => {
  6707. if (checkForEarlyExit()) return;
  6708. if (e.data.subTrees) {
  6709. if (onSplatTreeConstruction) onSplatTreeConstruction(false);
  6710. delayedExecute(() => {
  6711. if (checkForEarlyExit()) return;
  6712. for (let workerSubTree of e.data.subTrees) {
  6713. const convertedSubTree = SplatSubTree.convertWorkerSubTree(workerSubTree, splatMesh);
  6714. this.subTrees.push(convertedSubTree);
  6715. }
  6716. this.diposeSplatTreeWorker();
  6717. if (onSplatTreeConstruction) onSplatTreeConstruction(true);
  6718. delayedExecute(() => {
  6719. resolve();
  6720. });
  6721. });
  6722. }
  6723. };
  6724. delayedExecute(() => {
  6725. if (checkForEarlyExit()) return;
  6726. if (onIndexesUpload) onIndexesUpload(true);
  6727. const transferBuffers = allCenters.map((array) => array.buffer);
  6728. workerProcessCenters(this.splatTreeWorker, allCenters, transferBuffers, this.maxDepth, this.maxCentersPerNode);
  6729. });
  6730. });
  6731. });
  6732. };
  6733. countLeaves() {
  6734. let leafCount = 0;
  6735. this.visitLeaves(() => {
  6736. leafCount++;
  6737. });
  6738. return leafCount;
  6739. }
  6740. visitLeaves(visitFunc) {
  6741. const visitLeavesFromNode = (node, visitFunc) => {
  6742. if (node.children.length === 0) visitFunc(node);
  6743. for (let child of node.children) {
  6744. visitLeavesFromNode(child, visitFunc);
  6745. }
  6746. };
  6747. for (let subTree of this.subTrees) {
  6748. visitLeavesFromNode(subTree.rootNode, visitFunc);
  6749. }
  6750. }
  6751. }
  6752. function WebGLExtensions( gl ) {
  6753. const extensions = {};
  6754. function getExtension( name ) {
  6755. if ( extensions[name] !== undefined ) {
  6756. return extensions[name];
  6757. }
  6758. let extension;
  6759. switch ( name ) {
  6760. case 'WEBGL_depth_texture':
  6761. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) ||
  6762. gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  6763. break;
  6764. case 'EXT_texture_filter_anisotropic':
  6765. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  6766. gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  6767. gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  6768. break;
  6769. case 'WEBGL_compressed_texture_s3tc':
  6770. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  6771. gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  6772. gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  6773. break;
  6774. case 'WEBGL_compressed_texture_pvrtc':
  6775. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) ||
  6776. gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  6777. break;
  6778. default:
  6779. extension = gl.getExtension( name );
  6780. }
  6781. extensions[name] = extension;
  6782. return extension;
  6783. }
  6784. return {
  6785. has: function( name ) {
  6786. return getExtension( name ) !== null;
  6787. },
  6788. init: function( capabilities ) {
  6789. if ( capabilities.isWebGL2 ) {
  6790. getExtension( 'EXT_color_buffer_float' );
  6791. getExtension( 'WEBGL_clip_cull_distance' );
  6792. } else {
  6793. getExtension( 'WEBGL_depth_texture' );
  6794. getExtension( 'OES_texture_float' );
  6795. getExtension( 'OES_texture_half_float' );
  6796. getExtension( 'OES_texture_half_float_linear' );
  6797. getExtension( 'OES_standard_derivatives' );
  6798. getExtension( 'OES_element_index_uint' );
  6799. getExtension( 'OES_vertex_array_object' );
  6800. getExtension( 'ANGLE_instanced_arrays' );
  6801. }
  6802. getExtension( 'OES_texture_float_linear' );
  6803. getExtension( 'EXT_color_buffer_half_float' );
  6804. getExtension( 'WEBGL_multisampled_render_to_texture' );
  6805. },
  6806. get: function( name ) {
  6807. const extension = getExtension( name );
  6808. if ( extension === null ) {
  6809. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  6810. }
  6811. return extension;
  6812. }
  6813. };
  6814. }
  6815. function WebGLCapabilities( gl, extensions, parameters ) {
  6816. let maxAnisotropy;
  6817. function getMaxAnisotropy() {
  6818. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  6819. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  6820. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  6821. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  6822. } else {
  6823. maxAnisotropy = 0;
  6824. }
  6825. return maxAnisotropy;
  6826. }
  6827. function getMaxPrecision( precision ) {
  6828. if ( precision === 'highp' ) {
  6829. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  6830. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  6831. return 'highp';
  6832. }
  6833. precision = 'mediump';
  6834. }
  6835. if ( precision === 'mediump' ) {
  6836. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  6837. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  6838. return 'mediump';
  6839. }
  6840. }
  6841. return 'lowp';
  6842. }
  6843. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  6844. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  6845. const maxPrecision = getMaxPrecision( precision );
  6846. if ( maxPrecision !== precision ) {
  6847. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  6848. precision = maxPrecision;
  6849. }
  6850. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  6851. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  6852. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  6853. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  6854. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  6855. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  6856. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  6857. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  6858. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  6859. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  6860. const vertexTextures = maxVertexTextures > 0;
  6861. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  6862. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  6863. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  6864. return {
  6865. isWebGL2: isWebGL2,
  6866. drawBuffers: drawBuffers,
  6867. getMaxAnisotropy: getMaxAnisotropy,
  6868. getMaxPrecision: getMaxPrecision,
  6869. precision: precision,
  6870. logarithmicDepthBuffer: logarithmicDepthBuffer,
  6871. maxTextures: maxTextures,
  6872. maxVertexTextures: maxVertexTextures,
  6873. maxTextureSize: maxTextureSize,
  6874. maxCubemapSize: maxCubemapSize,
  6875. maxAttributes: maxAttributes,
  6876. maxVertexUniforms: maxVertexUniforms,
  6877. maxVaryings: maxVaryings,
  6878. maxFragmentUniforms: maxFragmentUniforms,
  6879. vertexTextures: vertexTextures,
  6880. floatFragmentTextures: floatFragmentTextures,
  6881. floatVertexTextures: floatVertexTextures,
  6882. maxSamples: maxSamples
  6883. };
  6884. }
  6885. const SceneRevealMode = {
  6886. Default: 0,
  6887. Gradual: 1,
  6888. Instant: 2
  6889. };
  6890. const LogLevel = {
  6891. None: 0,
  6892. Error: 1,
  6893. Warning: 2,
  6894. Info: 3,
  6895. Debug: 4
  6896. };
  6897. const dummyGeometry = new THREE.BufferGeometry();
  6898. const dummyMaterial = new THREE.MeshBasicMaterial();
  6899. const COVARIANCES_ELEMENTS_PER_SPLAT = 6;
  6900. const CENTER_COLORS_ELEMENTS_PER_SPLAT = 4;
  6901. const COVARIANCES_ELEMENTS_PER_TEXEL_STORED = 4;
  6902. const COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED = 4;
  6903. const COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED = 6;
  6904. const COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED = 8;
  6905. const SCALES_ROTATIONS_ELEMENTS_PER_TEXEL = 4;
  6906. const CENTER_COLORS_ELEMENTS_PER_TEXEL = 4;
  6907. const SCENE_INDEXES_ELEMENTS_PER_TEXEL = 1;
  6908. const SCENE_FADEIN_RATE_FAST = 0.012;
  6909. const SCENE_FADEIN_RATE_GRADUAL = 0.003;
  6910. const VISIBLE_REGION_EXPANSION_DELTA = 1;
  6911. // Based on my own observations across multiple devices, OSes and browsers, using textures that have one dimension
  6912. // greater than 4096 while the other is greater than or equal to 4096 causes issues (Essentially any texture larger
  6913. // than 4096 x 4096 (16777216) texels). Specifically it seems all texture data beyond the 4096 x 4096 texel boundary
  6914. // is corrupted, while data below that boundary is usable. In these cases the texture has been valid in the eyes of
  6915. // both Three.js and WebGL, and the texel format (RG, RGBA, etc.) has not mattered. More investigation will be needed,
  6916. // but for now the work-around is to split the spherical harmonics into three textures (one for each color channel).
  6917. const MAX_TEXTURE_TEXELS = 16777216;
  6918. /**
  6919. * SplatMesh: Container for one or more splat scenes, abstracting them into a single unified container for
  6920. * splat data. Additionally contains data structures and code to make the splat data renderable as a Three.js mesh.
  6921. */
  6922. class SplatMesh extends THREE.Mesh {
  6923. constructor(splatRenderMode = SplatRenderMode.ThreeD, dynamicMode = false, enableOptionalEffects = false,
  6924. halfPrecisionCovariancesOnGPU = false, devicePixelRatio = 1, enableDistancesComputationOnGPU = true,
  6925. integerBasedDistancesComputation = false, antialiased = false, maxScreenSpaceSplatSize = 1024, logLevel = LogLevel.None,
  6926. sphericalHarmonicsDegree = 0) {
  6927. super(dummyGeometry, dummyMaterial);
  6928. // Reference to a Three.js renderer
  6929. this.renderer = undefined;
  6930. // Determine how the splats are rendered
  6931. this.splatRenderMode = splatRenderMode;
  6932. // When 'dynamicMode' is true, scenes are assumed to be non-static. Dynamic scenes are handled differently
  6933. // and certain optimizations cannot be made for them. Additionally, by default, all splat data retrieved from
  6934. // this splat mesh will not have their scene transform applied to them if the splat mesh is dynamic. That
  6935. // can be overriden via parameters to the individual functions that are used to retrieve splat data.
  6936. this.dynamicMode = dynamicMode;
  6937. // When true, allows for usage of extra properties and attributes during rendering for effects such as opacity adjustment.
  6938. // Default is false for performance reasons. These properties are separate from transform properties (scale, rotation, position)
  6939. // that are enabled by the 'dynamicScene' parameter.
  6940. this.enableOptionalEffects = enableOptionalEffects;
  6941. // Use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit
  6942. this.halfPrecisionCovariancesOnGPU = halfPrecisionCovariancesOnGPU;
  6943. // Ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device
  6944. this.devicePixelRatio = devicePixelRatio;
  6945. // Use a transform feedback to calculate splat distances from the camera
  6946. this.enableDistancesComputationOnGPU = enableDistancesComputationOnGPU;
  6947. // Use a faster integer-based approach for calculating splat distances from the camera
  6948. this.integerBasedDistancesComputation = integerBasedDistancesComputation;
  6949. // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a
  6950. // substantially different resolution than that at which they were rendered during training. This will only work correctly
  6951. // for models that were trained using a process that utilizes this compensation calculation. For more details:
  6952. // https://github.com/nerfstudio-project/gsplat/pull/117
  6953. // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093
  6954. this.antialiased = antialiased;
  6955. // Specify the maximum clip space splat size, can help deal with large splats that get too unwieldy
  6956. this.maxScreenSpaceSplatSize = maxScreenSpaceSplatSize;
  6957. // The verbosity of console logging
  6958. this.logLevel = logLevel;
  6959. // Degree 0 means no spherical harmonics
  6960. this.sphericalHarmonicsDegree = sphericalHarmonicsDegree;
  6961. this.minSphericalHarmonicsDegree = 0;
  6962. // The individual splat scenes stored in this splat mesh, each containing their own transform
  6963. this.scenes = [];
  6964. // Special octree tailored to SplatMesh instances
  6965. this.splatTree = null;
  6966. this.baseSplatTree = null;
  6967. // Cache textures and the intermediate data used to populate them
  6968. this.splatDataTextures = {};
  6969. this.distancesTransformFeedback = {
  6970. 'id': null,
  6971. 'vertexShader': null,
  6972. 'fragmentShader': null,
  6973. 'program': null,
  6974. 'centersBuffer': null,
  6975. 'sceneIndexesBuffer': null,
  6976. 'outDistancesBuffer': null,
  6977. 'centersLoc': -1,
  6978. 'modelViewProjLoc': -1,
  6979. 'sceneIndexesLoc': -1,
  6980. 'transformsLocs': []
  6981. };
  6982. this.globalSplatIndexToLocalSplatIndexMap = [];
  6983. this.globalSplatIndexToSceneIndexMap = [];
  6984. this.lastBuildSplatCount = 0;
  6985. this.lastBuildScenes = [];
  6986. this.lastBuildMaxSplatCount = 0;
  6987. this.lastBuildSceneCount = 0;
  6988. this.firstRenderTime = -1;
  6989. this.finalBuild = false;
  6990. this.webGLUtils = null;
  6991. this.boundingBox = new THREE.Box3();
  6992. this.calculatedSceneCenter = new THREE.Vector3();
  6993. this.maxSplatDistanceFromSceneCenter = 0;
  6994. this.visibleRegionBufferRadius = 0;
  6995. this.visibleRegionRadius = 0;
  6996. this.visibleRegionFadeStartRadius = 0;
  6997. this.visibleRegionChanging = false;
  6998. this.splatScale = 1.0;
  6999. this.pointCloudModeEnabled = false;
  7000. this.disposed = false;
  7001. this.lastRenderer = null;
  7002. this.visible = false;
  7003. }
  7004. /**
  7005. * Build a container for each scene managed by this splat mesh based on an instance of SplatBuffer, along with optional
  7006. * transform data (position, scale, rotation) passed to the splat mesh during the build process.
  7007. * @param {Array<THREE.Matrix4>} splatBuffers SplatBuffer instances containing splats for each scene
  7008. * @param {Array<object>} sceneOptions Array of options objects: {
  7009. *
  7010. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  7011. *
  7012. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  7013. *
  7014. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  7015. * }
  7016. * @return {Array<THREE.Matrix4>}
  7017. */
  7018. static buildScenes(parentObject, splatBuffers, sceneOptions) {
  7019. const scenes = [];
  7020. scenes.length = splatBuffers.length;
  7021. for (let i = 0; i < splatBuffers.length; i++) {
  7022. const splatBuffer = splatBuffers[i];
  7023. const options = sceneOptions[i] || {};
  7024. let positionArray = options['position'] || [0, 0, 0];
  7025. let rotationArray = options['rotation'] || [0, 0, 0, 1];
  7026. let scaleArray = options['scale'] || [1, 1, 1];
  7027. const position = new THREE.Vector3().fromArray(positionArray);
  7028. const rotation = new THREE.Quaternion().fromArray(rotationArray);
  7029. const scale = new THREE.Vector3().fromArray(scaleArray);
  7030. const scene = SplatMesh.createScene(splatBuffer, position, rotation, scale,
  7031. options.splatAlphaRemovalThreshold || 1, options.opacity, options.visible);
  7032. parentObject.add(scene);
  7033. scenes[i] = scene;
  7034. }
  7035. return scenes;
  7036. }
  7037. static createScene(splatBuffer, position, rotation, scale, minimumAlpha, opacity = 1.0, visible = true) {
  7038. return new SplatScene(splatBuffer, position, rotation, scale, minimumAlpha, opacity, visible);
  7039. }
  7040. /**
  7041. * Build data structures that map global splat indexes (based on a unified index across all splat buffers) to
  7042. * local data within a single scene.
  7043. * @param {Array<SplatBuffer>} splatBuffers Instances of SplatBuffer off which to build the maps
  7044. * @return {object}
  7045. */
  7046. static buildSplatIndexMaps(splatBuffers) {
  7047. const localSplatIndexMap = [];
  7048. const sceneIndexMap = [];
  7049. let totalSplatCount = 0;
  7050. for (let s = 0; s < splatBuffers.length; s++) {
  7051. const splatBuffer = splatBuffers[s];
  7052. const maxSplatCount = splatBuffer.getMaxSplatCount();
  7053. for (let i = 0; i < maxSplatCount; i++) {
  7054. localSplatIndexMap[totalSplatCount] = i;
  7055. sceneIndexMap[totalSplatCount] = s;
  7056. totalSplatCount++;
  7057. }
  7058. }
  7059. return {
  7060. localSplatIndexMap,
  7061. sceneIndexMap
  7062. };
  7063. }
  7064. /**
  7065. * Build an instance of SplatTree (a specialized octree) for the given splat mesh.
  7066. * @param {Array<number>} minAlphas Array of minimum splat slphas for each scene
  7067. * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree
  7068. * builder worker starts and finishes.
  7069. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  7070. * the format produced by the splat tree builder worker starts and ends.
  7071. * @return {SplatTree}
  7072. */
  7073. buildSplatTree = function(minAlphas = [], onSplatTreeIndexesUpload, onSplatTreeConstruction) {
  7074. return new Promise((resolve) => {
  7075. this.disposeSplatTree();
  7076. // TODO: expose SplatTree constructor parameters (maximumDepth and maxCentersPerNode) so that they can
  7077. // be configured on a per-scene basis
  7078. this.baseSplatTree = new SplatTree(8, 1000);
  7079. const buildStartTime = performance.now();
  7080. const splatColor = new THREE.Vector4();
  7081. this.baseSplatTree.processSplatMesh(this, (splatIndex) => {
  7082. this.getSplatColor(splatIndex, splatColor);
  7083. const sceneIndex = this.getSceneIndexForSplat(splatIndex);
  7084. const minAlpha = minAlphas[sceneIndex] || 1;
  7085. return splatColor.w >= minAlpha;
  7086. }, onSplatTreeIndexesUpload, onSplatTreeConstruction)
  7087. .then(() => {
  7088. const buildTime = performance.now() - buildStartTime;
  7089. if (this.logLevel >= LogLevel.Info) console.log('SplatTree build: ' + buildTime + ' ms');
  7090. if (this.disposed) {
  7091. resolve();
  7092. } else {
  7093. this.splatTree = this.baseSplatTree;
  7094. this.baseSplatTree = null;
  7095. let leavesWithVertices = 0;
  7096. let avgSplatCount = 0;
  7097. let maxSplatCount = 0;
  7098. let nodeCount = 0;
  7099. this.splatTree.visitLeaves((node) => {
  7100. const nodeSplatCount = node.data.indexes.length;
  7101. if (nodeSplatCount > 0) {
  7102. avgSplatCount += nodeSplatCount;
  7103. maxSplatCount = Math.max(maxSplatCount, nodeSplatCount);
  7104. nodeCount++;
  7105. leavesWithVertices++;
  7106. }
  7107. });
  7108. if (this.logLevel >= LogLevel.Info) {
  7109. console.log(`SplatTree leaves: ${this.splatTree.countLeaves()}`);
  7110. console.log(`SplatTree leaves with splats:${leavesWithVertices}`);
  7111. avgSplatCount = avgSplatCount / nodeCount;
  7112. console.log(`Avg splat count per node: ${avgSplatCount}`);
  7113. console.log(`Total splat count: ${this.getSplatCount()}`);
  7114. }
  7115. resolve();
  7116. }
  7117. });
  7118. });
  7119. };
  7120. /**
  7121. * Construct this instance of SplatMesh.
  7122. * @param {Array<SplatBuffer>} splatBuffers The base splat data, instances of SplatBuffer
  7123. * @param {Array<object>} sceneOptions Dynamic options for each scene {
  7124. *
  7125. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  7126. * value (valid range: 0 - 255), defaults to 1
  7127. *
  7128. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  7129. *
  7130. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  7131. *
  7132. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  7133. *
  7134. * }
  7135. * @param {boolean} keepSceneTransforms For a scene that already exists and is being overwritten, this flag
  7136. * says to keep the transform from the existing scene.
  7137. * @param {boolean} finalBuild Will the splat mesh be in its final state after this build?
  7138. * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree
  7139. * builder worker starts and finishes.
  7140. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  7141. * the format produced by the splat tree builder worker starts and ends.
  7142. * @return {object} Object containing info about the splats that are updated
  7143. */
  7144. build(splatBuffers, sceneOptions, keepSceneTransforms = true, finalBuild = false,
  7145. onSplatTreeIndexesUpload, onSplatTreeConstruction, preserveVisibleRegion = true) {
  7146. this.sceneOptions = sceneOptions;
  7147. this.finalBuild = finalBuild;
  7148. const maxSplatCount = SplatMesh.getTotalMaxSplatCountForSplatBuffers(splatBuffers);
  7149. const newScenes = SplatMesh.buildScenes(this, splatBuffers, sceneOptions);
  7150. if (keepSceneTransforms) {
  7151. for (let i = 0; i < this.scenes.length && i < newScenes.length; i++) {
  7152. const newScene = newScenes[i];
  7153. const existingScene = this.getScene(i);
  7154. newScene.copyTransformData(existingScene);
  7155. }
  7156. }
  7157. this.scenes = newScenes;
  7158. let minSphericalHarmonicsDegree = 3;
  7159. for (let splatBuffer of splatBuffers) {
  7160. const splatBufferSphericalHarmonicsDegree = splatBuffer.getMinSphericalHarmonicsDegree();
  7161. if (splatBufferSphericalHarmonicsDegree < minSphericalHarmonicsDegree) {
  7162. minSphericalHarmonicsDegree = splatBufferSphericalHarmonicsDegree;
  7163. }
  7164. }
  7165. this.minSphericalHarmonicsDegree = Math.min(minSphericalHarmonicsDegree, this.sphericalHarmonicsDegree);
  7166. let splatBuffersChanged = false;
  7167. if (splatBuffers.length !== this.lastBuildScenes.length) {
  7168. splatBuffersChanged = true;
  7169. } else {
  7170. for (let i = 0; i < splatBuffers.length; i++) {
  7171. const splatBuffer = splatBuffers[i];
  7172. if (splatBuffer !== this.lastBuildScenes[i].splatBuffer) {
  7173. splatBuffersChanged = true;
  7174. break;
  7175. }
  7176. }
  7177. }
  7178. let isUpdateBuild = true;
  7179. if (this.scenes.length !== 1 ||
  7180. this.lastBuildSceneCount !== this.scenes.length ||
  7181. this.lastBuildMaxSplatCount !== maxSplatCount ||
  7182. splatBuffersChanged) {
  7183. isUpdateBuild = false;
  7184. }
  7185. if (!isUpdateBuild) {
  7186. this.boundingBox = new THREE.Box3();
  7187. if (!preserveVisibleRegion) {
  7188. this.maxSplatDistanceFromSceneCenter = 0;
  7189. this.visibleRegionBufferRadius = 0;
  7190. this.visibleRegionRadius = 0;
  7191. this.visibleRegionFadeStartRadius = 0;
  7192. this.firstRenderTime = -1;
  7193. }
  7194. this.lastBuildScenes = [];
  7195. this.lastBuildSplatCount = 0;
  7196. this.lastBuildMaxSplatCount = 0;
  7197. this.disposeMeshData();
  7198. this.geometry = SplatGeometry.build(maxSplatCount);
  7199. if (this.splatRenderMode === SplatRenderMode.ThreeD) {
  7200. this.material = SplatMaterial3D.build(this.dynamicMode, this.enableOptionalEffects, this.antialiased,
  7201. this.maxScreenSpaceSplatSize, this.splatScale, this.pointCloudModeEnabled,
  7202. this.minSphericalHarmonicsDegree);
  7203. } else {
  7204. this.material = SplatMaterial2D.build(this.dynamicMode, this.enableOptionalEffects,
  7205. this.splatScale, this.pointCloudModeEnabled, this.minSphericalHarmonicsDegree);
  7206. }
  7207. const indexMaps = SplatMesh.buildSplatIndexMaps(splatBuffers);
  7208. this.globalSplatIndexToLocalSplatIndexMap = indexMaps.localSplatIndexMap;
  7209. this.globalSplatIndexToSceneIndexMap = indexMaps.sceneIndexMap;
  7210. }
  7211. const splatCount = this.getSplatCount();
  7212. if (this.enableDistancesComputationOnGPU) this.setupDistancesComputationTransformFeedback();
  7213. const dataUpdateResults = this.refreshGPUDataFromSplatBuffers(isUpdateBuild);
  7214. for (let i = 0; i < this.scenes.length; i++) {
  7215. this.lastBuildScenes[i] = this.scenes[i];
  7216. }
  7217. this.lastBuildSplatCount = splatCount;
  7218. this.lastBuildMaxSplatCount = this.getMaxSplatCount();
  7219. this.lastBuildSceneCount = this.scenes.length;
  7220. if (finalBuild && this.scenes.length > 0) {
  7221. this.buildSplatTree(sceneOptions.map(options => options.splatAlphaRemovalThreshold || 1),
  7222. onSplatTreeIndexesUpload, onSplatTreeConstruction)
  7223. .then(() => {
  7224. if (this.onSplatTreeReadyCallback) this.onSplatTreeReadyCallback(this.splatTree);
  7225. this.onSplatTreeReadyCallback = null;
  7226. });
  7227. }
  7228. this.visible = (this.scenes.length > 0);
  7229. return dataUpdateResults;
  7230. }
  7231. freeIntermediateSplatData() {
  7232. const deleteTextureData = (texture) => {
  7233. delete texture.source.data;
  7234. delete texture.image;
  7235. texture.onUpdate = null;
  7236. };
  7237. delete this.splatDataTextures.baseData.covariances;
  7238. delete this.splatDataTextures.baseData.centers;
  7239. delete this.splatDataTextures.baseData.colors;
  7240. delete this.splatDataTextures.baseData.sphericalHarmonics;
  7241. delete this.splatDataTextures.centerColors.data;
  7242. delete this.splatDataTextures.covariances.data;
  7243. if (this.splatDataTextures.sphericalHarmonics) {
  7244. delete this.splatDataTextures.sphericalHarmonics.data;
  7245. }
  7246. if (this.splatDataTextures.sceneIndexes) {
  7247. delete this.splatDataTextures.sceneIndexes.data;
  7248. }
  7249. this.splatDataTextures.centerColors.texture.needsUpdate = true;
  7250. this.splatDataTextures.centerColors.texture.onUpdate = () => {
  7251. deleteTextureData(this.splatDataTextures.centerColors.texture);
  7252. };
  7253. this.splatDataTextures.covariances.texture.needsUpdate = true;
  7254. this.splatDataTextures.covariances.texture.onUpdate = () => {
  7255. deleteTextureData(this.splatDataTextures.covariances.texture);
  7256. };
  7257. if (this.splatDataTextures.sphericalHarmonics) {
  7258. if (this.splatDataTextures.sphericalHarmonics.texture) {
  7259. this.splatDataTextures.sphericalHarmonics.texture.needsUpdate = true;
  7260. this.splatDataTextures.sphericalHarmonics.texture.onUpdate = () => {
  7261. deleteTextureData(this.splatDataTextures.sphericalHarmonics.texture);
  7262. };
  7263. } else {
  7264. this.splatDataTextures.sphericalHarmonics.textures.forEach((texture) => {
  7265. texture.needsUpdate = true;
  7266. texture.onUpdate = () => {
  7267. deleteTextureData(texture);
  7268. };
  7269. });
  7270. }
  7271. }
  7272. if (this.splatDataTextures.sceneIndexes) {
  7273. this.splatDataTextures.sceneIndexes.texture.needsUpdate = true;
  7274. this.splatDataTextures.sceneIndexes.texture.onUpdate = () => {
  7275. deleteTextureData(this.splatDataTextures.sceneIndexes.texture);
  7276. };
  7277. }
  7278. }
  7279. /**
  7280. * Dispose all resources held by the splat mesh
  7281. */
  7282. dispose() {
  7283. this.disposeMeshData();
  7284. this.disposeTextures();
  7285. this.disposeSplatTree();
  7286. if (this.enableDistancesComputationOnGPU) {
  7287. if (this.computeDistancesOnGPUSyncTimeout) {
  7288. clearTimeout(this.computeDistancesOnGPUSyncTimeout);
  7289. this.computeDistancesOnGPUSyncTimeout = null;
  7290. }
  7291. this.disposeDistancesComputationGPUResources();
  7292. }
  7293. this.scenes = [];
  7294. this.distancesTransformFeedback = {
  7295. 'id': null,
  7296. 'vertexShader': null,
  7297. 'fragmentShader': null,
  7298. 'program': null,
  7299. 'centersBuffer': null,
  7300. 'sceneIndexesBuffer': null,
  7301. 'outDistancesBuffer': null,
  7302. 'centersLoc': -1,
  7303. 'modelViewProjLoc': -1,
  7304. 'sceneIndexesLoc': -1,
  7305. 'transformsLocs': []
  7306. };
  7307. this.renderer = null;
  7308. this.globalSplatIndexToLocalSplatIndexMap = [];
  7309. this.globalSplatIndexToSceneIndexMap = [];
  7310. this.lastBuildSplatCount = 0;
  7311. this.lastBuildScenes = [];
  7312. this.lastBuildMaxSplatCount = 0;
  7313. this.lastBuildSceneCount = 0;
  7314. this.firstRenderTime = -1;
  7315. this.finalBuild = false;
  7316. this.webGLUtils = null;
  7317. this.boundingBox = new THREE.Box3();
  7318. this.calculatedSceneCenter = new THREE.Vector3();
  7319. this.maxSplatDistanceFromSceneCenter = 0;
  7320. this.visibleRegionBufferRadius = 0;
  7321. this.visibleRegionRadius = 0;
  7322. this.visibleRegionFadeStartRadius = 0;
  7323. this.visibleRegionChanging = false;
  7324. this.splatScale = 1.0;
  7325. this.pointCloudModeEnabled = false;
  7326. this.disposed = true;
  7327. this.lastRenderer = null;
  7328. this.visible = false;
  7329. }
  7330. /**
  7331. * Dispose of only the Three.js mesh resources (geometry, material, and texture)
  7332. */
  7333. disposeMeshData() {
  7334. if (this.geometry && this.geometry !== dummyGeometry) {
  7335. this.geometry.dispose();
  7336. this.geometry = null;
  7337. }
  7338. if (this.material) {
  7339. this.material.dispose();
  7340. this.material = null;
  7341. }
  7342. }
  7343. disposeTextures() {
  7344. for (let textureKey in this.splatDataTextures) {
  7345. if (this.splatDataTextures.hasOwnProperty(textureKey)) {
  7346. const textureContainer = this.splatDataTextures[textureKey];
  7347. if (textureContainer.texture) {
  7348. textureContainer.texture.dispose();
  7349. textureContainer.texture = null;
  7350. }
  7351. }
  7352. }
  7353. this.splatDataTextures = null;
  7354. }
  7355. disposeSplatTree() {
  7356. if (this.splatTree) {
  7357. this.splatTree.dispose();
  7358. this.splatTree = null;
  7359. }
  7360. if (this.baseSplatTree) {
  7361. this.baseSplatTree.dispose();
  7362. this.baseSplatTree = null;
  7363. }
  7364. }
  7365. getSplatTree() {
  7366. return this.splatTree;
  7367. }
  7368. onSplatTreeReady(callback) {
  7369. this.onSplatTreeReadyCallback = callback;
  7370. }
  7371. /**
  7372. * Get copies of data that are necessary for splat distance computation: splat center positions and splat
  7373. * scene indexes (necessary for applying dynamic scene transformations during distance computation)
  7374. * @param {*} start The index at which to start copying data
  7375. * @param {*} end The index at which to stop copying data
  7376. * @return {object}
  7377. */
  7378. getDataForDistancesComputation(start, end) {
  7379. const centers = this.integerBasedDistancesComputation ?
  7380. this.getIntegerCenters(start, end, true) :
  7381. this.getFloatCenters(start, end, true);
  7382. const sceneIndexes = this.getSceneIndexes(start, end);
  7383. return {
  7384. centers,
  7385. sceneIndexes
  7386. };
  7387. }
  7388. /**
  7389. * Refresh data textures and GPU buffers with splat data from the splat buffers belonging to this mesh.
  7390. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  7391. * @return {object}
  7392. */
  7393. refreshGPUDataFromSplatBuffers(sinceLastBuildOnly) {
  7394. const splatCount = this.getSplatCount();
  7395. this.refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly);
  7396. const updateStart = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  7397. const { centers, sceneIndexes } = this.getDataForDistancesComputation(updateStart, splatCount - 1);
  7398. if (this.enableDistancesComputationOnGPU) {
  7399. this.refreshGPUBuffersForDistancesComputation(centers, sceneIndexes, sinceLastBuildOnly);
  7400. }
  7401. return {
  7402. 'from': updateStart,
  7403. 'to': splatCount - 1,
  7404. 'count': splatCount - updateStart,
  7405. 'centers': centers,
  7406. 'sceneIndexes': sceneIndexes
  7407. };
  7408. }
  7409. /**
  7410. * Update the GPU buffers that are used for computing splat distances on the GPU.
  7411. * @param {Array<number>} centers Splat center positions
  7412. * @param {Array<number>} sceneIndexes Indexes of the scene to which each splat belongs
  7413. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  7414. */
  7415. refreshGPUBuffersForDistancesComputation(centers, sceneIndexes, sinceLastBuildOnly = false) {
  7416. const offset = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  7417. this.updateGPUCentersBufferForDistancesComputation(sinceLastBuildOnly, centers, offset);
  7418. this.updateGPUTransformIndexesBufferForDistancesComputation(sinceLastBuildOnly, sceneIndexes, offset);
  7419. }
  7420. /**
  7421. * Refresh data textures with data from the splat buffers for this mesh.
  7422. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  7423. */
  7424. refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly) {
  7425. const splatCount = this.getSplatCount();
  7426. const fromSplat = this.lastBuildSplatCount;
  7427. const toSplat = splatCount - 1;
  7428. if (!sinceLastBuildOnly) {
  7429. this.setupDataTextures();
  7430. this.updateBaseDataFromSplatBuffers();
  7431. } else {
  7432. this.updateBaseDataFromSplatBuffers(fromSplat, toSplat);
  7433. }
  7434. this.updateDataTexturesFromBaseData(fromSplat, toSplat);
  7435. this.updateVisibleRegion(sinceLastBuildOnly);
  7436. }
  7437. setupDataTextures() {
  7438. const maxSplatCount = this.getMaxSplatCount();
  7439. const splatCount = this.getSplatCount();
  7440. this.disposeTextures();
  7441. const computeDataTextureSize = (elementsPerTexel, elementsPerSplat) => {
  7442. const texSize = new THREE.Vector2(4096, 1024);
  7443. while (texSize.x * texSize.y * elementsPerTexel < maxSplatCount * elementsPerSplat) texSize.y *= 2;
  7444. return texSize;
  7445. };
  7446. const getCovariancesElementsPertexelStored = (compressionLevel) => {
  7447. return compressionLevel >= 1 ? COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED : COVARIANCES_ELEMENTS_PER_TEXEL_STORED;
  7448. };
  7449. const getCovariancesInitialTextureSpecs = (compressionLevel) => {
  7450. const elementsPerTexelStored = getCovariancesElementsPertexelStored(compressionLevel);
  7451. const texSize = computeDataTextureSize(elementsPerTexelStored, 6);
  7452. return {elementsPerTexelStored, texSize};
  7453. };
  7454. let covarianceCompressionLevel = this.getTargetCovarianceCompressionLevel();
  7455. const scaleRotationCompressionLevel = 0;
  7456. const shCompressionLevel = this.getTargetSphericalHarmonicsCompressionLevel();
  7457. let covariances;
  7458. let scales;
  7459. let rotations;
  7460. if (this.splatRenderMode === SplatRenderMode.ThreeD) {
  7461. const initialCovTexSpecs = getCovariancesInitialTextureSpecs(covarianceCompressionLevel);
  7462. if (initialCovTexSpecs.texSize.x * initialCovTexSpecs.texSize.y > MAX_TEXTURE_TEXELS && covarianceCompressionLevel === 0) {
  7463. covarianceCompressionLevel = 1;
  7464. }
  7465. covariances = new Float32Array(maxSplatCount * COVARIANCES_ELEMENTS_PER_SPLAT);
  7466. } else {
  7467. scales = new Float32Array(maxSplatCount * 3);
  7468. rotations = new Float32Array(maxSplatCount * 4);
  7469. }
  7470. const centers = new Float32Array(maxSplatCount * 3);
  7471. const colors = new Uint8Array(maxSplatCount * 4);
  7472. let SphericalHarmonicsArrayType = Float32Array;
  7473. if (shCompressionLevel === 1) SphericalHarmonicsArrayType = Uint16Array;
  7474. else if (shCompressionLevel === 2) SphericalHarmonicsArrayType = Uint8Array;
  7475. const shComponentCount = getSphericalHarmonicsComponentCountForDegree(this.minSphericalHarmonicsDegree);
  7476. const shData = this.minSphericalHarmonicsDegree ? new SphericalHarmonicsArrayType(maxSplatCount * shComponentCount) : undefined;
  7477. // set up centers/colors data texture
  7478. const centersColsTexSize = computeDataTextureSize(CENTER_COLORS_ELEMENTS_PER_TEXEL, 4);
  7479. const paddedCentersCols = new Uint32Array(centersColsTexSize.x * centersColsTexSize.y * CENTER_COLORS_ELEMENTS_PER_TEXEL);
  7480. SplatMesh.updateCenterColorsPaddedData(0, splatCount - 1, centers, colors, paddedCentersCols);
  7481. const centersColsTex = new THREE.DataTexture(paddedCentersCols, centersColsTexSize.x, centersColsTexSize.y,
  7482. THREE.RGBAIntegerFormat, THREE.UnsignedIntType);
  7483. centersColsTex.internalFormat = 'RGBA32UI';
  7484. centersColsTex.needsUpdate = true;
  7485. this.material.uniforms.centersColorsTexture.value = centersColsTex;
  7486. this.material.uniforms.centersColorsTextureSize.value.copy(centersColsTexSize);
  7487. this.material.uniformsNeedUpdate = true;
  7488. this.splatDataTextures = {
  7489. 'baseData': {
  7490. 'covariances': covariances,
  7491. 'scales': scales,
  7492. 'rotations': rotations,
  7493. 'centers': centers,
  7494. 'colors': colors,
  7495. 'sphericalHarmonics': shData
  7496. },
  7497. 'centerColors': {
  7498. 'data': paddedCentersCols,
  7499. 'texture': centersColsTex,
  7500. 'size': centersColsTexSize
  7501. }
  7502. };
  7503. if (this.splatRenderMode === SplatRenderMode.ThreeD) {
  7504. // set up covariances data texture
  7505. const covTexSpecs = getCovariancesInitialTextureSpecs(covarianceCompressionLevel);
  7506. const covariancesElementsPerTexelStored = covTexSpecs.elementsPerTexelStored;
  7507. const covTexSize = covTexSpecs.texSize;
  7508. let CovariancesDataType = covarianceCompressionLevel >= 1 ? Uint32Array : Float32Array;
  7509. const covariancesElementsPerTexelAllocated = covarianceCompressionLevel >= 1 ?
  7510. COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED :
  7511. COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED;
  7512. const covariancesTextureData = new CovariancesDataType(covTexSize.x * covTexSize.y * covariancesElementsPerTexelAllocated);
  7513. if (covarianceCompressionLevel === 0) {
  7514. covariancesTextureData.set(covariances);
  7515. } else {
  7516. SplatMesh.updatePaddedCompressedCovariancesTextureData(covariances, covariancesTextureData, 0, 0, covariances.length);
  7517. }
  7518. let covTex;
  7519. if (covarianceCompressionLevel >= 1) {
  7520. covTex = new THREE.DataTexture(covariancesTextureData, covTexSize.x, covTexSize.y,
  7521. THREE.RGBAIntegerFormat, THREE.UnsignedIntType);
  7522. covTex.internalFormat = 'RGBA32UI';
  7523. this.material.uniforms.covariancesTextureHalfFloat.value = covTex;
  7524. } else {
  7525. covTex = new THREE.DataTexture(covariancesTextureData, covTexSize.x, covTexSize.y, THREE.RGBAFormat, THREE.FloatType);
  7526. this.material.uniforms.covariancesTexture.value = covTex;
  7527. // For some reason a usampler2D needs to have a valid texture attached or WebGL complains
  7528. const dummyTex = new THREE.DataTexture(new Uint32Array(32), 2, 2, THREE.RGBAIntegerFormat, THREE.UnsignedIntType);
  7529. dummyTex.internalFormat = 'RGBA32UI';
  7530. this.material.uniforms.covariancesTextureHalfFloat.value = dummyTex;
  7531. dummyTex.needsUpdate = true;
  7532. }
  7533. covTex.needsUpdate = true;
  7534. this.material.uniforms.covariancesAreHalfFloat.value = (covarianceCompressionLevel >= 1) ? 1 : 0;
  7535. this.material.uniforms.covariancesTextureSize.value.copy(covTexSize);
  7536. this.splatDataTextures['covariances'] = {
  7537. 'data': covariancesTextureData,
  7538. 'texture': covTex,
  7539. 'size': covTexSize,
  7540. 'compressionLevel': covarianceCompressionLevel,
  7541. 'elementsPerTexelStored': covariancesElementsPerTexelStored,
  7542. 'elementsPerTexelAllocated': covariancesElementsPerTexelAllocated
  7543. };
  7544. } else {
  7545. // set up scale & rotations data texture
  7546. const elementsPerSplat = 6;
  7547. const scaleRotationsTexSize = computeDataTextureSize(SCALES_ROTATIONS_ELEMENTS_PER_TEXEL, elementsPerSplat);
  7548. let ScaleRotationsDataType = scaleRotationCompressionLevel >= 1 ? Uint16Array : Float32Array;
  7549. let scaleRotationsTextureType = scaleRotationCompressionLevel >= 1 ? THREE.HalfFloatType : THREE.FloatType;
  7550. const paddedScaleRotations = new ScaleRotationsDataType(scaleRotationsTexSize.x * scaleRotationsTexSize.y *
  7551. SCALES_ROTATIONS_ELEMENTS_PER_TEXEL);
  7552. SplatMesh.updateScaleRotationsPaddedData(0, splatCount - 1, scales, rotations, paddedScaleRotations);
  7553. const scaleRotationsTex = new THREE.DataTexture(paddedScaleRotations, scaleRotationsTexSize.x, scaleRotationsTexSize.y,
  7554. THREE.RGBAFormat, scaleRotationsTextureType);
  7555. scaleRotationsTex.needsUpdate = true;
  7556. this.material.uniforms.scaleRotationsTexture.value = scaleRotationsTex;
  7557. this.material.uniforms.scaleRotationsTextureSize.value.copy(scaleRotationsTexSize);
  7558. this.splatDataTextures['scaleRotations'] = {
  7559. 'data': paddedScaleRotations,
  7560. 'texture': scaleRotationsTex,
  7561. 'size': scaleRotationsTexSize,
  7562. 'compressionLevel': scaleRotationCompressionLevel
  7563. };
  7564. }
  7565. if (shData) {
  7566. const shTextureType = shCompressionLevel === 2 ? THREE.UnsignedByteType : THREE.HalfFloatType;
  7567. let paddedSHComponentCount = shComponentCount;
  7568. if (paddedSHComponentCount % 2 !== 0) paddedSHComponentCount++;
  7569. const shElementsPerTexel = this.minSphericalHarmonicsDegree === 2 ? 4 : 2;
  7570. const texelFormat = shElementsPerTexel === 4 ? THREE.RGBAFormat : THREE.RGFormat;
  7571. let shTexSize = computeDataTextureSize(shElementsPerTexel, paddedSHComponentCount);
  7572. // Use one texture for all spherical harmonics data
  7573. if (shTexSize.x * shTexSize.y <= MAX_TEXTURE_TEXELS) {
  7574. const paddedSHArraySize = shTexSize.x * shTexSize.y * shElementsPerTexel;
  7575. const paddedSHArray = new SphericalHarmonicsArrayType(paddedSHArraySize);
  7576. for (let c = 0; c < splatCount; c++) {
  7577. const srcBase = shComponentCount * c;
  7578. const destBase = paddedSHComponentCount * c;
  7579. for (let i = 0; i < shComponentCount; i++) {
  7580. paddedSHArray[destBase + i] = shData[srcBase + i];
  7581. }
  7582. }
  7583. const shTexture = new THREE.DataTexture(paddedSHArray, shTexSize.x, shTexSize.y, texelFormat, shTextureType);
  7584. shTexture.needsUpdate = true;
  7585. this.material.uniforms.sphericalHarmonicsTexture.value = shTexture;
  7586. this.splatDataTextures['sphericalHarmonics'] = {
  7587. 'componentCount': shComponentCount,
  7588. 'paddedComponentCount': paddedSHComponentCount,
  7589. 'data': paddedSHArray,
  7590. 'textureCount': 1,
  7591. 'texture': shTexture,
  7592. 'size': shTexSize,
  7593. 'compressionLevel': shCompressionLevel,
  7594. 'elementsPerTexel': shElementsPerTexel
  7595. };
  7596. // Use three textures for spherical harmonics data, one per color channel
  7597. } else {
  7598. const shComponentCountPerChannel = shComponentCount / 3;
  7599. paddedSHComponentCount = shComponentCountPerChannel;
  7600. if (paddedSHComponentCount % 2 !== 0) paddedSHComponentCount++;
  7601. shTexSize = computeDataTextureSize(shElementsPerTexel, paddedSHComponentCount);
  7602. const paddedSHArraySize = shTexSize.x * shTexSize.y * shElementsPerTexel;
  7603. const textureUniforms = [this.material.uniforms.sphericalHarmonicsTextureR,
  7604. this.material.uniforms.sphericalHarmonicsTextureG,
  7605. this.material.uniforms.sphericalHarmonicsTextureB];
  7606. const paddedSHArrays = [];
  7607. const shTextures = [];
  7608. for (let t = 0; t < 3; t++) {
  7609. const paddedSHArray = new SphericalHarmonicsArrayType(paddedSHArraySize);
  7610. paddedSHArrays.push(paddedSHArray);
  7611. for (let c = 0; c < splatCount; c++) {
  7612. const srcBase = shComponentCount * c;
  7613. const destBase = paddedSHComponentCount * c;
  7614. if (shComponentCountPerChannel >= 3) {
  7615. for (let i = 0; i < 3; i++) paddedSHArray[destBase + i] = shData[srcBase + t * 3 + i];
  7616. if (shComponentCountPerChannel >= 8) {
  7617. for (let i = 0; i < 5; i++) paddedSHArray[destBase + 3 + i] = shData[srcBase + 9 + t * 5 + i];
  7618. }
  7619. }
  7620. }
  7621. const shTexture = new THREE.DataTexture(paddedSHArray, shTexSize.x, shTexSize.y, texelFormat, shTextureType);
  7622. shTextures.push(shTexture);
  7623. shTexture.needsUpdate = true;
  7624. textureUniforms[t].value = shTexture;
  7625. }
  7626. this.material.uniforms.sphericalHarmonicsMultiTextureMode.value = 1;
  7627. this.splatDataTextures['sphericalHarmonics'] = {
  7628. 'componentCount': shComponentCount,
  7629. 'componentCountPerChannel': shComponentCountPerChannel,
  7630. 'paddedComponentCount': paddedSHComponentCount,
  7631. 'data': paddedSHArrays,
  7632. 'textureCount': 3,
  7633. 'textures': shTextures,
  7634. 'size': shTexSize,
  7635. 'compressionLevel': shCompressionLevel,
  7636. 'elementsPerTexel': shElementsPerTexel
  7637. };
  7638. }
  7639. this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(shTexSize);
  7640. this.material.uniforms.sphericalHarmonics8BitMode.value = shCompressionLevel === 2 ? 1 : 0;
  7641. for (let s = 0; s < this.scenes.length; s++) {
  7642. const splatBuffer = this.scenes[s].splatBuffer;
  7643. this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[s] =
  7644. splatBuffer.minSphericalHarmonicsCoeff;
  7645. this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[s] =
  7646. splatBuffer.maxSphericalHarmonicsCoeff;
  7647. }
  7648. this.material.uniformsNeedUpdate = true;
  7649. }
  7650. const sceneIndexesTexSize = computeDataTextureSize(SCENE_INDEXES_ELEMENTS_PER_TEXEL, 4);
  7651. const paddedTransformIndexes = new Uint32Array(sceneIndexesTexSize.x *
  7652. sceneIndexesTexSize.y * SCENE_INDEXES_ELEMENTS_PER_TEXEL);
  7653. for (let c = 0; c < splatCount; c++) paddedTransformIndexes[c] = this.globalSplatIndexToSceneIndexMap[c];
  7654. const sceneIndexesTexture = new THREE.DataTexture(paddedTransformIndexes, sceneIndexesTexSize.x, sceneIndexesTexSize.y,
  7655. THREE.RedIntegerFormat, THREE.UnsignedIntType);
  7656. sceneIndexesTexture.internalFormat = 'R32UI';
  7657. sceneIndexesTexture.needsUpdate = true;
  7658. this.material.uniforms.sceneIndexesTexture.value = sceneIndexesTexture;
  7659. this.material.uniforms.sceneIndexesTextureSize.value.copy(sceneIndexesTexSize);
  7660. this.material.uniformsNeedUpdate = true;
  7661. this.splatDataTextures['sceneIndexes'] = {
  7662. 'data': paddedTransformIndexes,
  7663. 'texture': sceneIndexesTexture,
  7664. 'size': sceneIndexesTexSize
  7665. };
  7666. this.material.uniforms.sceneCount.value = this.scenes.length;
  7667. }
  7668. updateBaseDataFromSplatBuffers(fromSplat, toSplat) {
  7669. const covarancesTextureDesc = this.splatDataTextures['covariances'];
  7670. const covarianceCompressionLevel = covarancesTextureDesc ? covarancesTextureDesc.compressionLevel : undefined;
  7671. const scaleRotationsTextureDesc = this.splatDataTextures['scaleRotations'];
  7672. const scaleRotationCompressionLevel = scaleRotationsTextureDesc ? scaleRotationsTextureDesc.compressionLevel : undefined;
  7673. const shITextureDesc = this.splatDataTextures['sphericalHarmonics'];
  7674. const shCompressionLevel = shITextureDesc ? shITextureDesc.compressionLevel : 0;
  7675. this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances, this.splatDataTextures.baseData.scales,
  7676. this.splatDataTextures.baseData.rotations, this.splatDataTextures.baseData.centers,
  7677. this.splatDataTextures.baseData.colors, this.splatDataTextures.baseData.sphericalHarmonics, undefined,
  7678. covarianceCompressionLevel, scaleRotationCompressionLevel, shCompressionLevel,
  7679. fromSplat, toSplat, fromSplat);
  7680. }
  7681. updateDataTexturesFromBaseData(fromSplat, toSplat) {
  7682. const covarancesTextureDesc = this.splatDataTextures['covariances'];
  7683. const covarianceCompressionLevel = covarancesTextureDesc ? covarancesTextureDesc.compressionLevel : undefined;
  7684. const scaleRotationsTextureDesc = this.splatDataTextures['scaleRotations'];
  7685. const scaleRotationCompressionLevel = scaleRotationsTextureDesc ? scaleRotationsTextureDesc.compressionLevel : undefined;
  7686. const shTextureDesc = this.splatDataTextures['sphericalHarmonics'];
  7687. const shCompressionLevel = shTextureDesc ? shTextureDesc.compressionLevel : 0;
  7688. // Update center & color data texture
  7689. const centerColorsTextureDescriptor = this.splatDataTextures['centerColors'];
  7690. const paddedCenterColors = centerColorsTextureDescriptor.data;
  7691. const centerColorsTexture = centerColorsTextureDescriptor.texture;
  7692. SplatMesh.updateCenterColorsPaddedData(fromSplat, toSplat, this.splatDataTextures.baseData.centers,
  7693. this.splatDataTextures.baseData.colors, paddedCenterColors);
  7694. const centerColorsTextureProps = this.renderer ? this.renderer.properties.get(centerColorsTexture) : null;
  7695. if (!centerColorsTextureProps || !centerColorsTextureProps.__webglTexture) {
  7696. centerColorsTexture.needsUpdate = true;
  7697. } else {
  7698. this.updateDataTexture(paddedCenterColors, centerColorsTextureDescriptor.texture, centerColorsTextureDescriptor.size,
  7699. centerColorsTextureProps, CENTER_COLORS_ELEMENTS_PER_TEXEL, CENTER_COLORS_ELEMENTS_PER_SPLAT, 4,
  7700. fromSplat, toSplat);
  7701. }
  7702. // update covariance data texture
  7703. if (covarancesTextureDesc) {
  7704. const covariancesTexture = covarancesTextureDesc.texture;
  7705. const covarancesStartElement = fromSplat * COVARIANCES_ELEMENTS_PER_SPLAT;
  7706. const covariancesEndElement = toSplat * COVARIANCES_ELEMENTS_PER_SPLAT;
  7707. if (covarianceCompressionLevel === 0) {
  7708. for (let i = covarancesStartElement; i <= covariancesEndElement; i++) {
  7709. const covariance = this.splatDataTextures.baseData.covariances[i];
  7710. covarancesTextureDesc.data[i] = covariance;
  7711. }
  7712. } else {
  7713. SplatMesh.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,
  7714. covarancesTextureDesc.data,
  7715. fromSplat * covarancesTextureDesc.elementsPerTexelAllocated,
  7716. covarancesStartElement, covariancesEndElement);
  7717. }
  7718. const covariancesTextureProps = this.renderer ? this.renderer.properties.get(covariancesTexture) : null;
  7719. if (!covariancesTextureProps || !covariancesTextureProps.__webglTexture) {
  7720. covariancesTexture.needsUpdate = true;
  7721. } else {
  7722. if (covarianceCompressionLevel === 0) {
  7723. this.updateDataTexture(covarancesTextureDesc.data, covarancesTextureDesc.texture, covarancesTextureDesc.size,
  7724. covariancesTextureProps, covarancesTextureDesc.elementsPerTexelStored,
  7725. COVARIANCES_ELEMENTS_PER_SPLAT, 4, fromSplat, toSplat);
  7726. } else {
  7727. this.updateDataTexture(covarancesTextureDesc.data, covarancesTextureDesc.texture, covarancesTextureDesc.size,
  7728. covariancesTextureProps, covarancesTextureDesc.elementsPerTexelAllocated,
  7729. covarancesTextureDesc.elementsPerTexelAllocated, 2, fromSplat, toSplat);
  7730. }
  7731. }
  7732. }
  7733. // update scale and rotation data texture
  7734. if (scaleRotationsTextureDesc) {
  7735. const paddedScaleRotations = scaleRotationsTextureDesc.data;
  7736. const scaleRotationsTexture = scaleRotationsTextureDesc.texture;
  7737. const elementsPerSplat = 6;
  7738. const bytesPerElement = scaleRotationCompressionLevel === 0 ? 4 : 2;
  7739. SplatMesh.updateScaleRotationsPaddedData(fromSplat, toSplat, this.splatDataTextures.baseData.scales,
  7740. this.splatDataTextures.baseData.rotations, paddedScaleRotations);
  7741. const scaleRotationsTextureProps = this.renderer ? this.renderer.properties.get(scaleRotationsTexture) : null;
  7742. if (!scaleRotationsTextureProps || !scaleRotationsTextureProps.__webglTexture) {
  7743. scaleRotationsTexture.needsUpdate = true;
  7744. } else {
  7745. this.updateDataTexture(paddedScaleRotations, scaleRotationsTextureDesc.texture, scaleRotationsTextureDesc.size,
  7746. scaleRotationsTextureProps, SCALES_ROTATIONS_ELEMENTS_PER_TEXEL, elementsPerSplat, bytesPerElement,
  7747. fromSplat, toSplat);
  7748. }
  7749. }
  7750. // update spherical harmonics data texture
  7751. const shData = this.splatDataTextures.baseData.sphericalHarmonics;
  7752. if (shData) {
  7753. let shBytesPerElement = 4;
  7754. if (shCompressionLevel === 1) shBytesPerElement = 2;
  7755. else if (shCompressionLevel === 2) shBytesPerElement = 1;
  7756. const updateTexture = (shTexture, shTextureSize, elementsPerTexel, paddedSHArray, paddedSHComponentCount) => {
  7757. const shTextureProps = this.renderer ? this.renderer.properties.get(shTexture) : null;
  7758. if (!shTextureProps || !shTextureProps.__webglTexture) {
  7759. shTexture.needsUpdate = true;
  7760. } else {
  7761. this.updateDataTexture(paddedSHArray, shTexture, shTextureSize, shTextureProps, elementsPerTexel,
  7762. paddedSHComponentCount, shBytesPerElement, fromSplat, toSplat);
  7763. }
  7764. };
  7765. const shComponentCount = shTextureDesc.componentCount;
  7766. const paddedSHComponentCount = shTextureDesc.paddedComponentCount;
  7767. // Update for the case of a single texture for all spherical harmonics data
  7768. if (shTextureDesc.textureCount === 1) {
  7769. const paddedSHArray = shTextureDesc.data;
  7770. for (let c = fromSplat; c <= toSplat; c++) {
  7771. const srcBase = shComponentCount * c;
  7772. const destBase = paddedSHComponentCount * c;
  7773. for (let i = 0; i < shComponentCount; i++) {
  7774. paddedSHArray[destBase + i] = shData[srcBase + i];
  7775. }
  7776. }
  7777. updateTexture(shTextureDesc.texture, shTextureDesc.size,
  7778. shTextureDesc.elementsPerTexel, paddedSHArray, paddedSHComponentCount);
  7779. // Update for the case of spherical harmonics data split among three textures, one for each color channel
  7780. } else {
  7781. const shComponentCountPerChannel = shTextureDesc.componentCountPerChannel;
  7782. for (let t = 0; t < 3; t++) {
  7783. const paddedSHArray = shTextureDesc.data[t];
  7784. for (let c = fromSplat; c <= toSplat; c++) {
  7785. const srcBase = shComponentCount * c;
  7786. const destBase = paddedSHComponentCount * c;
  7787. if (shComponentCountPerChannel >= 3) {
  7788. for (let i = 0; i < 3; i++) paddedSHArray[destBase + i] = shData[srcBase + t * 3 + i];
  7789. if (shComponentCountPerChannel >= 8) {
  7790. for (let i = 0; i < 5; i++) paddedSHArray[destBase + 3 + i] = shData[srcBase + 9 + t * 5 + i];
  7791. }
  7792. }
  7793. }
  7794. updateTexture(shTextureDesc.textures[t], shTextureDesc.size,
  7795. shTextureDesc.elementsPerTexel, paddedSHArray, paddedSHComponentCount);
  7796. }
  7797. }
  7798. }
  7799. // update scene index & transform data
  7800. const sceneIndexesTexDesc = this.splatDataTextures['sceneIndexes'];
  7801. const paddedSceneIndexes = sceneIndexesTexDesc.data;
  7802. for (let c = this.lastBuildSplatCount; c <= toSplat; c++) {
  7803. paddedSceneIndexes[c] = this.globalSplatIndexToSceneIndexMap[c];
  7804. }
  7805. const sceneIndexesTexture = sceneIndexesTexDesc.texture;
  7806. const sceneIndexesTextureProps = this.renderer ? this.renderer.properties.get(sceneIndexesTexture) : null;
  7807. if (!sceneIndexesTextureProps || !sceneIndexesTextureProps.__webglTexture) {
  7808. sceneIndexesTexture.needsUpdate = true;
  7809. } else {
  7810. this.updateDataTexture(paddedSceneIndexes, sceneIndexesTexDesc.texture, sceneIndexesTexDesc.size,
  7811. sceneIndexesTextureProps, 1, 1, 1, this.lastBuildSplatCount, toSplat);
  7812. }
  7813. }
  7814. getTargetCovarianceCompressionLevel() {
  7815. return this.halfPrecisionCovariancesOnGPU ? 1 : 0;
  7816. }
  7817. getTargetSphericalHarmonicsCompressionLevel() {
  7818. return Math.max(1, this.getMaximumSplatBufferCompressionLevel());
  7819. }
  7820. getMaximumSplatBufferCompressionLevel() {
  7821. let maxCompressionLevel;
  7822. for (let i = 0; i < this.scenes.length; i++) {
  7823. const scene = this.getScene(i);
  7824. const splatBuffer = scene.splatBuffer;
  7825. if (i === 0 || splatBuffer.compressionLevel > maxCompressionLevel) {
  7826. maxCompressionLevel = splatBuffer.compressionLevel;
  7827. }
  7828. }
  7829. return maxCompressionLevel;
  7830. }
  7831. getMinimumSplatBufferCompressionLevel() {
  7832. let minCompressionLevel;
  7833. for (let i = 0; i < this.scenes.length; i++) {
  7834. const scene = this.getScene(i);
  7835. const splatBuffer = scene.splatBuffer;
  7836. if (i === 0 || splatBuffer.compressionLevel < minCompressionLevel) {
  7837. minCompressionLevel = splatBuffer.compressionLevel;
  7838. }
  7839. }
  7840. return minCompressionLevel;
  7841. }
  7842. static computeTextureUpdateRegion(startSplat, endSplat, textureWidth, elementsPerTexel, elementsPerSplat) {
  7843. const texelsPerSplat = elementsPerSplat / elementsPerTexel;
  7844. const startSplatTexels = startSplat * texelsPerSplat;
  7845. const startRow = Math.floor(startSplatTexels / textureWidth);
  7846. const startRowElement = startRow * textureWidth * elementsPerTexel;
  7847. const endSplatTexels = endSplat * texelsPerSplat;
  7848. const endRow = Math.floor(endSplatTexels / textureWidth);
  7849. const endRowEndElement = endRow * textureWidth * elementsPerTexel + (textureWidth * elementsPerTexel);
  7850. return {
  7851. 'dataStart': startRowElement,
  7852. 'dataEnd': endRowEndElement,
  7853. 'startRow': startRow,
  7854. 'endRow': endRow
  7855. };
  7856. }
  7857. updateDataTexture(paddedData, texture, textureSize, textureProps, elementsPerTexel, elementsPerSplat, bytesPerElement, from, to) {
  7858. const gl = this.renderer.getContext();
  7859. const updateRegion = SplatMesh.computeTextureUpdateRegion(from, to, textureSize.x, elementsPerTexel, elementsPerSplat);
  7860. const updateElementCount = updateRegion.dataEnd - updateRegion.dataStart;
  7861. const updateDataView = new paddedData.constructor(paddedData.buffer,
  7862. updateRegion.dataStart * bytesPerElement, updateElementCount);
  7863. const updateHeight = updateRegion.endRow - updateRegion.startRow + 1;
  7864. const glType = this.webGLUtils.convert(texture.type);
  7865. const glFormat = this.webGLUtils.convert(texture.format, texture.colorSpace);
  7866. const currentTexture = gl.getParameter(gl.TEXTURE_BINDING_2D);
  7867. gl.bindTexture(gl.TEXTURE_2D, textureProps.__webglTexture);
  7868. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, updateRegion.startRow,
  7869. textureSize.x, updateHeight, glFormat, glType, updateDataView);
  7870. gl.bindTexture(gl.TEXTURE_2D, currentTexture);
  7871. }
  7872. static updatePaddedCompressedCovariancesTextureData(sourceData, textureData, textureDataStartIndex, fromElement, toElement) {
  7873. let textureDataView = new DataView(textureData.buffer);
  7874. let textureDataIndex = textureDataStartIndex;
  7875. let sequentialCount = 0;
  7876. for (let i = fromElement; i <= toElement; i+=2) {
  7877. textureDataView.setUint16(textureDataIndex * 2, sourceData[i], true);
  7878. textureDataView.setUint16(textureDataIndex * 2 + 2, sourceData[i + 1], true);
  7879. textureDataIndex += 2;
  7880. sequentialCount++;
  7881. if (sequentialCount >= 3) {
  7882. textureDataIndex += 2;
  7883. sequentialCount = 0;
  7884. }
  7885. }
  7886. }
  7887. static updateCenterColorsPaddedData(from, to, centers, colors, paddedCenterColors) {
  7888. for (let c = from; c <= to; c++) {
  7889. const colorsBase = c * 4;
  7890. const centersBase = c * 3;
  7891. const centerColorsBase = c * 4;
  7892. paddedCenterColors[centerColorsBase] = rgbaArrayToInteger(colors, colorsBase);
  7893. paddedCenterColors[centerColorsBase + 1] = uintEncodedFloat(centers[centersBase]);
  7894. paddedCenterColors[centerColorsBase + 2] = uintEncodedFloat(centers[centersBase + 1]);
  7895. paddedCenterColors[centerColorsBase + 3] = uintEncodedFloat(centers[centersBase + 2]);
  7896. }
  7897. }
  7898. static updateScaleRotationsPaddedData(from, to, scales, rotations, paddedScaleRotations) {
  7899. const combinedSize = 6;
  7900. for (let c = from; c <= to; c++) {
  7901. const scaleBase = c * 3;
  7902. const rotationBase = c * 4;
  7903. const scaleRotationsBase = c * combinedSize;
  7904. paddedScaleRotations[scaleRotationsBase] = scales[scaleBase];
  7905. paddedScaleRotations[scaleRotationsBase + 1] = scales[scaleBase + 1];
  7906. paddedScaleRotations[scaleRotationsBase + 2] = scales[scaleBase + 2];
  7907. paddedScaleRotations[scaleRotationsBase + 3] = rotations[rotationBase];
  7908. paddedScaleRotations[scaleRotationsBase + 4] = rotations[rotationBase + 1];
  7909. paddedScaleRotations[scaleRotationsBase + 5] = rotations[rotationBase + 2];
  7910. }
  7911. }
  7912. updateVisibleRegion(sinceLastBuildOnly) {
  7913. const splatCount = this.getSplatCount();
  7914. const tempCenter = new THREE.Vector3();
  7915. if (!sinceLastBuildOnly) {
  7916. const avgCenter = new THREE.Vector3();
  7917. this.scenes.forEach((scene) => {
  7918. avgCenter.add(scene.splatBuffer.sceneCenter);
  7919. });
  7920. avgCenter.multiplyScalar(1.0 / this.scenes.length);
  7921. this.calculatedSceneCenter.copy(avgCenter);
  7922. this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter);
  7923. this.material.uniformsNeedUpdate = true;
  7924. }
  7925. const startSplatFormMaxDistanceCalc = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  7926. for (let i = startSplatFormMaxDistanceCalc; i < splatCount; i++) {
  7927. this.getSplatCenter(i, tempCenter, true);
  7928. const distFromCSceneCenter = tempCenter.sub(this.calculatedSceneCenter).length();
  7929. if (distFromCSceneCenter > this.maxSplatDistanceFromSceneCenter) this.maxSplatDistanceFromSceneCenter = distFromCSceneCenter;
  7930. }
  7931. if (this.maxSplatDistanceFromSceneCenter - this.visibleRegionBufferRadius > VISIBLE_REGION_EXPANSION_DELTA) {
  7932. this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter;
  7933. this.visibleRegionRadius = Math.max(this.visibleRegionBufferRadius - VISIBLE_REGION_EXPANSION_DELTA, 0.0);
  7934. }
  7935. if (this.finalBuild) this.visibleRegionRadius = this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter;
  7936. this.updateVisibleRegionFadeDistance();
  7937. }
  7938. updateVisibleRegionFadeDistance(sceneRevealMode = SceneRevealMode.Default) {
  7939. const fastFadeRate = SCENE_FADEIN_RATE_FAST;
  7940. const gradualFadeRate = SCENE_FADEIN_RATE_GRADUAL;
  7941. const defaultFadeInRate = this.finalBuild ? fastFadeRate : gradualFadeRate;
  7942. const fadeInRate = sceneRevealMode === SceneRevealMode.Default ? defaultFadeInRate : gradualFadeRate;
  7943. this.visibleRegionFadeStartRadius = (this.visibleRegionRadius - this.visibleRegionFadeStartRadius) *
  7944. fadeInRate + this.visibleRegionFadeStartRadius;
  7945. const fadeInPercentage = (this.visibleRegionBufferRadius > 0) ?
  7946. (this.visibleRegionFadeStartRadius / this.visibleRegionBufferRadius) : 0;
  7947. const fadeInComplete = fadeInPercentage > 0.99;
  7948. const shaderFadeInComplete = (fadeInComplete || sceneRevealMode === SceneRevealMode.Instant) ? 1 : 0;
  7949. this.material.uniforms.visibleRegionFadeStartRadius.value = this.visibleRegionFadeStartRadius;
  7950. this.material.uniforms.visibleRegionRadius.value = this.visibleRegionRadius;
  7951. this.material.uniforms.firstRenderTime.value = this.firstRenderTime;
  7952. this.material.uniforms.currentTime.value = performance.now();
  7953. this.material.uniforms.fadeInComplete.value = shaderFadeInComplete;
  7954. this.material.uniformsNeedUpdate = true;
  7955. this.visibleRegionChanging = !fadeInComplete;
  7956. }
  7957. /**
  7958. * Set the indexes of splats that should be rendered; should be sorted in desired render order.
  7959. * @param {Uint32Array} globalIndexes Sorted index list of splats to be rendered
  7960. * @param {number} renderSplatCount Total number of splats to be rendered. Necessary because we may not want to render
  7961. * every splat.
  7962. */
  7963. updateRenderIndexes(globalIndexes, renderSplatCount) {
  7964. const geometry = this.geometry;
  7965. geometry.attributes.splatIndex.set(globalIndexes);
  7966. geometry.attributes.splatIndex.needsUpdate = true;
  7967. if (renderSplatCount > 0 && this.firstRenderTime === -1) this.firstRenderTime = performance.now();
  7968. geometry.instanceCount = renderSplatCount;
  7969. //console.log('updateRenderIndexes')
  7970. }
  7971. /**
  7972. * Update the transforms for each scene in this splat mesh from their individual components (position,
  7973. * quaternion, and scale)
  7974. */
  7975. updateTransforms() {
  7976. for (let i = 0; i < this.scenes.length; i++) {
  7977. const scene = this.getScene(i);
  7978. scene.updateTransform(this.dynamicMode);
  7979. }
  7980. }
  7981. updateUniforms = function() {
  7982. const viewport = new THREE.Vector2();
  7983. return function(renderDimensions, cameraFocalLengthX, cameraFocalLengthY,
  7984. orthographicMode, orthographicZoom, inverseFocalAdjustment) {
  7985. const splatCount = this.getSplatCount();
  7986. if (splatCount > 0) {
  7987. viewport.set(renderDimensions.x * this.devicePixelRatio,
  7988. renderDimensions.y * this.devicePixelRatio);
  7989. this.material.uniforms.viewport.value.copy(viewport);
  7990. this.material.uniforms.basisViewport.value.set(1.0 / viewport.x, 1.0 / viewport.y);
  7991. this.material.uniforms.focal.value.set(cameraFocalLengthX, cameraFocalLengthY);
  7992. this.material.uniforms.orthographicMode.value = orthographicMode ? 1 : 0;
  7993. this.material.uniforms.orthoZoom.value = orthographicZoom;
  7994. this.material.uniforms.inverseFocalAdjustment.value = inverseFocalAdjustment;
  7995. if (this.dynamicMode) {
  7996. for (let i = 0; i < this.scenes.length; i++) {
  7997. this.material.uniforms.transforms.value[i].copy(this.getScene(i).transform);
  7998. }
  7999. }
  8000. if (this.enableOptionalEffects) {
  8001. for (let i = 0; i < this.scenes.length; i++) {
  8002. this.material.uniforms.sceneOpacity.value[i] = clamp(this.getScene(i).opacity, 0.0, 1.0);
  8003. this.material.uniforms.sceneVisibility.value[i] = this.getScene(i).visible ? 1 : 0;
  8004. this.material.uniformsNeedUpdate = true;
  8005. }
  8006. }
  8007. this.material.uniformsNeedUpdate = true;
  8008. }
  8009. };
  8010. }();
  8011. setSplatScale(splatScale = 1) {
  8012. this.splatScale = splatScale;
  8013. this.material.uniforms.splatScale.value = splatScale;
  8014. this.material.uniformsNeedUpdate = true;
  8015. }
  8016. getSplatScale() {
  8017. return this.splatScale;
  8018. }
  8019. setPointCloudModeEnabled(enabled) {
  8020. this.pointCloudModeEnabled = enabled;
  8021. this.material.uniforms.pointCloudModeEnabled.value = enabled ? 1 : 0;
  8022. this.material.uniformsNeedUpdate = true;
  8023. }
  8024. getPointCloudModeEnabled() {
  8025. return this.pointCloudModeEnabled;
  8026. }
  8027. getSplatDataTextures() {
  8028. return this.splatDataTextures;
  8029. }
  8030. getSplatCount() {
  8031. return SplatMesh.getTotalSplatCountForScenes(this.scenes);
  8032. }
  8033. static getTotalSplatCountForScenes(scenes) {
  8034. let totalSplatCount = 0;
  8035. for (let scene of scenes) {
  8036. if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getSplatCount();
  8037. }
  8038. return totalSplatCount;
  8039. }
  8040. static getTotalSplatCountForSplatBuffers(splatBuffers) {
  8041. let totalSplatCount = 0;
  8042. for (let splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getSplatCount();
  8043. return totalSplatCount;
  8044. }
  8045. getMaxSplatCount() {
  8046. return SplatMesh.getTotalMaxSplatCountForScenes(this.scenes);
  8047. }
  8048. static getTotalMaxSplatCountForScenes(scenes) {
  8049. let totalSplatCount = 0;
  8050. for (let scene of scenes) {
  8051. if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getMaxSplatCount();
  8052. }
  8053. return totalSplatCount;
  8054. }
  8055. static getTotalMaxSplatCountForSplatBuffers(splatBuffers) {
  8056. let totalSplatCount = 0;
  8057. for (let splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getMaxSplatCount();
  8058. return totalSplatCount;
  8059. }
  8060. disposeDistancesComputationGPUResources() {
  8061. if (!this.renderer) return;
  8062. const gl = this.renderer.getContext();
  8063. if (this.distancesTransformFeedback.vao) {
  8064. gl.deleteVertexArray(this.distancesTransformFeedback.vao);
  8065. this.distancesTransformFeedback.vao = null;
  8066. }
  8067. if (this.distancesTransformFeedback.program) {
  8068. gl.deleteProgram(this.distancesTransformFeedback.program);
  8069. gl.deleteShader(this.distancesTransformFeedback.vertexShader);
  8070. gl.deleteShader(this.distancesTransformFeedback.fragmentShader);
  8071. this.distancesTransformFeedback.program = null;
  8072. this.distancesTransformFeedback.vertexShader = null;
  8073. this.distancesTransformFeedback.fragmentShader = null;
  8074. }
  8075. this.disposeDistancesComputationGPUBufferResources();
  8076. if (this.distancesTransformFeedback.id) {
  8077. gl.deleteTransformFeedback(this.distancesTransformFeedback.id);
  8078. this.distancesTransformFeedback.id = null;
  8079. }
  8080. }
  8081. disposeDistancesComputationGPUBufferResources() {
  8082. if (!this.renderer) return;
  8083. const gl = this.renderer.getContext();
  8084. if (this.distancesTransformFeedback.centersBuffer) {
  8085. this.distancesTransformFeedback.centersBuffer = null;
  8086. gl.deleteBuffer(this.distancesTransformFeedback.centersBuffer);
  8087. }
  8088. if (this.distancesTransformFeedback.outDistancesBuffer) {
  8089. gl.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer);
  8090. this.distancesTransformFeedback.outDistancesBuffer = null;
  8091. }
  8092. }
  8093. /**
  8094. * Set the Three.js renderer used by this splat mesh
  8095. * @param {THREE.WebGLRenderer} renderer Instance of THREE.WebGLRenderer
  8096. */
  8097. setRenderer(renderer) {
  8098. if (renderer !== this.renderer) {
  8099. this.renderer = renderer;
  8100. const gl = this.renderer.getContext();
  8101. const extensions = new WebGLExtensions(gl);
  8102. const capabilities = new WebGLCapabilities(gl, extensions, {});
  8103. extensions.init(capabilities);
  8104. this.webGLUtils = new THREE.WebGLUtils(gl, extensions, capabilities);
  8105. if (this.enableDistancesComputationOnGPU && this.getSplatCount() > 0) {
  8106. this.setupDistancesComputationTransformFeedback();
  8107. const { centers, sceneIndexes } = this.getDataForDistancesComputation(0, this.getSplatCount() - 1);
  8108. this.refreshGPUBuffersForDistancesComputation(centers, sceneIndexes);
  8109. }
  8110. }
  8111. }
  8112. setupDistancesComputationTransformFeedback = function() {
  8113. let currentMaxSplatCount;
  8114. return function() {
  8115. const maxSplatCount = this.getMaxSplatCount();
  8116. if (!this.renderer) return;
  8117. const rebuildGPUObjects = (this.lastRenderer !== this.renderer);
  8118. const rebuildBuffers = currentMaxSplatCount !== maxSplatCount;
  8119. if (!rebuildGPUObjects && !rebuildBuffers) return;
  8120. if (rebuildGPUObjects) {
  8121. this.disposeDistancesComputationGPUResources();
  8122. } else if (rebuildBuffers) {
  8123. this.disposeDistancesComputationGPUBufferResources();
  8124. }
  8125. const gl = this.renderer.getContext();
  8126. const createShader = (gl, type, source) => {
  8127. const shader = gl.createShader(type);
  8128. if (!shader) {
  8129. console.error('Fatal error: gl could not create a shader object.');
  8130. return null;
  8131. }
  8132. gl.shaderSource(shader, source);
  8133. gl.compileShader(shader);
  8134. const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  8135. if (!compiled) {
  8136. let typeName = 'unknown';
  8137. if (type === gl.VERTEX_SHADER) typeName = 'vertex shader';
  8138. else if (type === gl.FRAGMENT_SHADER) typeName = 'fragement shader';
  8139. const errors = gl.getShaderInfoLog(shader);
  8140. console.error('Failed to compile ' + typeName + ' with these errors:' + errors);
  8141. gl.deleteShader(shader);
  8142. return null;
  8143. }
  8144. return shader;
  8145. };
  8146. let vsSource;
  8147. if (this.integerBasedDistancesComputation) {
  8148. vsSource =
  8149. `#version 300 es
  8150. in ivec4 center;
  8151. flat out int distance;`;
  8152. if (this.dynamicMode) {
  8153. vsSource += `
  8154. in uint sceneIndex;
  8155. uniform ivec4 transforms[${Constants.MaxScenes}];
  8156. void main(void) {
  8157. ivec4 transform = transforms[sceneIndex];
  8158. distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;
  8159. }
  8160. `;
  8161. } else {
  8162. vsSource += `
  8163. uniform ivec3 modelViewProj;
  8164. void main(void) {
  8165. distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;
  8166. }
  8167. `;
  8168. }
  8169. } else {
  8170. vsSource =
  8171. `#version 300 es
  8172. in vec4 center;
  8173. flat out float distance;`;
  8174. if (this.dynamicMode) {
  8175. vsSource += `
  8176. in uint sceneIndex;
  8177. uniform mat4 transforms[${Constants.MaxScenes}];
  8178. void main(void) {
  8179. vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);
  8180. distance = transformedCenter.z;
  8181. }
  8182. `;
  8183. } else {
  8184. vsSource += `
  8185. uniform vec3 modelViewProj;
  8186. void main(void) {
  8187. distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;
  8188. }
  8189. `;
  8190. }
  8191. }
  8192. const fsSource =
  8193. `#version 300 es
  8194. precision lowp float;
  8195. out vec4 fragColor;
  8196. void main(){}
  8197. `;
  8198. const currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  8199. const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);
  8200. const currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false;
  8201. if (rebuildGPUObjects) {
  8202. this.distancesTransformFeedback.vao = gl.createVertexArray();
  8203. }
  8204. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  8205. if (rebuildGPUObjects) {
  8206. const program = gl.createProgram();
  8207. const vertexShader = createShader(gl, gl.VERTEX_SHADER, vsSource);
  8208. const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
  8209. if (!vertexShader || !fragmentShader) {
  8210. throw new Error('Could not compile shaders for distances computation on GPU.');
  8211. }
  8212. gl.attachShader(program, vertexShader);
  8213. gl.attachShader(program, fragmentShader);
  8214. gl.transformFeedbackVaryings(program, ['distance'], gl.SEPARATE_ATTRIBS);
  8215. gl.linkProgram(program);
  8216. const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  8217. if (!linked) {
  8218. const error = gl.getProgramInfoLog(program);
  8219. console.error('Fatal error: Failed to link program: ' + error);
  8220. gl.deleteProgram(program);
  8221. gl.deleteShader(fragmentShader);
  8222. gl.deleteShader(vertexShader);
  8223. throw new Error('Could not link shaders for distances computation on GPU.');
  8224. }
  8225. this.distancesTransformFeedback.program = program;
  8226. this.distancesTransformFeedback.vertexShader = vertexShader;
  8227. this.distancesTransformFeedback.vertexShader = fragmentShader;
  8228. }
  8229. gl.useProgram(this.distancesTransformFeedback.program);
  8230. this.distancesTransformFeedback.centersLoc =
  8231. gl.getAttribLocation(this.distancesTransformFeedback.program, 'center');
  8232. if (this.dynamicMode) {
  8233. this.distancesTransformFeedback.sceneIndexesLoc =
  8234. gl.getAttribLocation(this.distancesTransformFeedback.program, 'sceneIndex');
  8235. for (let i = 0; i < this.scenes.length; i++) {
  8236. this.distancesTransformFeedback.transformsLocs[i] =
  8237. gl.getUniformLocation(this.distancesTransformFeedback.program, `transforms[${i}]`);
  8238. }
  8239. } else {
  8240. this.distancesTransformFeedback.modelViewProjLoc =
  8241. gl.getUniformLocation(this.distancesTransformFeedback.program, 'modelViewProj');
  8242. }
  8243. if (rebuildGPUObjects || rebuildBuffers) {
  8244. this.distancesTransformFeedback.centersBuffer = gl.createBuffer();
  8245. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  8246. gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc);
  8247. if (this.integerBasedDistancesComputation) {
  8248. gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0);
  8249. } else {
  8250. gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0);
  8251. }
  8252. if (this.dynamicMode) {
  8253. this.distancesTransformFeedback.sceneIndexesBuffer = gl.createBuffer();
  8254. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.sceneIndexesBuffer);
  8255. gl.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc);
  8256. gl.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0);
  8257. }
  8258. }
  8259. if (rebuildGPUObjects || rebuildBuffers) {
  8260. this.distancesTransformFeedback.outDistancesBuffer = gl.createBuffer();
  8261. }
  8262. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer);
  8263. gl.bufferData(gl.ARRAY_BUFFER, maxSplatCount * 4, gl.STATIC_READ);
  8264. if (rebuildGPUObjects) {
  8265. this.distancesTransformFeedback.id = gl.createTransformFeedback();
  8266. }
  8267. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id);
  8268. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer);
  8269. if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram);
  8270. if (currentVao) gl.bindVertexArray(currentVao);
  8271. this.lastRenderer = this.renderer;
  8272. currentMaxSplatCount = maxSplatCount;
  8273. };
  8274. }();
  8275. /**
  8276. * Refresh GPU buffers used for computing splat distances with centers data from the scenes for this mesh.
  8277. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill
  8278. * @param {Array<number>} centers The splat centers data
  8279. * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats
  8280. */
  8281. updateGPUCentersBufferForDistancesComputation(isUpdate, centers, offsetSplats) {
  8282. if (!this.renderer) return;
  8283. const gl = this.renderer.getContext();
  8284. const currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  8285. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  8286. const ArrayType = this.integerBasedDistancesComputation ? Uint32Array : Float32Array;
  8287. const attributeBytesPerCenter = 16;
  8288. const subBufferOffset = offsetSplats * attributeBytesPerCenter;
  8289. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  8290. if (isUpdate) {
  8291. gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, centers);
  8292. } else {
  8293. const maxArray = new ArrayType(this.getMaxSplatCount() * attributeBytesPerCenter);
  8294. maxArray.set(centers);
  8295. gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW);
  8296. }
  8297. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  8298. if (currentVao) gl.bindVertexArray(currentVao);
  8299. }
  8300. /**
  8301. * Refresh GPU buffers used for pre-computing splat distances with centers data from the scenes for this mesh.
  8302. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill
  8303. * @param {Array<number>} sceneIndexes The splat scene indexes
  8304. * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats
  8305. */
  8306. updateGPUTransformIndexesBufferForDistancesComputation(isUpdate, sceneIndexes, offsetSplats) {
  8307. if (!this.renderer || !this.dynamicMode) return;
  8308. const gl = this.renderer.getContext();
  8309. const currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  8310. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  8311. const subBufferOffset = offsetSplats * 4;
  8312. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.sceneIndexesBuffer);
  8313. if (isUpdate) {
  8314. gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, sceneIndexes);
  8315. } else {
  8316. const maxArray = new Uint32Array(this.getMaxSplatCount() * 4);
  8317. maxArray.set(sceneIndexes);
  8318. gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW);
  8319. }
  8320. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  8321. if (currentVao) gl.bindVertexArray(currentVao);
  8322. }
  8323. /**
  8324. * Get a typed array containing a mapping from global splat indexes to their scene index.
  8325. * @param {number} start Starting splat index to store
  8326. * @param {number} end Ending splat index to store
  8327. * @return {Uint32Array}
  8328. */
  8329. getSceneIndexes(start, end) {
  8330. let sceneIndexes;
  8331. const fillCount = end - start + 1;
  8332. sceneIndexes = new Uint32Array(fillCount);
  8333. for (let i = start; i <= end; i++) {
  8334. sceneIndexes[i] = this.globalSplatIndexToSceneIndexMap[i];
  8335. }
  8336. return sceneIndexes;
  8337. }
  8338. /**
  8339. * Fill 'array' with the transforms for each scene in this splat mesh.
  8340. * @param {Array} array Empty array to be filled with scene transforms. If not empty, contents will be overwritten.
  8341. */
  8342. fillTransformsArray = function() {
  8343. const tempArray = [];
  8344. return function(array) {
  8345. if (tempArray.length !== array.length) tempArray.length = array.length;
  8346. for (let i = 0; i < this.scenes.length; i++) {
  8347. const sceneTransform = this.getScene(i).transform;
  8348. const sceneTransformElements = sceneTransform.elements;
  8349. for (let j = 0; j < 16; j++) {
  8350. tempArray[i * 16 + j] = sceneTransformElements[j];
  8351. }
  8352. }
  8353. array.set(tempArray);
  8354. };
  8355. }();
  8356. computeDistancesOnGPU = function() {
  8357. const tempMatrix = new THREE.Matrix4();
  8358. return function(modelViewProjMatrix, outComputedDistances) {
  8359. if (!this.renderer) return;
  8360. // console.time("gpu_compute_distances");
  8361. const gl = this.renderer.getContext();
  8362. const currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  8363. const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);
  8364. const currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false;
  8365. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  8366. gl.useProgram(this.distancesTransformFeedback.program);
  8367. gl.enable(gl.RASTERIZER_DISCARD);
  8368. if (this.dynamicMode) {
  8369. for (let i = 0; i < this.scenes.length; i++) {
  8370. tempMatrix.copy(this.getScene(i).transform);
  8371. tempMatrix.premultiply(modelViewProjMatrix);
  8372. if (this.integerBasedDistancesComputation) {
  8373. const iTempMatrix = SplatMesh.getIntegerMatrixArray(tempMatrix);
  8374. const iTransform = [iTempMatrix[2], iTempMatrix[6], iTempMatrix[10], iTempMatrix[14]];
  8375. gl.uniform4i(this.distancesTransformFeedback.transformsLocs[i], iTransform[0], iTransform[1],
  8376. iTransform[2], iTransform[3]);
  8377. } else {
  8378. gl.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[i], false, tempMatrix.elements);
  8379. }
  8380. }
  8381. } else {
  8382. if (this.integerBasedDistancesComputation) {
  8383. const iViewProjMatrix = SplatMesh.getIntegerMatrixArray(modelViewProjMatrix);
  8384. const iViewProj = [iViewProjMatrix[2], iViewProjMatrix[6], iViewProjMatrix[10]];
  8385. gl.uniform3i(this.distancesTransformFeedback.modelViewProjLoc, iViewProj[0], iViewProj[1], iViewProj[2]);
  8386. } else {
  8387. const viewProj = [modelViewProjMatrix.elements[2], modelViewProjMatrix.elements[6], modelViewProjMatrix.elements[10]];
  8388. gl.uniform3f(this.distancesTransformFeedback.modelViewProjLoc, viewProj[0], viewProj[1], viewProj[2]);
  8389. }
  8390. }
  8391. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  8392. gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc);
  8393. if (this.integerBasedDistancesComputation) {
  8394. gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0);
  8395. } else {
  8396. gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0);
  8397. }
  8398. if (this.dynamicMode) {
  8399. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.sceneIndexesBuffer);
  8400. gl.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc);
  8401. gl.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0);
  8402. }
  8403. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id);
  8404. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer);
  8405. gl.beginTransformFeedback(gl.POINTS);
  8406. gl.drawArrays(gl.POINTS, 0, this.getSplatCount());
  8407. gl.endTransformFeedback();
  8408. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);
  8409. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
  8410. gl.disable(gl.RASTERIZER_DISCARD);
  8411. const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
  8412. gl.flush();
  8413. const promise = new Promise((resolve) => {
  8414. const checkSync = () => {
  8415. if (this.disposed) {
  8416. resolve();
  8417. } else {
  8418. const timeout = 0;
  8419. const bitflags = 0;
  8420. const status = gl.clientWaitSync(sync, bitflags, timeout);
  8421. switch (status) {
  8422. case gl.TIMEOUT_EXPIRED:
  8423. this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync);
  8424. return this.computeDistancesOnGPUSyncTimeout;
  8425. case gl.WAIT_FAILED:
  8426. throw new Error('should never get here');
  8427. default:
  8428. this.computeDistancesOnGPUSyncTimeout = null;
  8429. gl.deleteSync(sync);
  8430. const currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  8431. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  8432. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer);
  8433. gl.getBufferSubData(gl.ARRAY_BUFFER, 0, outComputedDistances);
  8434. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  8435. if (currentVao) gl.bindVertexArray(currentVao);
  8436. // console.timeEnd("gpu_compute_distances");
  8437. resolve();
  8438. }
  8439. }
  8440. };
  8441. this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync);
  8442. });
  8443. if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram);
  8444. if (currentVao) gl.bindVertexArray(currentVao);
  8445. return promise;
  8446. };
  8447. }();
  8448. /**
  8449. * Given a global splat index, return corresponding local data (splat buffer, index of splat in that splat
  8450. * buffer, and the corresponding transform)
  8451. * @param {number} globalIndex Global splat index
  8452. * @param {object} paramsObj Object in which to store local data
  8453. * @param {boolean} returnSceneTransform By default, the transform of the scene to which the splat at 'globalIndex' belongs will be
  8454. * returned via the 'sceneTransform' property of 'paramsObj' only if the splat mesh is static.
  8455. * If 'returnSceneTransform' is true, the 'sceneTransform' property will always contain the scene
  8456. * transform, and if 'returnSceneTransform' is false, the 'sceneTransform' property will always
  8457. * be null.
  8458. */
  8459. getLocalSplatParameters(globalIndex, paramsObj, returnSceneTransform) {
  8460. if (returnSceneTransform === undefined || returnSceneTransform === null) {
  8461. returnSceneTransform = this.dynamicMode ? false : true;
  8462. }
  8463. paramsObj.splatBuffer = this.getSplatBufferForSplat(globalIndex);
  8464. paramsObj.localIndex = this.getSplatLocalIndex(globalIndex);
  8465. paramsObj.sceneTransform = returnSceneTransform ? this.getSceneTransformForSplat(globalIndex) : null;
  8466. }
  8467. /**
  8468. * Fill arrays with splat data and apply transforms if appropriate. Each array is optional.
  8469. * @param {Float32Array} covariances Target storage for splat covariances
  8470. * @param {Float32Array} scales Target storage for splat scales
  8471. * @param {Float32Array} rotations Target storage for splat rotations
  8472. * @param {Float32Array} centers Target storage for splat centers
  8473. * @param {Uint8Array} colors Target storage for splat colors
  8474. * @param {Float32Array} sphericalHarmonics Target storage for spherical harmonics
  8475. * @param {boolean} applySceneTransform By default, scene transforms are applied to relevant splat data only if the splat mesh is
  8476. * static. If 'applySceneTransform' is true, scene transforms will always be applied and if
  8477. * it is false, they will never be applied. If undefined, the default behavior will apply.
  8478. * @param {number} covarianceCompressionLevel The compression level for covariances in the destination array
  8479. * @param {number} sphericalHarmonicsCompressionLevel The compression level for spherical harmonics in the destination array
  8480. * @param {number} srcStart The start location from which to pull source data
  8481. * @param {number} srcEnd The end location from which to pull source data
  8482. * @param {number} destStart The start location from which to write data
  8483. */
  8484. fillSplatDataArrays(covariances, scales, rotations, centers, colors, sphericalHarmonics, applySceneTransform,
  8485. covarianceCompressionLevel = 0, scaleRotationCompressionLevel = 0, sphericalHarmonicsCompressionLevel = 1,
  8486. srcStart, srcEnd, destStart = 0) {
  8487. const scaleOverride = new THREE.Vector3();
  8488. scaleOverride.x = undefined;
  8489. scaleOverride.y = undefined;
  8490. if (this.splatRenderMode === SplatRenderMode.ThreeD) {
  8491. scaleOverride.z = undefined;
  8492. } else {
  8493. scaleOverride.z = 1;
  8494. }
  8495. const tempTransform = new THREE.Matrix4();
  8496. for (let i = 0; i < this.scenes.length; i++) {
  8497. if (applySceneTransform === undefined || applySceneTransform === null) {
  8498. applySceneTransform = this.dynamicMode ? false : true;
  8499. }
  8500. const scene = this.getScene(i);
  8501. const splatBuffer = scene.splatBuffer;
  8502. let sceneTransform;
  8503. if (applySceneTransform) {
  8504. this.getSceneTransform(i, tempTransform);
  8505. sceneTransform = tempTransform;
  8506. }
  8507. if (covariances) {
  8508. splatBuffer.fillSplatCovarianceArray(covariances, sceneTransform, srcStart, srcEnd, destStart, covarianceCompressionLevel);
  8509. }
  8510. if (scales || rotations) {
  8511. if (!scales || !rotations) {
  8512. throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');
  8513. }
  8514. splatBuffer.fillSplatScaleRotationArray(scales, rotations, sceneTransform,
  8515. srcStart, srcEnd, destStart, scaleRotationCompressionLevel, scaleOverride);
  8516. }
  8517. if (centers) splatBuffer.fillSplatCenterArray(centers, sceneTransform, srcStart, srcEnd, destStart);
  8518. if (colors) splatBuffer.fillSplatColorArray(colors, scene.minimumAlpha, srcStart, srcEnd, destStart);
  8519. if (sphericalHarmonics) {
  8520. splatBuffer.fillSphericalHarmonicsArray(sphericalHarmonics, this.minSphericalHarmonicsDegree,
  8521. sceneTransform, srcStart, srcEnd, destStart, sphericalHarmonicsCompressionLevel);
  8522. }
  8523. destStart += splatBuffer.getSplatCount();
  8524. }
  8525. }
  8526. /**
  8527. * Convert splat centers, which are floating point values, to an array of integers and multiply
  8528. * each by 1000. Centers will get transformed as appropriate before conversion to integer.
  8529. * @param {number} start The index at which to start retrieving data
  8530. * @param {number} end The index at which to stop retrieving data
  8531. * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values
  8532. * @return {Int32Array}
  8533. */
  8534. getIntegerCenters(start, end, padFour = false) {
  8535. const splatCount = end - start + 1;
  8536. const floatCenters = new Float32Array(splatCount * 3);
  8537. this.fillSplatDataArrays(null, null, null, floatCenters, null, null, undefined, undefined, undefined, undefined, start);
  8538. let intCenters;
  8539. let componentCount = padFour ? 4 : 3;
  8540. intCenters = new Int32Array(splatCount * componentCount);
  8541. for (let i = 0; i < splatCount; i++) {
  8542. for (let t = 0; t < 3; t++) {
  8543. intCenters[i * componentCount + t] = Math.round(floatCenters[i * 3 + t] * 1000.0);
  8544. }
  8545. if (padFour) intCenters[i * componentCount + 3] = 1000;
  8546. }
  8547. return intCenters;
  8548. }
  8549. /**
  8550. * Returns an array of splat centers, transformed as appropriate, optionally padded.
  8551. * @param {number} start The index at which to start retrieving data
  8552. * @param {number} end The index at which to stop retrieving data
  8553. * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values
  8554. * @return {Float32Array}
  8555. */
  8556. getFloatCenters(start, end, padFour = false) {
  8557. const splatCount = end - start + 1;
  8558. const floatCenters = new Float32Array(splatCount * 3);
  8559. this.fillSplatDataArrays(null, null, null, floatCenters, null, null, undefined, undefined, undefined, undefined, start);
  8560. if (!padFour) return floatCenters;
  8561. let paddedFloatCenters = new Float32Array(splatCount * 4);
  8562. for (let i = 0; i < splatCount; i++) {
  8563. for (let t = 0; t < 3; t++) {
  8564. paddedFloatCenters[i * 4 + t] = floatCenters[i * 3 + t];
  8565. }
  8566. paddedFloatCenters[i * 4 + 3] = 1.0;
  8567. }
  8568. return paddedFloatCenters;
  8569. }
  8570. /**
  8571. * Get the center for a splat, transformed as appropriate.
  8572. * @param {number} globalIndex Global index of splat
  8573. * @param {THREE.Vector3} outCenter THREE.Vector3 instance in which to store splat center
  8574. * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at
  8575. * 'globalIndex' belongs will be applied to the splat center. If 'applySceneTransform' is true,
  8576. * the scene transform will always be applied and if 'applySceneTransform' is false, the
  8577. * scene transform will never be applied. If undefined, the default behavior will apply.
  8578. */
  8579. getSplatCenter = function() {
  8580. const paramsObj = {};
  8581. return function(globalIndex, outCenter, applySceneTransform) {
  8582. this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform);
  8583. paramsObj.splatBuffer.getSplatCenter(paramsObj.localIndex, outCenter, paramsObj.sceneTransform);
  8584. };
  8585. }();
  8586. /**
  8587. * Get the scale and rotation for a splat, transformed as appropriate.
  8588. * @param {number} globalIndex Global index of splat
  8589. * @param {THREE.Vector3} outScale THREE.Vector3 instance in which to store splat scale
  8590. * @param {THREE.Quaternion} outRotation THREE.Quaternion instance in which to store splat rotation
  8591. * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at
  8592. * 'globalIndex' belongs will be applied to the splat scale and rotation. If
  8593. * 'applySceneTransform' is true, the scene transform will always be applied and if
  8594. * 'applySceneTransform' is false, the scene transform will never be applied. If undefined,
  8595. * the default behavior will apply.
  8596. */
  8597. getSplatScaleAndRotation = function() {
  8598. const paramsObj = {};
  8599. const scaleOverride = new THREE.Vector3();
  8600. return function(globalIndex, outScale, outRotation, applySceneTransform) {
  8601. this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform);
  8602. scaleOverride.x = undefined;
  8603. scaleOverride.y = undefined;
  8604. scaleOverride.z = undefined;
  8605. if (this.splatRenderMode === SplatRenderMode.TwoD) scaleOverride.z = 0;
  8606. paramsObj.splatBuffer.getSplatScaleAndRotation(paramsObj.localIndex, outScale, outRotation,
  8607. paramsObj.sceneTransform, scaleOverride);
  8608. };
  8609. }();
  8610. /**
  8611. * Get the color for a splat.
  8612. * @param {number} globalIndex Global index of splat
  8613. * @param {THREE.Vector4} outColor THREE.Vector4 instance in which to store splat color
  8614. */
  8615. getSplatColor = function() {
  8616. const paramsObj = {};
  8617. return function(globalIndex, outColor) {
  8618. this.getLocalSplatParameters(globalIndex, paramsObj);
  8619. paramsObj.splatBuffer.getSplatColor(paramsObj.localIndex, outColor);
  8620. };
  8621. }();
  8622. /**
  8623. * Store the transform of the scene at 'sceneIndex' in 'outTransform'.
  8624. * @param {number} sceneIndex Index of the desired scene
  8625. * @param {THREE.Matrix4} outTransform Instance of THREE.Matrix4 in which to store the scene's transform
  8626. */
  8627. getSceneTransform(sceneIndex, outTransform) {
  8628. const scene = this.getScene(sceneIndex);
  8629. scene.updateTransform(this.dynamicMode);
  8630. outTransform.copy(scene.transform);
  8631. }
  8632. /**
  8633. * Get the scene at 'sceneIndex'.
  8634. * @param {number} sceneIndex Index of the desired scene
  8635. * @return {SplatScene}
  8636. */
  8637. getScene(sceneIndex) {
  8638. if (sceneIndex < 0 || sceneIndex >= this.scenes.length) {
  8639. throw new Error('SplatMesh::getScene() -> Invalid scene index.');
  8640. }
  8641. return this.scenes[sceneIndex];
  8642. }
  8643. getSceneCount() {
  8644. return this.scenes.length;
  8645. }
  8646. getSplatBufferForSplat(globalIndex) {
  8647. return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).splatBuffer;
  8648. }
  8649. getSceneIndexForSplat(globalIndex) {
  8650. return this.globalSplatIndexToSceneIndexMap[globalIndex];
  8651. }
  8652. getSceneTransformForSplat(globalIndex) {
  8653. return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).transform;
  8654. }
  8655. getSplatLocalIndex(globalIndex) {
  8656. return this.globalSplatIndexToLocalSplatIndexMap[globalIndex];
  8657. }
  8658. static getIntegerMatrixArray(matrix) {
  8659. const matrixElements = matrix.elements;
  8660. const intMatrixArray = [];
  8661. for (let i = 0; i < 16; i++) {
  8662. intMatrixArray[i] = Math.round(matrixElements[i] * 1000.0);
  8663. }
  8664. return intMatrixArray;
  8665. }
  8666. }
  8667. var SorterWasm = "AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEbA2AAAGAQf39/f39/f39/f39/f39/fwBgAAF/AhIBA2VudgZtZW1vcnkCAwCAgAQDBAMAAQIHVAQRX193YXNtX2NhbGxfY3RvcnMAABhfX3dhc21fYXBwbHlfZGF0YV9yZWxvY3MAAAtzb3J0SW5kZXhlcwABE2Vtc2NyaXB0ZW5fdGxzX2luaXQAAgqWEAMDAAELihAEAXwDewN/A30gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEBA0AgAyABQQJ0IgVqIAIgACAFaigCAEECdGooAgAiBTYCACAFIAogBSAKSBshCiAFIA0gBSANShshDSABQQFqIgEgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiFWooAgAiFkECdGooAgAiFEcEQAJ/IAX9CQI4IAggFEEGdGoiDv0JAgwgDioCHP0gASAOKgIs/SACIA4qAjz9IAP95gEgBf0JAiggDv0JAgggDioCGP0gASAOKgIo/SACIA4qAjj9IAP95gEgBf0JAgggDv0JAgAgDioCEP0gASAOKgIg/SACIA4qAjD9IAP95gEgBf0JAhggDv0JAgQgDioCFP0gASAOKgIk/SACIA4qAjT9IAP95gH95AH95AH95AEiEf1f/QwAAAAAAECPQAAAAAAAQI9AIhL98gEiE/0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBP9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/REgDv0cAQJ/IBEgEf0NCAkKCwwNDg8AAAAAAAAAAP1fIBL98gEiEf0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9HAICfyAR/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAyESIBQhDwsgAyAVaiABIBZBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmogEf0bA2oiDjYCACAOIAogCiAOShshCiAOIA0gDSAOSBshDSACQQFqIgIgC0cNAAsMAwsCfyAFKgIIu/0UIAUqAhi7/SIB/QwAAAAAAECPQAAAAAAAQI9A/fIBIhH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIQ4CfyAR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyECAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQIgAv0RIA79HAEgBf0cAiESIAwhBQNAIAMgBUECdCICaiABIAAgAmooAgBBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmoiAjYCACACIAogAiAKSBshCiACIA0gAiANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEBA0AgAyABQQJ0IgVqAn8gAiAAIAVqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAFBAWoiASALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIRcgBSoCGCEYIAUqAgghGUH4////ByEKQYiAgIB4IQ0gDCEFA0ACfyAXIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCAZIAIqAgCUIBggAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIUaigCAEECdCIVaigCACIORwRAIAX9CQI4IAggDkEGdGoiD/0JAgwgDyoCHP0gASAPKgIs/SACIA8qAjz9IAP95gEgBf0JAiggD/0JAgggDyoCGP0gASAPKgIo/SACIA8qAjj9IAP95gEgBf0JAgggD/0JAgAgDyoCEP0gASAPKgIg/SACIA8qAjD9IAP95gEgBf0JAhggD/0JAgQgDyoCFP0gASAPKgIk/SACIA8qAjT9IAP95gH95AH95AH95AEhESAOIQ8LIAMgFGoCfyAR/R8DIAEgFUECdCIOQQxyaioCAJQgEf0fAiABIA5BCHJqKgIAlCAR/R8AIAEgDmoqAgCUIBH9HwEgASAOQQRyaioCAJSSkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSACQQFqIgIgC0cNAAsMAQtBiICAgHghDUH4////ByEKCyALIAxLBEAgCUEBa7MgDbIgCrKTlSEXIAwhDQNAAn8gFyADIA1BAnRqIgEoAgAgCmuylCIYi0MAAABPXQRAIBioDAELQYCAgIB4CyEOIAEgDjYCACAEIA5BAnRqIgEgASgCAEEBajYCACANQQFqIg0gC0cNAAsLIAlBAk8EQCAEKAIAIQ1BASEKA0AgBCAKQQJ0aiIBIAEoAgAgDWoiDTYCACAKQQFqIgogCUcNAAsLIAxBAEoEQCAMIQoDQCAGIApBAWsiAUECdCICaiAAIAJqKAIANgIAIApBAUshAiABIQogAg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCwsEAEEACw==";
  8668. var SorterWasmNoSIMD = "AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACEgEDZW52Bm1lbW9yeQIDAICABAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws=";
  8669. var SorterWasmNonShared = "AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQrrDwICAAvlDwQBfAN7B30DfyALIAprIQwCQAJAIA4EQCANBEBB+P///wchCkGIgICAeCENIAsgDE0NAyAMIQUDQCADIAVBAnQiAWogAiAAIAFqKAIAQQJ0aigCACIBNgIAIAEgCiABIApIGyEKIAEgDSABIA1KGyENIAVBAWoiBSALRw0ACwwDCyAPBEAgCyAMTQ0CQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIcaigCACIdQQJ0aigCACIbRwRAAn8gBf0JAjggCCAbQQZ0aiIO/QkCDCAOKgIc/SABIA4qAiz9IAIgDioCPP0gA/3mASAF/QkCKCAO/QkCCCAOKgIY/SABIA4qAij9IAIgDioCOP0gA/3mASAF/QkCCCAO/QkCACAOKgIQ/SABIA4qAiD9IAIgDioCMP0gA/3mASAF/QkCGCAO/QkCBCAOKgIU/SABIA4qAiT9IAIgDioCNP0gA/3mAf3kAf3kAf3kASIR/V/9DAAAAAAAQI9AAAAAAABAj0AiEv3yASIT/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOAn8gE/0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9ESAO/RwBAn8gESAR/Q0ICQoLDA0ODwABAgMAAQID/V8gEv3yASIR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAgJ/IBH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/RwDIRIgGyEPCyADIBxqIAEgHUEEdGr9AAAAIBL9tQEiEf0bACAR/RsBaiAR/RsCaiAR/RsDaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAgi7/RQgBSoCGLv9IgH9DAAAAAAAQI9AAAAAAABAj0D98gEiEf0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBH9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQL9ESAO/RwBIAX9HAIhEiAMIQUDQCADIAVBAnQiAmogASAAIAJqKAIAQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIgI2AgAgAiAKIAIgCkgbIQogAiANIAIgDUobIQ0gBUEBaiIFIAtHDQALDAILIA0EQEH4////ByEKQYiAgIB4IQ0gCyAMTQ0CIAwhBQNAIAMgBUECdCIBagJ/IAIgACABaigCAEECdGoqAgC7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgD0UEQCALIAxNDQEgBSoCKCEUIAUqAhghFSAFKgIIIRZB+P///wchCkGIgICAeCENIAwhBQNAAn8gFCABIAAgBUECdCIHaigCAEEEdGoiAioCCJQgFiACKgIAlCAVIAIqAgSUkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDiADIAdqIA42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gBUEBaiIFIAtHDQALDAILIAsgDE0NAEF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiG2ooAgBBAnQiHGooAgAiDkcEQCAFKgI4IhQgCCAOQQZ0aiIPKgI8lCAFKgIoIhUgDyoCOJQgBSoCCCIWIA8qAjCUIAUqAhgiFyAPKgI0lJKSkiEYIBQgDyoCLJQgFSAPKgIolCAWIA8qAiCUIBcgDyoCJJSSkpIhGSAUIA8qAhyUIBUgDyoCGJQgFiAPKgIQlCAXIA8qAhSUkpKSIRogFCAPKgIMlCAVIA8qAgiUIBYgDyoCAJQgFyAPKgIElJKSkiEUIA4hDwsgAyAbagJ/IBggASAcQQJ0aiIOKgIMlCAZIA4qAgiUIBQgDioCAJQgGiAOKgIElJKSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAJBAWoiAiALRw0ACwwBC0GIgICAeCENQfj///8HIQoLIAsgDEsEQCAJQQFrsyANsiAKspOVIRQgDCENA0ACfyAUIAMgDUECdGoiASgCACAKa7KUIhWLQwAAAE9dBEAgFagMAQtBgICAgHgLIQ4gASAONgIAIAQgDkECdGoiASABKAIAQQFqNgIAIA1BAWoiDSALRw0ACwsgCUECTwRAIAQoAgAhDUEBIQoDQCAEIApBAnRqIgEgASgCACANaiINNgIAIApBAWoiCiAJRw0ACwsgDEEASgRAIAwhCgNAIAYgCkEBayIBQQJ0IgJqIAAgAmooAgA2AgAgCkEBSyABIQoNAAsLIAsgDEoEQCALIQoDQCAGIAsgBCADIApBAWsiCkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgCiAMSg0ACwsL";
  8670. var SorterWasmNoSIMDNonShared = "AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws=";
  8671. function sortWorker(self) {
  8672. let wasmInstance;
  8673. let wasmMemory;
  8674. let useSharedMemory;
  8675. let integerBasedSort;
  8676. let dynamicMode;
  8677. let splatCount;
  8678. let indexesToSortOffset;
  8679. let sortedIndexesOffset;
  8680. let sceneIndexesOffset;
  8681. let transformsOffset;
  8682. let precomputedDistancesOffset;
  8683. let mappedDistancesOffset;
  8684. let frequenciesOffset;
  8685. let centersOffset;
  8686. let modelViewProjOffset;
  8687. let countsZero;
  8688. let sortedIndexesOut;
  8689. let Constants;
  8690. function sort(splatSortCount, splatRenderCount, modelViewProj,
  8691. usePrecomputedDistances, copyIndexesToSort, copyPrecomputedDistances, copyTransforms) {
  8692. const sortStartTime = performance.now();
  8693. if (!useSharedMemory) {
  8694. const indexesToSort = new Uint32Array(wasmMemory, indexesToSortOffset, copyIndexesToSort.byteLength / Constants.BytesPerInt);
  8695. indexesToSort.set(copyIndexesToSort);
  8696. const transforms = new Float32Array(wasmMemory, transformsOffset, copyTransforms.byteLength / Constants.BytesPerFloat);
  8697. transforms.set(copyTransforms);
  8698. if (usePrecomputedDistances) {
  8699. let precomputedDistances;
  8700. if (integerBasedSort) {
  8701. precomputedDistances = new Int32Array(wasmMemory, precomputedDistancesOffset,
  8702. copyPrecomputedDistances.byteLength / Constants.BytesPerInt);
  8703. } else {
  8704. precomputedDistances = new Float32Array(wasmMemory, precomputedDistancesOffset,
  8705. copyPrecomputedDistances.byteLength / Constants.BytesPerFloat);
  8706. }
  8707. precomputedDistances.set(copyPrecomputedDistances);
  8708. }
  8709. }
  8710. if (!countsZero) countsZero = new Uint32Array(Constants.DepthMapRange);
  8711. new Float32Array(wasmMemory, modelViewProjOffset, 16).set(modelViewProj);
  8712. new Uint32Array(wasmMemory, frequenciesOffset, Constants.DepthMapRange).set(countsZero);
  8713. wasmInstance.exports.sortIndexes(indexesToSortOffset, centersOffset, precomputedDistancesOffset,
  8714. mappedDistancesOffset, frequenciesOffset, modelViewProjOffset,
  8715. sortedIndexesOffset, sceneIndexesOffset, transformsOffset, Constants.DepthMapRange,
  8716. splatSortCount, splatRenderCount, splatCount, usePrecomputedDistances, integerBasedSort,
  8717. dynamicMode);
  8718. const sortMessage = {
  8719. 'sortDone': true,
  8720. 'splatSortCount': splatSortCount,
  8721. 'splatRenderCount': splatRenderCount,
  8722. 'sortTime': 0
  8723. };
  8724. if (!useSharedMemory) {
  8725. const sortedIndexes = new Uint32Array(wasmMemory, sortedIndexesOffset, splatRenderCount);
  8726. if (!sortedIndexesOut || sortedIndexesOut.length < splatRenderCount) {
  8727. sortedIndexesOut = new Uint32Array(splatRenderCount);
  8728. }
  8729. sortedIndexesOut.set(sortedIndexes);
  8730. sortMessage.sortedIndexes = sortedIndexesOut;
  8731. }
  8732. const sortEndTime = performance.now();
  8733. sortMessage.sortTime = sortEndTime - sortStartTime;
  8734. self.postMessage(sortMessage);
  8735. }
  8736. self.onmessage = (e) => {
  8737. if (e.data.centers) {
  8738. centers = e.data.centers;
  8739. sceneIndexes = e.data.sceneIndexes;
  8740. if (integerBasedSort) {
  8741. new Int32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerInt * 4,
  8742. e.data.range.count * 4).set(new Int32Array(centers));
  8743. } else {
  8744. new Float32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerFloat * 4,
  8745. e.data.range.count * 4).set(new Float32Array(centers));
  8746. }
  8747. if (dynamicMode) {
  8748. new Uint32Array(wasmMemory, sceneIndexesOffset + e.data.range.from * 4,
  8749. e.data.range.count).set(new Uint32Array(sceneIndexes));
  8750. }
  8751. self.postMessage({
  8752. 'centerDataSet': true,
  8753. });
  8754. } else if (e.data.sort) {
  8755. const renderCount = e.data.sort.splatRenderCount || 0;
  8756. const sortCount = e.data.sort.splatSortCount || 0;
  8757. const usePrecomputedDistances = e.data.sort.usePrecomputedDistances;
  8758. let copyIndexesToSort;
  8759. let copyPrecomputedDistances;
  8760. let copyTransforms;
  8761. if (!useSharedMemory) {
  8762. copyIndexesToSort = e.data.sort.indexesToSort;
  8763. copyTransforms = e.data.sort.transforms;
  8764. if (usePrecomputedDistances) copyPrecomputedDistances = e.data.sort.precomputedDistances;
  8765. }
  8766. sort(sortCount, renderCount, e.data.sort.modelViewProj, usePrecomputedDistances,
  8767. copyIndexesToSort, copyPrecomputedDistances, copyTransforms);
  8768. } else if (e.data.init) {
  8769. // Yep, this is super hacky and gross :(
  8770. Constants = e.data.init.Constants;
  8771. splatCount = e.data.init.splatCount;
  8772. useSharedMemory = e.data.init.useSharedMemory;
  8773. integerBasedSort = e.data.init.integerBasedSort;
  8774. dynamicMode = e.data.init.dynamicMode;
  8775. const CENTERS_BYTES_PER_ENTRY = integerBasedSort ? (Constants.BytesPerInt * 4) : (Constants.BytesPerFloat * 4);
  8776. const sorterWasmBytes = new Uint8Array(e.data.init.sorterWasmBytes);
  8777. const matrixSize = 16 * Constants.BytesPerFloat;
  8778. const memoryRequiredForIndexesToSort = splatCount * Constants.BytesPerInt;
  8779. const memoryRequiredForCenters = splatCount * CENTERS_BYTES_PER_ENTRY;
  8780. const memoryRequiredForModelViewProjectionMatrix = matrixSize;
  8781. const memoryRequiredForPrecomputedDistances = integerBasedSort ?
  8782. (splatCount * Constants.BytesPerInt) : (splatCount * Constants.BytesPerFloat);
  8783. const memoryRequiredForMappedDistances = splatCount * Constants.BytesPerInt;
  8784. const memoryRequiredForSortedIndexes = splatCount * Constants.BytesPerInt;
  8785. const memoryRequiredForIntermediateSortBuffers = Constants.DepthMapRange * Constants.BytesPerInt * 2;
  8786. const memoryRequiredforTransformIndexes = dynamicMode ? (splatCount * Constants.BytesPerInt) : 0;
  8787. const memoryRequiredforTransforms = dynamicMode ? (Constants.MaxScenes * matrixSize) : 0;
  8788. const extraMemory = Constants.MemoryPageSize * 32;
  8789. const totalRequiredMemory = memoryRequiredForIndexesToSort +
  8790. memoryRequiredForCenters +
  8791. memoryRequiredForModelViewProjectionMatrix +
  8792. memoryRequiredForPrecomputedDistances +
  8793. memoryRequiredForMappedDistances +
  8794. memoryRequiredForIntermediateSortBuffers +
  8795. memoryRequiredForSortedIndexes +
  8796. memoryRequiredforTransformIndexes +
  8797. memoryRequiredforTransforms +
  8798. extraMemory;
  8799. const totalPagesRequired = Math.floor(totalRequiredMemory / Constants.MemoryPageSize ) + 1;
  8800. const sorterWasmImport = {
  8801. module: {},
  8802. env: {
  8803. memory: new WebAssembly.Memory({
  8804. initial: totalPagesRequired,
  8805. maximum: totalPagesRequired,
  8806. shared: true,
  8807. }),
  8808. }
  8809. };
  8810. WebAssembly.compile(sorterWasmBytes)
  8811. .then((wasmModule) => {
  8812. return WebAssembly.instantiate(wasmModule, sorterWasmImport);
  8813. })
  8814. .then((instance) => {
  8815. wasmInstance = instance;
  8816. indexesToSortOffset = 0;
  8817. centersOffset = indexesToSortOffset + memoryRequiredForIndexesToSort;
  8818. modelViewProjOffset = centersOffset + memoryRequiredForCenters;
  8819. precomputedDistancesOffset = modelViewProjOffset + memoryRequiredForModelViewProjectionMatrix;
  8820. mappedDistancesOffset = precomputedDistancesOffset + memoryRequiredForPrecomputedDistances;
  8821. frequenciesOffset = mappedDistancesOffset + memoryRequiredForMappedDistances;
  8822. sortedIndexesOffset = frequenciesOffset + memoryRequiredForIntermediateSortBuffers;
  8823. sceneIndexesOffset = sortedIndexesOffset + memoryRequiredForSortedIndexes;
  8824. transformsOffset = sceneIndexesOffset + memoryRequiredforTransformIndexes;
  8825. wasmMemory = sorterWasmImport.env.memory.buffer;
  8826. if (useSharedMemory) {
  8827. self.postMessage({
  8828. 'sortSetupPhase1Complete': true,
  8829. 'indexesToSortBuffer': wasmMemory,
  8830. 'indexesToSortOffset': indexesToSortOffset,
  8831. 'sortedIndexesBuffer': wasmMemory,
  8832. 'sortedIndexesOffset': sortedIndexesOffset,
  8833. 'precomputedDistancesBuffer': wasmMemory,
  8834. 'precomputedDistancesOffset': precomputedDistancesOffset,
  8835. 'transformsBuffer': wasmMemory,
  8836. 'transformsOffset': transformsOffset
  8837. });
  8838. } else {
  8839. self.postMessage({
  8840. 'sortSetupPhase1Complete': true
  8841. });
  8842. }
  8843. });
  8844. }
  8845. };
  8846. }
  8847. function createSortWorker(splatCount, useSharedMemory, enableSIMDInSort, integerBasedSort, dynamicMode) {
  8848. const worker = new Worker(
  8849. URL.createObjectURL(
  8850. new Blob(['(', sortWorker.toString(), ')(self)'], {
  8851. type: 'application/javascript',
  8852. }),
  8853. ),
  8854. );
  8855. let sourceWasm = SorterWasm;
  8856. // iOS makes choosing the right WebAssembly configuration tricky :(
  8857. let iOSSemVer = isIOS() ? getIOSSemever() : null;
  8858. if (!enableSIMDInSort && !useSharedMemory) {
  8859. sourceWasm = SorterWasmNoSIMD;
  8860. if (iOSSemVer && iOSSemVer.major < 16 && iOSSemVer.minor < 4) {
  8861. sourceWasm = SorterWasmNoSIMDNonShared;
  8862. }
  8863. } else if (!enableSIMDInSort) {
  8864. sourceWasm = SorterWasmNoSIMD;
  8865. } else if (!useSharedMemory) {
  8866. if (iOSSemVer && iOSSemVer.major < 16 && iOSSemVer.minor < 4) {
  8867. sourceWasm = SorterWasmNonShared;
  8868. }
  8869. }
  8870. const sorterWasmBinaryString = atob(sourceWasm);
  8871. const sorterWasmBytes = new Uint8Array(sorterWasmBinaryString.length);
  8872. for (let i = 0; i < sorterWasmBinaryString.length; i++) {
  8873. sorterWasmBytes[i] = sorterWasmBinaryString.charCodeAt(i);
  8874. }
  8875. worker.postMessage({
  8876. 'init': {
  8877. 'sorterWasmBytes': sorterWasmBytes.buffer,
  8878. 'splatCount': splatCount,
  8879. 'useSharedMemory': useSharedMemory,
  8880. 'integerBasedSort': integerBasedSort,
  8881. 'dynamicMode': dynamicMode,
  8882. // Super hacky
  8883. 'Constants': {
  8884. 'BytesPerFloat': Constants.BytesPerFloat,
  8885. 'BytesPerInt': Constants.BytesPerInt,
  8886. 'DepthMapRange': Constants.DepthMapRange,
  8887. 'MemoryPageSize': Constants.MemoryPageSize,
  8888. 'MaxScenes': Constants.MaxScenes
  8889. }
  8890. }
  8891. });
  8892. return worker;
  8893. }
  8894. const WebXRMode = {
  8895. None: 0,
  8896. VR: 1,
  8897. AR: 2
  8898. };
  8899. /*
  8900. Copyright © 2010-2024 three.js authors & Mark Kellogg
  8901. Permission is hereby granted, free of charge, to any person obtaining a copy
  8902. of this software and associated documentation files (the "Software"), to deal
  8903. in the Software without restriction, including without limitation the rights
  8904. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8905. copies of the Software, and to permit persons to whom the Software is
  8906. furnished to do so, subject to the following conditions:
  8907. The above copyright notice and this permission notice shall be included in
  8908. all copies or substantial portions of the Software.
  8909. */
  8910. class VRButton {
  8911. static createButton( renderer ) {
  8912. const button = document.createElement( 'button' );
  8913. function showEnterVR( /* device */ ) {
  8914. let currentSession = null;
  8915. async function onSessionStarted( session ) {
  8916. session.addEventListener( 'end', onSessionEnded );
  8917. await renderer.xr.setSession( session );
  8918. button.textContent = 'EXIT VR';
  8919. currentSession = session;
  8920. }
  8921. function onSessionEnded( /* event */ ) {
  8922. currentSession.removeEventListener( 'end', onSessionEnded );
  8923. button.textContent = 'ENTER VR';
  8924. currentSession = null;
  8925. }
  8926. //
  8927. button.style.display = '';
  8928. button.style.cursor = 'pointer';
  8929. button.style.left = 'calc(50% - 50px)';
  8930. button.style.width = '100px';
  8931. button.textContent = 'ENTER VR';
  8932. // WebXR's requestReferenceSpace only works if the corresponding feature
  8933. // was requested at session creation time. For simplicity, just ask for
  8934. // the interesting ones as optional features, but be aware that the
  8935. // requestReferenceSpace call will fail if it turns out to be unavailable.
  8936. // ('local' is always available for immersive sessions and doesn't need to
  8937. // be requested separately.)
  8938. const sessionInit = { optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking', 'layers'] };
  8939. button.onmouseenter = function() {
  8940. button.style.opacity = '1.0';
  8941. };
  8942. button.onmouseleave = function() {
  8943. button.style.opacity = '0.5';
  8944. };
  8945. button.onclick = function() {
  8946. if ( currentSession === null ) {
  8947. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  8948. } else {
  8949. currentSession.end();
  8950. if ( navigator.xr.offerSession !== undefined ) {
  8951. navigator.xr.offerSession( 'immersive-vr', sessionInit )
  8952. .then( onSessionStarted )
  8953. .catch( ( err ) => {
  8954. console.warn( err );
  8955. } );
  8956. }
  8957. }
  8958. };
  8959. if ( navigator.xr.offerSession !== undefined ) {
  8960. navigator.xr.offerSession( 'immersive-vr', sessionInit )
  8961. .then( onSessionStarted )
  8962. .catch( ( err ) => {
  8963. console.warn( err );
  8964. } );
  8965. }
  8966. }
  8967. function disableButton() {
  8968. button.style.display = '';
  8969. button.style.cursor = 'auto';
  8970. button.style.left = 'calc(50% - 75px)';
  8971. button.style.width = '150px';
  8972. button.onmouseenter = null;
  8973. button.onmouseleave = null;
  8974. button.onclick = null;
  8975. }
  8976. function showWebXRNotFound() {
  8977. disableButton();
  8978. button.textContent = 'VR NOT SUPPORTED';
  8979. }
  8980. function showVRNotAllowed( exception ) {
  8981. disableButton();
  8982. console.warn( 'Exception when trying to call xr.isSessionSupported', exception );
  8983. button.textContent = 'VR NOT ALLOWED';
  8984. }
  8985. function stylizeElement( element ) {
  8986. element.style.position = 'absolute';
  8987. element.style.bottom = '20px';
  8988. element.style.padding = '12px 6px';
  8989. element.style.border = '1px solid #fff';
  8990. element.style.borderRadius = '4px';
  8991. element.style.background = 'rgba(0,0,0,0.1)';
  8992. element.style.color = '#fff';
  8993. element.style.font = 'normal 13px sans-serif';
  8994. element.style.textAlign = 'center';
  8995. element.style.opacity = '0.5';
  8996. element.style.outline = 'none';
  8997. element.style.zIndex = '999';
  8998. }
  8999. if ( 'xr' in navigator ) {
  9000. button.id = 'VRButton';
  9001. button.style.display = 'none';
  9002. stylizeElement( button );
  9003. navigator.xr.isSessionSupported( 'immersive-vr' ).then( function( supported ) {
  9004. supported ? showEnterVR() : showWebXRNotFound();
  9005. if ( supported && VRButton.xrSessionIsGranted ) {
  9006. button.click();
  9007. }
  9008. } ).catch( showVRNotAllowed );
  9009. return button;
  9010. } else {
  9011. const message = document.createElement( 'a' );
  9012. if ( window.isSecureContext === false ) {
  9013. message.href = document.location.href.replace( /^http:/, 'https:' );
  9014. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  9015. } else {
  9016. message.href = 'https://immersiveweb.dev/';
  9017. message.innerHTML = 'WEBXR NOT AVAILABLE';
  9018. }
  9019. message.style.left = 'calc(50% - 90px)';
  9020. message.style.width = '180px';
  9021. message.style.textDecoration = 'none';
  9022. stylizeElement( message );
  9023. return message;
  9024. }
  9025. }
  9026. static registerSessionGrantedListener() {
  9027. if ( typeof navigator !== 'undefined' && 'xr' in navigator ) {
  9028. // WebXRViewer (based on Firefox) has a bug where addEventListener
  9029. // throws a silent exception and aborts execution entirely.
  9030. if ( /WebXRViewer\//i.test( navigator.userAgent ) ) return;
  9031. navigator.xr.addEventListener( 'sessiongranted', () => {
  9032. VRButton.xrSessionIsGranted = true;
  9033. } );
  9034. }
  9035. }
  9036. }
  9037. VRButton.xrSessionIsGranted = false;
  9038. VRButton.registerSessionGrantedListener();
  9039. /*
  9040. Copyright © 2010-2024 three.js authors & Mark Kellogg
  9041. Permission is hereby granted, free of charge, to any person obtaining a copy
  9042. of this software and associated documentation files (the "Software"), to deal
  9043. in the Software without restriction, including without limitation the rights
  9044. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9045. copies of the Software, and to permit persons to whom the Software is
  9046. furnished to do so, subject to the following conditions:
  9047. The above copyright notice and this permission notice shall be included in
  9048. all copies or substantial portions of the Software.
  9049. */
  9050. class ARButton {
  9051. static createButton( renderer, sessionInit = {} ) {
  9052. const button = document.createElement( 'button' );
  9053. function showStartAR( /* device */ ) {
  9054. if ( sessionInit.domOverlay === undefined ) {
  9055. const overlay = document.createElement( 'div' );
  9056. overlay.style.display = 'none';
  9057. document.body.appendChild( overlay );
  9058. const svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
  9059. svg.setAttribute( 'width', 38 );
  9060. svg.setAttribute( 'height', 38 );
  9061. svg.style.position = 'absolute';
  9062. svg.style.right = '20px';
  9063. svg.style.top = '20px';
  9064. svg.addEventListener( 'click', function() {
  9065. currentSession.end();
  9066. } );
  9067. overlay.appendChild( svg );
  9068. const path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  9069. path.setAttribute( 'd', 'M 12,12 L 28,28 M 28,12 12,28' );
  9070. path.setAttribute( 'stroke', '#fff' );
  9071. path.setAttribute( 'stroke-width', 2 );
  9072. svg.appendChild( path );
  9073. if ( sessionInit.optionalFeatures === undefined ) {
  9074. sessionInit.optionalFeatures = [];
  9075. }
  9076. sessionInit.optionalFeatures.push( 'dom-overlay' );
  9077. sessionInit.domOverlay = { root: overlay };
  9078. }
  9079. //
  9080. let currentSession = null;
  9081. async function onSessionStarted( session ) {
  9082. session.addEventListener( 'end', onSessionEnded );
  9083. renderer.xr.setReferenceSpaceType( 'local' );
  9084. await renderer.xr.setSession( session );
  9085. button.textContent = 'STOP AR';
  9086. sessionInit.domOverlay.root.style.display = '';
  9087. currentSession = session;
  9088. }
  9089. function onSessionEnded( /* event */ ) {
  9090. currentSession.removeEventListener( 'end', onSessionEnded );
  9091. button.textContent = 'START AR';
  9092. sessionInit.domOverlay.root.style.display = 'none';
  9093. currentSession = null;
  9094. }
  9095. //
  9096. button.style.display = '';
  9097. button.style.cursor = 'pointer';
  9098. button.style.left = 'calc(50% - 50px)';
  9099. button.style.width = '100px';
  9100. button.textContent = 'START AR';
  9101. button.onmouseenter = function() {
  9102. button.style.opacity = '1.0';
  9103. };
  9104. button.onmouseleave = function() {
  9105. button.style.opacity = '0.5';
  9106. };
  9107. button.onclick = function() {
  9108. if ( currentSession === null ) {
  9109. navigator.xr.requestSession( 'immersive-ar', sessionInit ).then( onSessionStarted );
  9110. } else {
  9111. currentSession.end();
  9112. if ( navigator.xr.offerSession !== undefined ) {
  9113. navigator.xr.offerSession( 'immersive-ar', sessionInit )
  9114. .then( onSessionStarted )
  9115. .catch( ( err ) => {
  9116. console.warn( err );
  9117. } );
  9118. }
  9119. }
  9120. };
  9121. if ( navigator.xr.offerSession !== undefined ) {
  9122. navigator.xr.offerSession( 'immersive-ar', sessionInit )
  9123. .then( onSessionStarted )
  9124. .catch( ( err ) => {
  9125. console.warn( err );
  9126. } );
  9127. }
  9128. }
  9129. function disableButton() {
  9130. button.style.display = '';
  9131. button.style.cursor = 'auto';
  9132. button.style.left = 'calc(50% - 75px)';
  9133. button.style.width = '150px';
  9134. button.onmouseenter = null;
  9135. button.onmouseleave = null;
  9136. button.onclick = null;
  9137. }
  9138. function showARNotSupported() {
  9139. disableButton();
  9140. button.textContent = 'AR NOT SUPPORTED';
  9141. }
  9142. function showARNotAllowed( exception ) {
  9143. disableButton();
  9144. console.warn( 'Exception when trying to call xr.isSessionSupported', exception );
  9145. button.textContent = 'AR NOT ALLOWED';
  9146. }
  9147. function stylizeElement( element ) {
  9148. element.style.position = 'absolute';
  9149. element.style.bottom = '20px';
  9150. element.style.padding = '12px 6px';
  9151. element.style.border = '1px solid #fff';
  9152. element.style.borderRadius = '4px';
  9153. element.style.background = 'rgba(0,0,0,0.1)';
  9154. element.style.color = '#fff';
  9155. element.style.font = 'normal 13px sans-serif';
  9156. element.style.textAlign = 'center';
  9157. element.style.opacity = '0.5';
  9158. element.style.outline = 'none';
  9159. element.style.zIndex = '999';
  9160. }
  9161. if ( 'xr' in navigator ) {
  9162. button.id = 'ARButton';
  9163. button.style.display = 'none';
  9164. stylizeElement( button );
  9165. navigator.xr.isSessionSupported( 'immersive-ar' ).then( function( supported ) {
  9166. supported ? showStartAR() : showARNotSupported();
  9167. } ).catch( showARNotAllowed );
  9168. return button;
  9169. } else {
  9170. const message = document.createElement( 'a' );
  9171. if ( window.isSecureContext === false ) {
  9172. message.href = document.location.href.replace( /^http:/, 'https:' );
  9173. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  9174. } else {
  9175. message.href = 'https://immersiveweb.dev/';
  9176. message.innerHTML = 'WEBXR NOT AVAILABLE';
  9177. }
  9178. message.style.left = 'calc(50% - 90px)';
  9179. message.style.width = '180px';
  9180. message.style.textDecoration = 'none';
  9181. stylizeElement( message );
  9182. return message;
  9183. }
  9184. }
  9185. }
  9186. const RenderMode = {
  9187. Always: 0,
  9188. OnChange: 1,
  9189. Never: 2
  9190. };
  9191. const THREE_CAMERA_FOV = 50;
  9192. const MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT = .75;
  9193. const MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER = 1500000;
  9194. const FOCUS_MARKER_FADE_IN_SPEED = 10.0;
  9195. const FOCUS_MARKER_FADE_OUT_SPEED = 2.5;
  9196. const CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION = 60;
  9197. /**
  9198. * Viewer: Manages the rendering of splat scenes. Manages an instance of SplatMesh as well as a web worker
  9199. * that performs the sort for its splats.
  9200. */
  9201. class Viewer {
  9202. constructor(options = {}) {
  9203. // The natural 'up' vector for viewing the scene (only has an effect when used with orbit controls and
  9204. // when the viewer uses its own camera).
  9205. if (!options.cameraUp) options.cameraUp = [0, 1, 0];
  9206. this.cameraUp = new THREE.Vector3().fromArray(options.cameraUp);
  9207. // The camera's initial position (only used when the viewer uses its own camera).
  9208. if (!options.initialCameraPosition) options.initialCameraPosition = [0, 10, 15];
  9209. this.initialCameraPosition = new THREE.Vector3().fromArray(options.initialCameraPosition);
  9210. // The initial focal point of the camera and center of the camera's orbit (only used when the viewer uses its own camera).
  9211. if (!options.initialCameraLookAt) options.initialCameraLookAt = [0, 0, 0];
  9212. this.initialCameraLookAt = new THREE.Vector3().fromArray(options.initialCameraLookAt);
  9213. // 'dropInMode' is a flag that is used internally to support the usage of the viewer as a Three.js scene object
  9214. this.dropInMode = options.dropInMode || false;
  9215. // If 'selfDrivenMode' is true, the viewer manages its own update/animation loop via requestAnimationFrame()
  9216. if (options.selfDrivenMode === undefined || options.selfDrivenMode === null) options.selfDrivenMode = true;
  9217. this.selfDrivenMode = options.selfDrivenMode && !this.dropInMode;
  9218. this.selfDrivenUpdateFunc = this.selfDrivenUpdate.bind(this);
  9219. // If 'useBuiltInControls' is true, the viewer will create its own instance of OrbitControls and attach to the camera
  9220. if (options.useBuiltInControls === undefined) options.useBuiltInControls = true;
  9221. this.useBuiltInControls = options.useBuiltInControls;
  9222. // parent element of the Three.js renderer canvas
  9223. this.rootElement = options.rootElement;
  9224. // Tells the viewer to pretend the device pixel ratio is 1, which can boost performance on devices where it is larger,
  9225. // at a small cost to visual quality
  9226. this.ignoreDevicePixelRatio = options.ignoreDevicePixelRatio || false;
  9227. this.devicePixelRatio = this.ignoreDevicePixelRatio ? 1 : window.devicePixelRatio;
  9228. // Tells the viewer to use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit
  9229. this.halfPrecisionCovariancesOnGPU = options.halfPrecisionCovariancesOnGPU || false;
  9230. // If 'threeScene' is valid, it will be rendered by the viewer along with the splat mesh
  9231. this.threeScene = options.threeScene;
  9232. // Allows for usage of an external Three.js renderer
  9233. this.renderer = options.renderer;
  9234. // Allows for usage of an external Three.js camera
  9235. this.camera = options.camera;
  9236. // If 'gpuAcceleratedSort' is true, a partially GPU-accelerated approach to sorting splats will be used.
  9237. // Currently this means pre-computing splat distances from the camera on the GPU
  9238. this.gpuAcceleratedSort = options.gpuAcceleratedSort || false;
  9239. // if 'integerBasedSort' is true, the integer version of splat centers as well as other values used to calculate
  9240. // splat distances are used instead of the float version. This speeds up computation, but introduces the possibility of
  9241. // overflow in larger scenes.
  9242. if (options.integerBasedSort === undefined || options.integerBasedSort === null) {
  9243. options.integerBasedSort = true;
  9244. }
  9245. this.integerBasedSort = options.integerBasedSort;
  9246. // If 'sharedMemoryForWorkers' is true, a SharedArrayBuffer will be used to communicate with web workers. This method
  9247. // is faster than copying memory to or from web workers, but comes with security implications as outlined here:
  9248. // https://web.dev/articles/cross-origin-isolation-guide
  9249. // If enabled, it requires specific CORS headers to be present in the response from the server that is sent when
  9250. // loading the application. More information is available in the README.
  9251. if (options.sharedMemoryForWorkers === undefined || options.sharedMemoryForWorkers === null) options.sharedMemoryForWorkers = true;
  9252. this.sharedMemoryForWorkers = options.sharedMemoryForWorkers;
  9253. // if 'dynamicScene' is true, it tells the viewer to assume scene elements are not stationary or that the number of splats in the
  9254. // scene may change. This prevents optimizations that depend on a static scene from being made. Additionally, if 'dynamicScene' is
  9255. // true it tells the splat mesh to not apply scene tranforms to splat data that is returned by functions like
  9256. // SplatMesh.getSplatCenter() by default.
  9257. this.dynamicScene = !!options.dynamicScene;
  9258. // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a
  9259. // substantially different resolution than that at which they were rendered during training. This will only work correctly
  9260. // for models that were trained using a process that utilizes this compensation calculation. For more details:
  9261. // https://github.com/nerfstudio-project/gsplat/pull/117
  9262. // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093
  9263. this.antialiased = options.antialiased || false;
  9264. this.webXRMode = options.webXRMode || WebXRMode.None;
  9265. if (this.webXRMode !== WebXRMode.None) {
  9266. this.gpuAcceleratedSort = false;
  9267. }
  9268. this.webXRActive = false;
  9269. // if 'renderMode' is RenderMode.Always, then the viewer will rrender the scene on every update. If it is RenderMode.OnChange,
  9270. // it will only render when something in the scene has changed.
  9271. this.renderMode = options.renderMode || RenderMode.Always;
  9272. // SceneRevealMode.Default results in a nice, slow fade-in effect for progressively loaded scenes,
  9273. // and a fast fade-in for non progressively loaded scenes.
  9274. // SceneRevealMode.Gradual will force a slow fade-in for all scenes.
  9275. // SceneRevealMode.Instant will force all loaded scene data to be immediately visible.
  9276. this.sceneRevealMode = options.sceneRevealMode || SceneRevealMode.Default;
  9277. // Hacky, experimental, non-scientific parameter for tweaking focal length related calculations. For scenes with very
  9278. // small gaussians, small details, and small dimensions -- increasing this value can help improve visual quality.
  9279. this.focalAdjustment = options.focalAdjustment || 1.0;
  9280. // Specify the maximum screen-space splat size, can help deal with large splats that get too unwieldy
  9281. this.maxScreenSpaceSplatSize = options.maxScreenSpaceSplatSize || 1024;
  9282. // The verbosity of console logging
  9283. this.logLevel = options.logLevel || LogLevel.None;
  9284. // Degree of spherical harmonics to utilize in rendering splats (assuming the data is present in the splat scene).
  9285. // Valid values are 0 - 2. Default value is 0.
  9286. this.sphericalHarmonicsDegree = options.sphericalHarmonicsDegree || 0;
  9287. // When true, allows for usage of extra properties and attributes during rendering for effects such as opacity adjustment.
  9288. // Default is false for performance reasons. These properties are separate from transform properties (scale, rotation, position)
  9289. // that are enabled by the 'dynamicScene' parameter.
  9290. this.enableOptionalEffects = options.enableOptionalEffects || false;
  9291. // Enable the usage of SIMD WebAssembly instructions for the splat sort
  9292. if (options.enableSIMDInSort === undefined || options.enableSIMDInSort === null) options.enableSIMDInSort = true;
  9293. this.enableSIMDInSort = options.enableSIMDInSort;
  9294. // Level to compress PLY files when loading them for direct rendering (not exporting to .ksplat)
  9295. if (options.plyInMemoryCompressionLevel === undefined || options.plyInMemoryCompressionLevel === null) {
  9296. options.plyInMemoryCompressionLevel = 2;
  9297. }
  9298. this.plyInMemoryCompressionLevel = options.plyInMemoryCompressionLevel;
  9299. // When true, the intermediate splat data that is the result of decompressing splat bufffer(s) and is used to
  9300. // populate the data textures will be freed. This will reduces memory usage, but if that data needs to be modified
  9301. // it will need to be re-populated from the splat buffer(s). Default is false.
  9302. if (options.freeIntermediateSplatData === undefined || options.freeIntermediateSplatData === null) {
  9303. options.freeIntermediateSplatData = false;
  9304. }
  9305. this.freeIntermediateSplatData = options.freeIntermediateSplatData;
  9306. // It appears that for certain iOS versions, special actions need to be taken with the
  9307. // usage of SIMD instructions and shared memory
  9308. if (isIOS()) {
  9309. const semver = getIOSSemever();
  9310. if (semver.major < 17) {
  9311. this.enableSIMDInSort = false;
  9312. }
  9313. if (semver.major < 16) {
  9314. this.sharedMemoryForWorkers = false;
  9315. }
  9316. }
  9317. // Tell the viewer how to render the splats
  9318. if (options.splatRenderMode === undefined || options.splatRenderMode === null) {
  9319. options.splatRenderMode = SplatRenderMode.ThreeD;
  9320. }
  9321. this.splatRenderMode = options.splatRenderMode;
  9322. this.onSplatMeshChangedCallback = null;
  9323. this.createSplatMesh();
  9324. this.controls = null;
  9325. this.perspectiveControls = null;
  9326. this.orthographicControls = null;
  9327. this.orthographicCamera = null;
  9328. this.perspectiveCamera = null;
  9329. this.showMeshCursor = false;
  9330. this.showControlPlane = false;
  9331. this.showInfo = false;
  9332. this.sceneHelper = null;
  9333. this.sortWorker = null;
  9334. this.sortRunning = false;
  9335. this.splatRenderCount = 0;
  9336. this.sortWorkerIndexesToSort = null;
  9337. this.sortWorkerSortedIndexes = null;
  9338. this.sortWorkerPrecomputedDistances = null;
  9339. this.sortWorkerTransforms = null;
  9340. this.runAfterNextSort = [];
  9341. this.selfDrivenModeRunning = false;
  9342. this.splatRenderReady = false;
  9343. this.raycaster = new Raycaster();
  9344. this.infoPanel = null;
  9345. this.startInOrthographicMode = false;
  9346. this.currentFPS = 0;
  9347. this.lastSortTime = 0;
  9348. this.consecutiveRenderFrames = 0;
  9349. this.previousCameraTarget = new THREE.Vector3();
  9350. this.nextCameraTarget = new THREE.Vector3();
  9351. this.mousePosition = new THREE.Vector2();
  9352. this.mouseDownPosition = new THREE.Vector2();
  9353. this.mouseDownTime = null;
  9354. this.resizeObserver = null;
  9355. this.mouseMoveListener = null;
  9356. this.mouseDownListener = null;
  9357. this.mouseUpListener = null;
  9358. this.keyDownListener = null;
  9359. this.sortPromise = null;
  9360. this.sortPromiseResolver = null;
  9361. this.splatSceneDownloadPromises = {};
  9362. this.splatSceneDownloadAndBuildPromise = null;
  9363. this.splatSceneRemovalPromise = null;
  9364. this.loadingSpinner = new LoadingSpinner(null, this.rootElement || document.body);
  9365. this.loadingSpinner.hide();
  9366. this.loadingProgressBar = new LoadingProgressBar(this.rootElement || document.body);
  9367. this.loadingProgressBar.hide();
  9368. this.infoPanel = new InfoPanel(this.rootElement || document.body);
  9369. this.infoPanel.hide();
  9370. this.usingExternalCamera = (this.dropInMode || this.camera) ? true : false;
  9371. this.usingExternalRenderer = (this.dropInMode || this.renderer) ? true : false;
  9372. this.initialized = false;
  9373. this.disposing = false;
  9374. this.disposed = false;
  9375. this.disposePromise = null;
  9376. if (!this.dropInMode) this.init();
  9377. }
  9378. createSplatMesh() {
  9379. this.splatMesh = new SplatMesh(this.splatRenderMode, this.dynamicScene, this.enableOptionalEffects,
  9380. this.halfPrecisionCovariancesOnGPU, this.devicePixelRatio, this.gpuAcceleratedSort,
  9381. this.integerBasedSort, this.antialiased, this.maxScreenSpaceSplatSize, this.logLevel,
  9382. this.sphericalHarmonicsDegree);
  9383. this.splatMesh.frustumCulled = false;
  9384. if (this.onSplatMeshChangedCallback) this.onSplatMeshChangedCallback();
  9385. }
  9386. init() {
  9387. if (this.initialized) return;
  9388. if (!this.rootElement) {
  9389. if (!this.usingExternalRenderer) {
  9390. this.rootElement = document.createElement('div');
  9391. this.rootElement.style.width = '100%';
  9392. this.rootElement.style.height = '100%';
  9393. this.rootElement.style.position = 'absolute';
  9394. document.body.appendChild(this.rootElement);
  9395. } else {
  9396. this.rootElement = this.renderer.domElement.parentElement || document.body;
  9397. }
  9398. }
  9399. this.setupCamera();
  9400. this.setupRenderer();
  9401. this.setupWebXR();
  9402. this.setupControls();
  9403. this.setupEventHandlers();
  9404. this.threeScene = this.threeScene || new THREE.Scene();
  9405. this.sceneHelper = new SceneHelper(this.threeScene);
  9406. this.sceneHelper.setupMeshCursor();
  9407. this.sceneHelper.setupFocusMarker();
  9408. this.sceneHelper.setupControlPlane();
  9409. this.loadingProgressBar.setContainer(this.rootElement);
  9410. this.loadingSpinner.setContainer(this.rootElement);
  9411. this.infoPanel.setContainer(this.rootElement);
  9412. this.initialized = true;
  9413. }
  9414. setupCamera() {
  9415. if (!this.usingExternalCamera) {
  9416. const renderDimensions = new THREE.Vector2();
  9417. this.getRenderDimensions(renderDimensions);
  9418. this.perspectiveCamera = new THREE.PerspectiveCamera(THREE_CAMERA_FOV, renderDimensions.x / renderDimensions.y, 0.1, 1000);
  9419. this.orthographicCamera = new THREE.OrthographicCamera(renderDimensions.x / -2, renderDimensions.x / 2,
  9420. renderDimensions.y / 2, renderDimensions.y / -2, 0.1, 1000 );
  9421. this.camera = this.startInOrthographicMode ? this.orthographicCamera : this.perspectiveCamera;
  9422. this.camera.position.copy(this.initialCameraPosition);
  9423. this.camera.up.copy(this.cameraUp).normalize();
  9424. this.camera.lookAt(this.initialCameraLookAt);
  9425. }
  9426. }
  9427. setupRenderer() {
  9428. if (!this.usingExternalRenderer) {
  9429. const renderDimensions = new THREE.Vector2();
  9430. this.getRenderDimensions(renderDimensions);
  9431. this.renderer = new THREE.WebGLRenderer({
  9432. antialias: false,
  9433. precision: 'highp'
  9434. });
  9435. this.renderer.setPixelRatio(this.devicePixelRatio);
  9436. this.renderer.autoClear = true;
  9437. this.renderer.setClearColor(new THREE.Color( 0x000000 ), 0.0);
  9438. this.renderer.setSize(renderDimensions.x, renderDimensions.y);
  9439. this.resizeObserver = new ResizeObserver(() => {
  9440. this.getRenderDimensions(renderDimensions);
  9441. this.renderer.setSize(renderDimensions.x, renderDimensions.y);
  9442. this.forceRenderNextFrame();
  9443. });
  9444. this.resizeObserver.observe(this.rootElement);
  9445. this.rootElement.appendChild(this.renderer.domElement);
  9446. }
  9447. }
  9448. setupWebXR() {
  9449. if (this.webXRMode) {
  9450. if (this.webXRMode === WebXRMode.VR) {
  9451. this.rootElement.appendChild(VRButton.createButton(this.renderer));
  9452. } else if (this.webXRMode === WebXRMode.AR) {
  9453. this.rootElement.appendChild(ARButton.createButton(this.renderer));
  9454. }
  9455. this.renderer.xr.addEventListener('sessionstart', (e) => {
  9456. this.webXRActive = true;
  9457. });
  9458. this.renderer.xr.addEventListener('sessionend', (e) => {
  9459. this.webXRActive = false;
  9460. });
  9461. this.renderer.xr.enabled = true;
  9462. this.camera.position.copy(this.initialCameraPosition);
  9463. this.camera.up.copy(this.cameraUp).normalize();
  9464. this.camera.lookAt(this.initialCameraLookAt);
  9465. }
  9466. }
  9467. setupControls() {
  9468. if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) {
  9469. if (!this.usingExternalCamera) {
  9470. this.perspectiveControls = new OrbitControls(this.perspectiveCamera, this.renderer.domElement);
  9471. this.orthographicControls = new OrbitControls(this.orthographicCamera, this.renderer.domElement);
  9472. } else {
  9473. if (this.camera.isOrthographicCamera) {
  9474. this.orthographicControls = new OrbitControls(this.camera, this.renderer.domElement);
  9475. } else {
  9476. this.perspectiveControls = new OrbitControls(this.camera, this.renderer.domElement);
  9477. }
  9478. }
  9479. for (let controls of [this.orthographicControls, this.perspectiveControls,]) {
  9480. if (controls) {
  9481. controls.listenToKeyEvents(window);
  9482. controls.rotateSpeed = 0.5;
  9483. controls.maxPolarAngle = Math.PI * .75;
  9484. controls.minPolarAngle = 0.1;
  9485. controls.enableDamping = true;
  9486. controls.dampingFactor = 0.05;
  9487. controls.target.copy(this.initialCameraLookAt);
  9488. controls.update();
  9489. }
  9490. }
  9491. this.controls = this.camera.isOrthographicCamera ? this.orthographicControls : this.perspectiveControls;
  9492. this.controls.update();
  9493. }
  9494. }
  9495. setupEventHandlers() {
  9496. if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) {
  9497. this.mouseMoveListener = this.onMouseMove.bind(this);
  9498. this.renderer.domElement.addEventListener('pointermove', this.mouseMoveListener, false);
  9499. this.mouseDownListener = this.onMouseDown.bind(this);
  9500. this.renderer.domElement.addEventListener('pointerdown', this.mouseDownListener, false);
  9501. this.mouseUpListener = this.onMouseUp.bind(this);
  9502. this.renderer.domElement.addEventListener('pointerup', this.mouseUpListener, false);
  9503. this.keyDownListener = this.onKeyDown.bind(this);
  9504. window.addEventListener('keydown', this.keyDownListener, false);
  9505. }
  9506. }
  9507. removeEventHandlers() {
  9508. if (this.useBuiltInControls) {
  9509. this.renderer.domElement.removeEventListener('pointermove', this.mouseMoveListener);
  9510. this.mouseMoveListener = null;
  9511. this.renderer.domElement.removeEventListener('pointerdown', this.mouseDownListener);
  9512. this.mouseDownListener = null;
  9513. this.renderer.domElement.removeEventListener('pointerup', this.mouseUpListener);
  9514. this.mouseUpListener = null;
  9515. window.removeEventListener('keydown', this.keyDownListener);
  9516. this.keyDownListener = null;
  9517. }
  9518. }
  9519. setRenderMode(renderMode) {
  9520. this.renderMode = renderMode;
  9521. }
  9522. onSplatMeshChanged(callback) {
  9523. this.onSplatMeshChangedCallback = callback;
  9524. }
  9525. onKeyDown = function() {
  9526. const forward = new THREE.Vector3();
  9527. const tempMatrixLeft = new THREE.Matrix4();
  9528. const tempMatrixRight = new THREE.Matrix4();
  9529. return function(e) {
  9530. forward.set(0, 0, -1);
  9531. forward.transformDirection(this.camera.matrixWorld);
  9532. tempMatrixLeft.makeRotationAxis(forward, Math.PI / 128);
  9533. tempMatrixRight.makeRotationAxis(forward, -Math.PI / 128);
  9534. switch (e.code) {
  9535. case 'KeyG':
  9536. this.focalAdjustment += 0.02;
  9537. this.forceRenderNextFrame();
  9538. break;
  9539. case 'KeyF':
  9540. this.focalAdjustment -= 0.02;
  9541. this.forceRenderNextFrame();
  9542. break;
  9543. case 'ArrowLeft':
  9544. this.camera.up.transformDirection(tempMatrixLeft);
  9545. break;
  9546. case 'ArrowRight':
  9547. this.camera.up.transformDirection(tempMatrixRight);
  9548. break;
  9549. case 'KeyC':
  9550. this.showMeshCursor = !this.showMeshCursor;
  9551. break;
  9552. case 'KeyU':
  9553. this.showControlPlane = !this.showControlPlane;
  9554. break;
  9555. case 'KeyI':
  9556. this.showInfo = !this.showInfo;
  9557. if (this.showInfo) {
  9558. this.infoPanel.show();
  9559. } else {
  9560. this.infoPanel.hide();
  9561. }
  9562. break;
  9563. case 'KeyO':
  9564. if (!this.usingExternalCamera) {
  9565. this.setOrthographicMode(!this.camera.isOrthographicCamera);
  9566. }
  9567. break;
  9568. case 'KeyP':
  9569. if (!this.usingExternalCamera) {
  9570. this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled());
  9571. }
  9572. break;
  9573. case 'Equal':
  9574. if (!this.usingExternalCamera) {
  9575. this.splatMesh.setSplatScale(this.splatMesh.getSplatScale() + 0.05);
  9576. }
  9577. break;
  9578. case 'Minus':
  9579. if (!this.usingExternalCamera) {
  9580. this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale() - 0.05, 0.0));
  9581. }
  9582. break;
  9583. }
  9584. };
  9585. }();
  9586. onMouseMove(mouse) {
  9587. this.mousePosition.set(mouse.offsetX, mouse.offsetY);
  9588. }
  9589. onMouseDown() {
  9590. this.mouseDownPosition.copy(this.mousePosition);
  9591. this.mouseDownTime = getCurrentTime();
  9592. }
  9593. onMouseUp = function() {
  9594. const clickOffset = new THREE.Vector2();
  9595. return function(mouse) {
  9596. clickOffset.copy(this.mousePosition).sub(this.mouseDownPosition);
  9597. const mouseUpTime = getCurrentTime();
  9598. const wasClick = mouseUpTime - this.mouseDownTime < 0.5 && clickOffset.length() < 2;
  9599. if (wasClick) {
  9600. this.onMouseClick(mouse);
  9601. }
  9602. };
  9603. }();
  9604. onMouseClick(mouse) {
  9605. this.mousePosition.set(mouse.offsetX, mouse.offsetY);
  9606. this.checkForFocalPointChange();
  9607. }
  9608. checkForFocalPointChange = function() {
  9609. const renderDimensions = new THREE.Vector2();
  9610. const toNewFocalPoint = new THREE.Vector3();
  9611. const outHits = [];
  9612. return function() {
  9613. if (!this.transitioningCameraTarget) {
  9614. this.getRenderDimensions(renderDimensions);
  9615. outHits.length = 0;
  9616. this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions);
  9617. this.raycaster.intersectSplatMesh(this.splatMesh, outHits);
  9618. if (outHits.length > 0) {
  9619. const hit = outHits[0];
  9620. const intersectionPoint = hit.origin;
  9621. toNewFocalPoint.copy(intersectionPoint).sub(this.camera.position);
  9622. if (toNewFocalPoint.length() > MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT) {
  9623. this.previousCameraTarget.copy(this.controls.target);
  9624. this.nextCameraTarget.copy(intersectionPoint);
  9625. this.transitioningCameraTarget = true;
  9626. this.transitioningCameraTargetStartTime = getCurrentTime();
  9627. }
  9628. }
  9629. }
  9630. };
  9631. }();
  9632. getRenderDimensions(outDimensions) {
  9633. if (this.rootElement) {
  9634. outDimensions.x = this.rootElement.offsetWidth;
  9635. outDimensions.y = this.rootElement.offsetHeight;
  9636. } else {
  9637. this.renderer.getSize(outDimensions);
  9638. }
  9639. }
  9640. setOrthographicMode(orthographicMode) {
  9641. if (orthographicMode === this.camera.isOrthographicCamera) return;
  9642. const fromCamera = this.camera;
  9643. const toCamera = orthographicMode ? this.orthographicCamera : this.perspectiveCamera;
  9644. toCamera.position.copy(fromCamera.position);
  9645. toCamera.up.copy(fromCamera.up);
  9646. toCamera.rotation.copy(fromCamera.rotation);
  9647. toCamera.quaternion.copy(fromCamera.quaternion);
  9648. toCamera.matrix.copy(fromCamera.matrix);
  9649. this.camera = toCamera;
  9650. if (this.controls) {
  9651. const resetControls = (controls) => {
  9652. controls.saveState();
  9653. controls.reset();
  9654. };
  9655. const fromControls = this.controls;
  9656. const toControls = orthographicMode ? this.orthographicControls : this.perspectiveControls;
  9657. resetControls(toControls);
  9658. resetControls(fromControls);
  9659. toControls.target.copy(fromControls.target);
  9660. if (orthographicMode) {
  9661. Viewer.setCameraZoomFromPosition(toCamera, fromCamera, fromControls);
  9662. } else {
  9663. Viewer.setCameraPositionFromZoom(toCamera, fromCamera, toControls);
  9664. }
  9665. this.controls = toControls;
  9666. this.camera.lookAt(this.controls.target);
  9667. }
  9668. }
  9669. static setCameraPositionFromZoom = function() {
  9670. const tempVector = new THREE.Vector3();
  9671. return function(positionCamera, zoomedCamera, controls) {
  9672. const toLookAtDistance = 1 / (zoomedCamera.zoom * 0.001);
  9673. tempVector.copy(controls.target).sub(positionCamera.position).normalize().multiplyScalar(toLookAtDistance).negate();
  9674. positionCamera.position.copy(controls.target).add(tempVector);
  9675. };
  9676. }();
  9677. static setCameraZoomFromPosition = function() {
  9678. const tempVector = new THREE.Vector3();
  9679. return function(zoomCamera, positionZamera, controls) {
  9680. const toLookAtDistance = tempVector.copy(controls.target).sub(positionZamera.position).length();
  9681. zoomCamera.zoom = 1 / (toLookAtDistance * .001);
  9682. };
  9683. }();
  9684. updateSplatMesh = function() {
  9685. const renderDimensions = new THREE.Vector2();
  9686. return function() {
  9687. if (!this.splatMesh) return;
  9688. const splatCount = this.splatMesh.getSplatCount();
  9689. if (splatCount > 0) {
  9690. this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode);
  9691. this.splatMesh.updateTransforms();
  9692. this.getRenderDimensions(renderDimensions);
  9693. const focalLengthX = this.camera.projectionMatrix.elements[0] * 0.5 *
  9694. this.devicePixelRatio * renderDimensions.x;
  9695. const focalLengthY = this.camera.projectionMatrix.elements[5] * 0.5 *
  9696. this.devicePixelRatio * renderDimensions.y;
  9697. const focalMultiplier = this.camera.isOrthographicCamera ? (1.0 / this.devicePixelRatio) : 1.0;
  9698. const focalAdjustment = this.focalAdjustment * focalMultiplier;
  9699. const inverseFocalAdjustment = 1.0 / focalAdjustment;
  9700. this.adjustForWebXRStereo(renderDimensions);
  9701. this.splatMesh.updateUniforms(renderDimensions, focalLengthX * focalAdjustment, focalLengthY * focalAdjustment,
  9702. this.camera.isOrthographicCamera, this.camera.zoom || 1.0, inverseFocalAdjustment);
  9703. }
  9704. };
  9705. }();
  9706. adjustForWebXRStereo(renderDimensions) {
  9707. // TODO: Figure out a less hacky way to determine if stereo rendering is active
  9708. if (this.camera && this.webXRActive) {
  9709. const xrCamera = this.renderer.xr.getCamera();
  9710. const xrCameraProj00 = xrCamera.projectionMatrix.elements[0];
  9711. const cameraProj00 = this.camera.projectionMatrix.elements[0];
  9712. renderDimensions.x *= (cameraProj00 / xrCameraProj00);
  9713. }
  9714. }
  9715. isLoadingOrUnloading() {
  9716. return Object.keys(this.splatSceneDownloadPromises).length > 0 || this.splatSceneDownloadAndBuildPromise !== null ||
  9717. this.splatSceneRemovalPromise !== null;
  9718. }
  9719. isDisposingOrDisposed() {
  9720. return this.disposing || this.disposed;
  9721. }
  9722. addSplatSceneDownloadPromise(promise) {
  9723. this.splatSceneDownloadPromises[promise.id] = promise;
  9724. }
  9725. removeSplatSceneDownloadPromise(promise) {
  9726. delete this.splatSceneDownloadPromises[promise.id];
  9727. }
  9728. setSplatSceneDownloadAndBuildPromise(promise) {
  9729. this.splatSceneDownloadAndBuildPromise = promise;
  9730. }
  9731. clearSplatSceneDownloadAndBuildPromise() {
  9732. this.splatSceneDownloadAndBuildPromise = null;
  9733. }
  9734. /**
  9735. * Add a splat scene to the viewer and display any loading UI if appropriate.
  9736. * @param {string} path Path to splat scene to be loaded
  9737. * @param {object} options {
  9738. *
  9739. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  9740. * value (valid range: 0 - 255), defaults to 1
  9741. *
  9742. * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true
  9743. *
  9744. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  9745. *
  9746. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  9747. *
  9748. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  9749. *
  9750. * onProgress: Function to be called as file data are received, or other processing occurs
  9751. *
  9752. * }
  9753. * @return {AbortablePromise}
  9754. */
  9755. addSplatScene(path, options = {}) {
  9756. if (this.isLoadingOrUnloading()) {
  9757. throw new Error('Cannot add splat scene while another load or unload is already in progress.');
  9758. }
  9759. if (this.isDisposingOrDisposed()) {
  9760. throw new Error('Cannot add splat scene after dispose() is called.');
  9761. }
  9762. if (options.progressiveLoad && this.splatMesh.scenes && this.splatMesh.scenes.length > 0) {
  9763. console.log('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes');
  9764. options.progressiveLoad = false;
  9765. }
  9766. const format = (options.format !== undefined && options.format !== null) ? options.format : sceneFormatFromPath(path);
  9767. const progressiveLoad = Viewer.isProgressivelyLoadable(format) && options.progressiveLoad;
  9768. const showLoadingUI = (options.showLoadingUI !== undefined && options.showLoadingUI !== null) ? options.showLoadingUI : true;
  9769. let loadingUITaskId = null;
  9770. if (showLoadingUI) {
  9771. this.loadingSpinner.removeAllTasks();
  9772. loadingUITaskId = this.loadingSpinner.addTask('Downloading...');
  9773. }
  9774. const hideLoadingUI = () => {
  9775. this.loadingProgressBar.hide();
  9776. this.loadingSpinner.removeAllTasks();
  9777. };
  9778. const onProgressUIUpdate = (percentComplete, percentCompleteLabel, loaderStatus) => {
  9779. if (showLoadingUI) {
  9780. if (loaderStatus === LoaderStatus.Downloading) {
  9781. if (percentComplete == 100) {
  9782. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Download complete!');
  9783. } else {
  9784. if (progressiveLoad) {
  9785. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Downloading splats...');
  9786. } else {
  9787. const suffix = percentCompleteLabel ? `: ${percentCompleteLabel}` : `...`;
  9788. this.loadingSpinner.setMessageForTask(loadingUITaskId, `Downloading${suffix}`);
  9789. }
  9790. }
  9791. } else if (loaderStatus === LoaderStatus.Processing) {
  9792. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Processing splats...');
  9793. }
  9794. }
  9795. };
  9796. let downloadDone = false;
  9797. let downloadedPercentage = 0;
  9798. const splatBuffersAddedUIUpdate = (firstBuild, finalBuild) => {
  9799. if (showLoadingUI) {
  9800. if (firstBuild && progressiveLoad || finalBuild && !progressiveLoad) {
  9801. this.loadingSpinner.removeTask(loadingUITaskId);
  9802. if (!finalBuild && !downloadDone) this.loadingProgressBar.show();
  9803. }
  9804. if (progressiveLoad) {
  9805. if (finalBuild) {
  9806. downloadDone = true;
  9807. this.loadingProgressBar.hide();
  9808. } else {
  9809. this.loadingProgressBar.setProgress(downloadedPercentage);
  9810. }
  9811. }
  9812. }
  9813. };
  9814. const onProgress = (percentComplete, percentCompleteLabel, loaderStatus) => {
  9815. downloadedPercentage = percentComplete;
  9816. onProgressUIUpdate(percentComplete, percentCompleteLabel, loaderStatus);
  9817. if (options.onProgress) options.onProgress(percentComplete, percentCompleteLabel, loaderStatus);
  9818. };
  9819. const buildSection = (splatBuffer, firstBuild, finalBuild) => {
  9820. if (!progressiveLoad && options.onProgress) options.onProgress(0, '0%', LoaderStatus.Processing);
  9821. const addSplatBufferOptions = {
  9822. 'rotation': options.rotation || options.orientation,
  9823. 'position': options.position,
  9824. 'scale': options.scale,
  9825. 'splatAlphaRemovalThreshold': options.splatAlphaRemovalThreshold,
  9826. };
  9827. return this.addSplatBuffers([splatBuffer], [addSplatBufferOptions],
  9828. finalBuild, firstBuild && showLoadingUI, showLoadingUI,
  9829. progressiveLoad, progressiveLoad).then(() => {
  9830. if (!progressiveLoad && options.onProgress) options.onProgress(100, '100%', LoaderStatus.Processing);
  9831. splatBuffersAddedUIUpdate(firstBuild, finalBuild);
  9832. });
  9833. };
  9834. const loadFunc = progressiveLoad ? this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this) :
  9835. this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this);
  9836. return loadFunc(path, format, options.splatAlphaRemovalThreshold, buildSection.bind(this), onProgress, hideLoadingUI.bind(this));
  9837. }
  9838. /**
  9839. * Download a single splat scene, convert to splat buffer and then rebuild the viewer's splat mesh
  9840. * by calling 'buildFunc' -- all before displaying the scene. Also sets/clears relevant instance synchronization objects,
  9841. * and calls appropriate functions on success or failure.
  9842. * @param {string} path Path to splat scene to be loaded
  9843. * @param {SceneFormat} format Format of the splat scene file
  9844. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255)
  9845. * @param {function} buildFunc Function to build the viewer's splat mesh with the downloaded splat buffer
  9846. * @param {function} onProgress Function to be called as file data are received, or other processing occurs
  9847. * @param {function} onException Function to be called when exception occurs
  9848. * @return {AbortablePromise}
  9849. */
  9850. downloadAndBuildSingleSplatSceneStandardLoad(path, format, splatAlphaRemovalThreshold, buildFunc, onProgress, onException) {
  9851. const downloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold,
  9852. onProgress, false, undefined, format);
  9853. const downloadAndBuildPromise = abortablePromiseWithExtractedComponents(downloadPromise.abortHandler);
  9854. downloadPromise.then((splatBuffer) => {
  9855. this.removeSplatSceneDownloadPromise(downloadPromise);
  9856. return buildFunc(splatBuffer, true, true).then(() => {
  9857. downloadAndBuildPromise.resolve();
  9858. this.clearSplatSceneDownloadAndBuildPromise();
  9859. });
  9860. })
  9861. .catch((e) => {
  9862. if (onException) onException();
  9863. this.clearSplatSceneDownloadAndBuildPromise();
  9864. this.removeSplatSceneDownloadPromise(downloadPromise);
  9865. const error = (e instanceof AbortedPromiseError) ? e : new Error(`Viewer::addSplatScene -> Could not load file ${path}`);
  9866. downloadAndBuildPromise.reject(error);
  9867. });
  9868. this.addSplatSceneDownloadPromise(downloadPromise);
  9869. this.setSplatSceneDownloadAndBuildPromise(downloadAndBuildPromise.promise);
  9870. return downloadAndBuildPromise.promise;
  9871. }
  9872. /**
  9873. * Download a single splat scene and convert to splat buffer in a progressive manner, allowing rendering as the file downloads.
  9874. * As each section is downloaded, the viewer's splat mesh is rebuilt by calling 'buildFunc'
  9875. * Also sets/clears relevant instance synchronization objects, and calls appropriate functions on success or failure.
  9876. * @param {string} path Path to splat scene to be loaded
  9877. * @param {SceneFormat} format Format of the splat scene file
  9878. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255)
  9879. * @param {function} buildFunc Function to rebuild the viewer's splat mesh after a new splat buffer section is downloaded
  9880. * @param {function} onDownloadProgress Function to be called as file data are received
  9881. * @param {function} onDownloadException Function to be called when exception occurs at any point during the full download
  9882. * @return {AbortablePromise}
  9883. */
  9884. downloadAndBuildSingleSplatSceneProgressiveLoad(path, format, splatAlphaRemovalThreshold, buildFunc,
  9885. onDownloadProgress, onDownloadException) {
  9886. let progressiveLoadedSectionBuildCount = 0;
  9887. let progressiveLoadedSectionBuilding = false;
  9888. const queuedProgressiveLoadSectionBuilds = [];
  9889. const checkAndBuildProgressiveLoadSections = () => {
  9890. if (queuedProgressiveLoadSectionBuilds.length > 0 &&
  9891. !progressiveLoadedSectionBuilding &&
  9892. !this.isDisposingOrDisposed()) {
  9893. progressiveLoadedSectionBuilding = true;
  9894. const queuedBuild = queuedProgressiveLoadSectionBuilds.shift();
  9895. buildFunc(queuedBuild.splatBuffer, queuedBuild.firstBuild, queuedBuild.finalBuild)
  9896. .then(() => {
  9897. progressiveLoadedSectionBuilding = false;
  9898. if (queuedBuild.firstBuild) {
  9899. progressiveLoadFirstSectionBuildPromise.reject = null;
  9900. progressiveLoadFirstSectionBuildPromise.resolve();
  9901. } else if (queuedBuild.finalBuild) {
  9902. splatSceneDownloadAndBuildPromise.resolve();
  9903. this.clearSplatSceneDownloadAndBuildPromise();
  9904. }
  9905. if (queuedProgressiveLoadSectionBuilds.length > 0) {
  9906. delayedExecute(() => checkAndBuildProgressiveLoadSections());
  9907. }
  9908. });
  9909. }
  9910. };
  9911. const onProgressiveLoadSectionProgress = (splatBuffer, finalBuild) => {
  9912. if (!this.isDisposingOrDisposed()) {
  9913. if (finalBuild || queuedProgressiveLoadSectionBuilds.length === 0 ||
  9914. splatBuffer.getSplatCount() > queuedProgressiveLoadSectionBuilds[0].splatBuffer.getSplatCount()) {
  9915. queuedProgressiveLoadSectionBuilds.push({
  9916. splatBuffer,
  9917. firstBuild: progressiveLoadedSectionBuildCount === 0,
  9918. finalBuild
  9919. });
  9920. progressiveLoadedSectionBuildCount++;
  9921. checkAndBuildProgressiveLoadSections();
  9922. }
  9923. }
  9924. };
  9925. let splatSceneDownloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold, onDownloadProgress, true,
  9926. onProgressiveLoadSectionProgress, format);
  9927. const progressiveLoadFirstSectionBuildPromise = abortablePromiseWithExtractedComponents(splatSceneDownloadPromise.abortHandler);
  9928. const splatSceneDownloadAndBuildPromise = abortablePromiseWithExtractedComponents();
  9929. this.addSplatSceneDownloadPromise(splatSceneDownloadPromise);
  9930. this.setSplatSceneDownloadAndBuildPromise(splatSceneDownloadAndBuildPromise.promise);
  9931. splatSceneDownloadPromise.then(() => {
  9932. this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise);
  9933. })
  9934. .catch((e) => {
  9935. this.clearSplatSceneDownloadAndBuildPromise();
  9936. this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise);
  9937. const error = (e instanceof AbortedPromiseError) ? e : new Error(`Viewer::addSplatScene -> Could not load one or more scenes`);
  9938. progressiveLoadFirstSectionBuildPromise.reject(error);
  9939. if (onDownloadException) onDownloadException(error);
  9940. });
  9941. return progressiveLoadFirstSectionBuildPromise.promise;
  9942. }
  9943. /**
  9944. * Add multiple splat scenes to the viewer and display any loading UI if appropriate.
  9945. * @param {Array<object>} sceneOptions Array of per-scene options: {
  9946. *
  9947. * path: Path to splat scene to be loaded
  9948. *
  9949. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  9950. * value (valid range: 0 - 255), defaults to 1
  9951. *
  9952. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  9953. *
  9954. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  9955. *
  9956. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  9957. * }
  9958. * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true
  9959. * @param {function} onProgress Function to be called as file data are received
  9960. * @return {AbortablePromise}
  9961. */
  9962. addSplatScenes(sceneOptions, showLoadingUI = true, onProgress = undefined) {
  9963. if (this.isLoadingOrUnloading()) {
  9964. throw new Error('Cannot add splat scene while another load or unload is already in progress.');
  9965. }
  9966. if (this.isDisposingOrDisposed()) {
  9967. throw new Error('Cannot add splat scene after dispose() is called.');
  9968. }
  9969. const fileCount = sceneOptions.length;
  9970. const percentComplete = [];
  9971. let loadingUITaskId;
  9972. if (showLoadingUI) {
  9973. this.loadingSpinner.removeAllTasks();
  9974. loadingUITaskId = this.loadingSpinner.addTask('Downloading...');
  9975. }
  9976. const onLoadProgress = (fileIndex, percent, percentLabel, loaderStatus) => {
  9977. percentComplete[fileIndex] = percent;
  9978. let totalPercent = 0;
  9979. for (let i = 0; i < fileCount; i++) totalPercent += percentComplete[i] || 0;
  9980. totalPercent = totalPercent / fileCount;
  9981. percentLabel = `${totalPercent.toFixed(2)}%`;
  9982. if (showLoadingUI) {
  9983. if (loaderStatus === LoaderStatus.Downloading) {
  9984. this.loadingSpinner.setMessageForTask(loadingUITaskId, totalPercent == 100 ?
  9985. `Download complete!` : `Downloading: ${percentLabel}`);
  9986. }
  9987. }
  9988. if (onProgress) onProgress(totalPercent, percentLabel, loaderStatus);
  9989. };
  9990. const baseDownloadPromises = [];
  9991. const nativeDownloadPromises = [];
  9992. for (let i = 0; i < sceneOptions.length; i++) {
  9993. const options = sceneOptions[i];
  9994. const format = (options.format !== undefined && options.format !== null) ? options.format : sceneFormatFromPath(options.path);
  9995. const baseDownloadPromise = this.downloadSplatSceneToSplatBuffer(options.path, options.splatAlphaRemovalThreshold,
  9996. onLoadProgress.bind(this, i), false, undefined, format);
  9997. baseDownloadPromises.push(baseDownloadPromise);
  9998. nativeDownloadPromises.push(baseDownloadPromise.promise);
  9999. }
  10000. const downloadAndBuildPromise = new AbortablePromise((resolve, reject) => {
  10001. Promise.all(nativeDownloadPromises)
  10002. .then((splatBuffers) => {
  10003. if (showLoadingUI) this.loadingSpinner.removeTask(loadingUITaskId);
  10004. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  10005. this.addSplatBuffers(splatBuffers, sceneOptions, true, showLoadingUI, showLoadingUI, false, false).then(() => {
  10006. if (onProgress) onProgress(100, '100%', LoaderStatus.Processing);
  10007. this.clearSplatSceneDownloadAndBuildPromise();
  10008. resolve();
  10009. });
  10010. })
  10011. .catch((e) => {
  10012. if (showLoadingUI) this.loadingSpinner.removeTask(loadingUITaskId);
  10013. this.clearSplatSceneDownloadAndBuildPromise();
  10014. const error = (e instanceof AbortedPromiseError) ? e :
  10015. new Error(`Viewer::addSplatScenes -> Could not load one or more splat scenes.`);
  10016. reject(error);
  10017. })
  10018. .finally(() => {
  10019. this.removeSplatSceneDownloadPromise(downloadAndBuildPromise);
  10020. });
  10021. }, (reason) => {
  10022. for (let baseDownloadPromise of baseDownloadPromises) {
  10023. baseDownloadPromise.abort(reason);
  10024. }
  10025. });
  10026. this.addSplatSceneDownloadPromise(downloadAndBuildPromise);
  10027. this.setSplatSceneDownloadAndBuildPromise(downloadAndBuildPromise);
  10028. return downloadAndBuildPromise;
  10029. }
  10030. /**
  10031. * Download a splat scene and convert to SplatBuffer instance.
  10032. * @param {string} path Path to splat scene to be loaded
  10033. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified
  10034. * value (valid range: 0 - 255), defaults to 1
  10035. *
  10036. * @param {function} onProgress Function to be called as file data are received
  10037. * @param {boolean} progressiveBuild Construct file sections into splat buffers as they are downloaded
  10038. * @param {function} onSectionBuilt Function to be called when new section is added to the file
  10039. * @param {string} format File format of the scene
  10040. * @return {AbortablePromise}
  10041. */
  10042. downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold = 1, onProgress = undefined,
  10043. progressiveBuild = false, onSectionBuilt = undefined, format) {
  10044. if (format === SceneFormat.Splat) {
  10045. return SplatLoader.loadFromURL(path, onProgress, progressiveBuild,
  10046. onSectionBuilt, splatAlphaRemovalThreshold, 0, false);
  10047. } else if (format === SceneFormat.KSplat) {
  10048. return KSplatLoader.loadFromURL(path, onProgress, progressiveBuild, onSectionBuilt);
  10049. } else if (format === SceneFormat.Ply) {
  10050. return PlyLoader.loadFromURL(path, onProgress, progressiveBuild, onSectionBuilt,
  10051. splatAlphaRemovalThreshold, this.plyInMemoryCompressionLevel, this.sphericalHarmonicsDegree);
  10052. }
  10053. throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${path}`);
  10054. }
  10055. static isProgressivelyLoadable(format) {
  10056. return format === SceneFormat.Splat || format === SceneFormat.KSplat || format === SceneFormat.Ply;
  10057. }
  10058. /**
  10059. * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer and set up the sorting web worker.
  10060. * This function will terminate the existing sort worker (if there is one).
  10061. */
  10062. addSplatBuffers = function() {
  10063. return function(splatBuffers, splatBufferOptions = [], finalBuild = true, showLoadingUI = true,
  10064. showLoadingUIForSplatTreeBuild = true, replaceExisting = false,
  10065. enableRenderBeforeFirstSort = false, preserveVisibleRegion = true) {
  10066. if (this.isDisposingOrDisposed()) return Promise.resolve();
  10067. this.splatRenderReady = false;
  10068. let splatProcessingTaskId = null;
  10069. const removeSplatProcessingTask = () => {
  10070. if (splatProcessingTaskId !== null) {
  10071. this.loadingSpinner.removeTask(splatProcessingTaskId);
  10072. splatProcessingTaskId = null;
  10073. }
  10074. };
  10075. const finish = (buildResults, resolver) => {
  10076. if (this.isDisposingOrDisposed()) return;
  10077. // If we aren't calculating the splat distances from the center on the GPU, the sorting worker needs splat centers and
  10078. // transform indexes so that it can calculate those distance values.
  10079. if (!this.gpuAcceleratedSort && this.sortWorker) {
  10080. this.sortWorker.postMessage({
  10081. 'centers': buildResults.centers.buffer,
  10082. 'sceneIndexes': buildResults.sceneIndexes.buffer,
  10083. 'range': {
  10084. 'from': buildResults.from,
  10085. 'to': buildResults.to,
  10086. 'count': buildResults.count
  10087. }
  10088. });
  10089. }
  10090. this.runSplatSort(true).then((sortRunning) => {
  10091. if (!this.sortWorker || !sortRunning) {
  10092. this.splatRenderReady = true;
  10093. removeSplatProcessingTask();
  10094. resolver();
  10095. } else {
  10096. if (enableRenderBeforeFirstSort) {
  10097. this.splatRenderReady = true;
  10098. } else {
  10099. this.runAfterNextSort.push(() => {
  10100. this.splatRenderReady = true;
  10101. });
  10102. }
  10103. this.runAfterNextSort.push(() => {
  10104. removeSplatProcessingTask();
  10105. resolver();
  10106. });
  10107. }
  10108. });
  10109. };
  10110. return new Promise((resolve) => {
  10111. if (showLoadingUI) {
  10112. splatProcessingTaskId = this.loadingSpinner.addTask('Processing splats...');
  10113. }
  10114. delayedExecute(() => {
  10115. if (this.isDisposingOrDisposed()) {
  10116. resolve();
  10117. } else {
  10118. const buildResults = this.addSplatBuffersToMesh(splatBuffers, splatBufferOptions, finalBuild,
  10119. showLoadingUIForSplatTreeBuild, replaceExisting,
  10120. preserveVisibleRegion);
  10121. const maxSplatCount = this.splatMesh.getMaxSplatCount();
  10122. if (this.sortWorker && this.sortWorker.maxSplatCount !== maxSplatCount) this.disposeSortWorker();
  10123. const sortWorkerSetupPromise = (!this.sortWorker && maxSplatCount > 0) ?
  10124. this.setupSortWorker(this.splatMesh) : Promise.resolve();
  10125. sortWorkerSetupPromise.then(() => {
  10126. finish(buildResults, resolve);
  10127. });
  10128. }
  10129. }, true);
  10130. });
  10131. };
  10132. }();
  10133. /**
  10134. * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer. By default, this function is additive;
  10135. * all splat buffers contained by the viewer's splat mesh before calling this function will be preserved. This behavior can be
  10136. * changed by passing 'true' for 'replaceExisting'.
  10137. * @param {Array<SplatBuffer>} splatBuffers SplatBuffer instances
  10138. * @param {Array<object>} splatBufferOptions Array of options objects: {
  10139. *
  10140. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  10141. * value (valid range: 0 - 255), defaults to 1
  10142. *
  10143. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  10144. *
  10145. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  10146. *
  10147. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  10148. * }
  10149. * @param {boolean} finalBuild Will the splat mesh be in its final state after this build?
  10150. * @param {boolean} showLoadingUIForSplatTreeBuild Whether or not to show the loading spinner during construction of the splat tree.
  10151. * @return {object} Object containing info about the splats that are updated
  10152. */
  10153. addSplatBuffersToMesh = function() {
  10154. let splatOptimizingTaskId;
  10155. return function(splatBuffers, splatBufferOptions, finalBuild = true, showLoadingUIForSplatTreeBuild = false,
  10156. replaceExisting = false, preserveVisibleRegion = true) {
  10157. if (this.isDisposingOrDisposed()) return;
  10158. let allSplatBuffers = [];
  10159. let allSplatBufferOptions = [];
  10160. if (!replaceExisting) {
  10161. allSplatBuffers = this.splatMesh.scenes.map((scene) => scene.splatBuffer) || [];
  10162. allSplatBufferOptions = this.splatMesh.sceneOptions ? this.splatMesh.sceneOptions.map((sceneOptions) => sceneOptions) : [];
  10163. }
  10164. allSplatBuffers.push(...splatBuffers);
  10165. allSplatBufferOptions.push(...splatBufferOptions);
  10166. if (this.renderer) this.splatMesh.setRenderer(this.renderer);
  10167. const onSplatTreeIndexesUpload = (finished) => {
  10168. if (this.isDisposingOrDisposed()) return;
  10169. const splatCount = this.splatMesh.getSplatCount();
  10170. if (showLoadingUIForSplatTreeBuild && splatCount >= MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER) {
  10171. if (!finished && !splatOptimizingTaskId) {
  10172. this.loadingSpinner.setMinimized(true, true);
  10173. splatOptimizingTaskId = this.loadingSpinner.addTask('Optimizing splats...');
  10174. }
  10175. }
  10176. };
  10177. const onSplatTreeReady = (finished) => {
  10178. if (this.isDisposingOrDisposed()) return;
  10179. if (finished && splatOptimizingTaskId) {
  10180. this.loadingSpinner.removeTask(splatOptimizingTaskId);
  10181. splatOptimizingTaskId = null;
  10182. }
  10183. };
  10184. const buildResults = this.splatMesh.build(allSplatBuffers, allSplatBufferOptions, true, finalBuild, onSplatTreeIndexesUpload,
  10185. onSplatTreeReady, preserveVisibleRegion);
  10186. if (finalBuild && this.freeIntermediateSplatData) this.splatMesh.freeIntermediateSplatData();
  10187. return buildResults;
  10188. };
  10189. }();
  10190. /**
  10191. * Set up the splat sorting web worker.
  10192. * @param {SplatMesh} splatMesh SplatMesh instance that contains the splats to be sorted
  10193. * @return {Promise}
  10194. */
  10195. setupSortWorker(splatMesh) {
  10196. if (this.isDisposingOrDisposed()) return;
  10197. return new Promise((resolve) => {
  10198. const DistancesArrayType = this.integerBasedSort ? Int32Array : Float32Array;
  10199. const splatCount = splatMesh.getSplatCount();
  10200. const maxSplatCount = splatMesh.getMaxSplatCount();
  10201. this.sortWorker = createSortWorker(maxSplatCount, this.sharedMemoryForWorkers, this.enableSIMDInSort,
  10202. this.integerBasedSort, this.splatMesh.dynamicMode);
  10203. this.sortWorker.onmessage = (e) => {
  10204. if (e.data.sortDone) {
  10205. this.sortRunning = false;
  10206. if (this.sharedMemoryForWorkers) {
  10207. this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes, e.data.splatRenderCount);
  10208. } else {
  10209. const sortedIndexes = new Uint32Array(e.data.sortedIndexes.buffer, 0, e.data.splatRenderCount);
  10210. this.splatMesh.updateRenderIndexes(sortedIndexes, e.data.splatRenderCount);
  10211. }
  10212. this.lastSortTime = e.data.sortTime;
  10213. this.sortPromiseResolver();
  10214. this.sortPromiseResolver = null;
  10215. this.forceRenderNextFrame();
  10216. if (this.runAfterNextSort.length > 0) {
  10217. this.runAfterNextSort.forEach((func) => {
  10218. func();
  10219. });
  10220. this.runAfterNextSort.length = 0;
  10221. }
  10222. } else if (e.data.sortCanceled) {
  10223. this.sortRunning = false;
  10224. } else if (e.data.sortSetupPhase1Complete) {
  10225. if (this.logLevel >= LogLevel.Info) console.log('Sorting web worker WASM setup complete.');
  10226. if (this.sharedMemoryForWorkers) {
  10227. this.sortWorkerSortedIndexes = new Uint32Array(e.data.sortedIndexesBuffer,
  10228. e.data.sortedIndexesOffset, maxSplatCount);
  10229. this.sortWorkerIndexesToSort = new Uint32Array(e.data.indexesToSortBuffer,
  10230. e.data.indexesToSortOffset, maxSplatCount);
  10231. this.sortWorkerPrecomputedDistances = new DistancesArrayType(e.data.precomputedDistancesBuffer,
  10232. e.data.precomputedDistancesOffset,
  10233. maxSplatCount);
  10234. this.sortWorkerTransforms = new Float32Array(e.data.transformsBuffer,
  10235. e.data.transformsOffset, Constants.MaxScenes * 16);
  10236. } else {
  10237. this.sortWorkerIndexesToSort = new Uint32Array(maxSplatCount);
  10238. this.sortWorkerPrecomputedDistances = new DistancesArrayType(maxSplatCount);
  10239. this.sortWorkerTransforms = new Float32Array(Constants.MaxScenes * 16);
  10240. }
  10241. for (let i = 0; i < splatCount; i++) this.sortWorkerIndexesToSort[i] = i;
  10242. this.sortWorker.maxSplatCount = maxSplatCount;
  10243. if (this.logLevel >= LogLevel.Info) {
  10244. console.log('Sorting web worker ready.');
  10245. const splatDataTextures = this.splatMesh.getSplatDataTextures();
  10246. const covariancesTextureSize = splatDataTextures.covariances.size;
  10247. const centersColorsTextureSize = splatDataTextures.centerColors.size;
  10248. console.log('Covariances texture size: ' + covariancesTextureSize.x + ' x ' + covariancesTextureSize.y);
  10249. console.log('Centers/colors texture size: ' + centersColorsTextureSize.x + ' x ' + centersColorsTextureSize.y);
  10250. }
  10251. resolve();
  10252. }
  10253. };
  10254. });
  10255. }
  10256. disposeSortWorker() {
  10257. if (this.sortWorker) this.sortWorker.terminate();
  10258. this.sortWorker = null;
  10259. this.sortPromise = null;
  10260. if (this.sortPromiseResolver) {
  10261. this.sortPromiseResolver();
  10262. this.sortPromiseResolver = null;
  10263. }
  10264. this.sortRunning = false;
  10265. }
  10266. removeSplatScene(indexToRemove, showLoadingUI = true) {
  10267. return this.removeSplatScenes([indexToRemove], showLoadingUI);
  10268. }
  10269. removeSplatScenes(indexesToRemove, showLoadingUI = true) {
  10270. if (this.isLoadingOrUnloading()) {
  10271. throw new Error('Cannot remove splat scene while another load or unload is already in progress.');
  10272. }
  10273. if (this.isDisposingOrDisposed()) {
  10274. throw new Error('Cannot remove splat scene after dispose() is called.');
  10275. }
  10276. let sortPromise;
  10277. this.splatSceneRemovalPromise = new Promise((resolve, reject) => {
  10278. let revmovalTaskId;
  10279. if (showLoadingUI) {
  10280. this.loadingSpinner.removeAllTasks();
  10281. this.loadingSpinner.show();
  10282. revmovalTaskId = this.loadingSpinner.addTask('Removing splat scene...');
  10283. }
  10284. const checkAndHideLoadingUI = () => {
  10285. if (showLoadingUI) {
  10286. this.loadingSpinner.hide();
  10287. this.loadingSpinner.removeTask(revmovalTaskId);
  10288. }
  10289. };
  10290. const onDone = (error) => {
  10291. checkAndHideLoadingUI();
  10292. this.splatSceneRemovalPromise = null;
  10293. if (!error) resolve();
  10294. else reject(error);
  10295. };
  10296. const checkForEarlyExit = () => {
  10297. if (this.isDisposingOrDisposed()) {
  10298. onDone();
  10299. return true;
  10300. }
  10301. return false;
  10302. };
  10303. sortPromise = this.sortPromise || Promise.resolve();
  10304. sortPromise.then(() => {
  10305. if (checkForEarlyExit()) return;
  10306. const savedSplatBuffers = [];
  10307. const savedSceneOptions = [];
  10308. const savedSceneTransformComponents = [];
  10309. for (let i = 0; i < this.splatMesh.scenes.length; i++) {
  10310. let shouldRemove = false;
  10311. for (let indexToRemove of indexesToRemove) {
  10312. if (indexToRemove === i) {
  10313. shouldRemove = true;
  10314. break;
  10315. }
  10316. }
  10317. if (!shouldRemove) {
  10318. const scene = this.splatMesh.scenes[i];
  10319. savedSplatBuffers.push(scene.splatBuffer);
  10320. savedSceneOptions.push(this.splatMesh.sceneOptions[i]);
  10321. savedSceneTransformComponents.push({
  10322. 'position': scene.position.clone(),
  10323. 'quaternion': scene.quaternion.clone(),
  10324. 'scale': scene.scale.clone()
  10325. });
  10326. }
  10327. }
  10328. this.disposeSortWorker();
  10329. this.splatMesh.dispose();
  10330. this.sceneRevealMode = SceneRevealMode.Instant;
  10331. this.createSplatMesh();
  10332. this.addSplatBuffers(savedSplatBuffers, savedSceneOptions, true, false, true)
  10333. .then(() => {
  10334. if (checkForEarlyExit()) return;
  10335. checkAndHideLoadingUI();
  10336. this.splatMesh.scenes.forEach((scene, index) => {
  10337. scene.position.copy(savedSceneTransformComponents[index].position);
  10338. scene.quaternion.copy(savedSceneTransformComponents[index].quaternion);
  10339. scene.scale.copy(savedSceneTransformComponents[index].scale);
  10340. });
  10341. this.splatMesh.updateTransforms();
  10342. this.splatRenderReady = false;
  10343. this.runSplatSort(true)
  10344. .then(() => {
  10345. if (checkForEarlyExit()) {
  10346. this.splatRenderReady = true;
  10347. return;
  10348. }
  10349. sortPromise = this.sortPromise || Promise.resolve();
  10350. sortPromise.then(() => {
  10351. this.splatRenderReady = true;
  10352. onDone();
  10353. });
  10354. });
  10355. })
  10356. .catch((e) => {
  10357. onDone(e);
  10358. });
  10359. });
  10360. });
  10361. return this.splatSceneRemovalPromise;
  10362. }
  10363. /**
  10364. * Start self-driven mode
  10365. */
  10366. start() {
  10367. if (this.selfDrivenMode) {
  10368. if (this.webXRMode) {
  10369. this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc);
  10370. } else {
  10371. this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc);
  10372. }
  10373. this.selfDrivenModeRunning = true;
  10374. } else {
  10375. throw new Error('Cannot start viewer unless it is in self driven mode.');
  10376. }
  10377. }
  10378. /**
  10379. * Stop self-driven mode
  10380. */
  10381. stop() {
  10382. if (this.selfDrivenMode && this.selfDrivenModeRunning) {
  10383. if (!this.webXRMode) {
  10384. cancelAnimationFrame(this.requestFrameId);
  10385. }
  10386. this.selfDrivenModeRunning = false;
  10387. }
  10388. }
  10389. /**
  10390. * Dispose of all resources held directly and indirectly by this viewer.
  10391. */
  10392. async dispose() {
  10393. if (this.isDisposingOrDisposed()) return this.disposePromise;
  10394. let waitPromises = [];
  10395. let promisesToAbort = [];
  10396. for (let promiseKey in this.splatSceneDownloadPromises) {
  10397. if (this.splatSceneDownloadPromises.hasOwnProperty(promiseKey)) {
  10398. const downloadPromiseToAbort = this.splatSceneDownloadPromises[promiseKey];
  10399. promisesToAbort.push(downloadPromiseToAbort);
  10400. waitPromises.push(downloadPromiseToAbort.promise);
  10401. }
  10402. }
  10403. if (this.sortPromise) {
  10404. waitPromises.push(this.sortPromise);
  10405. }
  10406. this.disposing = true;
  10407. this.disposePromise = Promise.all(waitPromises).finally(() => {
  10408. this.stop();
  10409. if (this.controls) {
  10410. this.controls.dispose();
  10411. this.controls = null;
  10412. }
  10413. if (this.splatMesh) {
  10414. this.splatMesh.dispose();
  10415. this.splatMesh = null;
  10416. }
  10417. if (this.sceneHelper) {
  10418. this.sceneHelper.dispose();
  10419. this.sceneHelper = null;
  10420. }
  10421. if (this.resizeObserver) {
  10422. this.resizeObserver.unobserve(this.rootElement);
  10423. this.resizeObserver = null;
  10424. }
  10425. this.disposeSortWorker();
  10426. this.removeEventHandlers();
  10427. this.loadingSpinner.removeAllTasks();
  10428. this.loadingSpinner.setContainer(null);
  10429. this.loadingProgressBar.hide();
  10430. this.loadingProgressBar.setContainer(null);
  10431. this.infoPanel.setContainer(null);
  10432. this.camera = null;
  10433. this.threeScene = null;
  10434. this.splatRenderReady = false;
  10435. this.initialized = false;
  10436. if (this.renderer) {
  10437. if (!this.usingExternalRenderer) {
  10438. this.rootElement.removeChild(this.renderer.domElement);
  10439. this.renderer.dispose();
  10440. }
  10441. this.renderer = null;
  10442. }
  10443. if (!this.usingExternalRenderer) {
  10444. document.body.removeChild(this.rootElement);
  10445. }
  10446. this.sortWorkerSortedIndexes = null;
  10447. this.sortWorkerIndexesToSort = null;
  10448. this.sortWorkerPrecomputedDistances = null;
  10449. this.sortWorkerTransforms = null;
  10450. this.disposed = true;
  10451. this.disposing = false;
  10452. this.disposePromise = null;
  10453. });
  10454. promisesToAbort.forEach((toAbort) => {
  10455. toAbort.abort('Scene disposed');
  10456. });
  10457. return this.disposePromise;
  10458. }
  10459. selfDrivenUpdate() {
  10460. /* if (this.selfDrivenMode && !this.webXRMode) { //xzw delete 改用自己的
  10461. this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc);
  10462. } */
  10463. this.update();
  10464. if (this.shouldRender()) {
  10465. this.render();
  10466. this.consecutiveRenderFrames++;
  10467. } else {
  10468. this.consecutiveRenderFrames = 0;
  10469. }
  10470. this.renderNextFrame = false;
  10471. }
  10472. forceRenderNextFrame() {
  10473. this.renderNextFrame = true;
  10474. }
  10475. shouldRender = function() {
  10476. let renderCount = 0;
  10477. const lastCameraPosition = new THREE.Vector3();
  10478. const lastCameraOrientation = new THREE.Quaternion();
  10479. const changeEpsilon = 0.0001;
  10480. return function() {
  10481. let shouldRender = false;
  10482. let cameraChanged = false;
  10483. if (this.camera) {
  10484. const cp = this.camera.position;
  10485. const co = this.camera.quaternion;
  10486. cameraChanged = Math.abs(cp.x - lastCameraPosition.x) > changeEpsilon ||
  10487. Math.abs(cp.y - lastCameraPosition.y) > changeEpsilon ||
  10488. Math.abs(cp.z - lastCameraPosition.z) > changeEpsilon ||
  10489. Math.abs(co.x - lastCameraOrientation.x) > changeEpsilon ||
  10490. Math.abs(co.y - lastCameraOrientation.y) > changeEpsilon ||
  10491. Math.abs(co.z - lastCameraOrientation.z) > changeEpsilon ||
  10492. Math.abs(co.w - lastCameraOrientation.w) > changeEpsilon;
  10493. }
  10494. shouldRender = this.renderMode !== RenderMode.Never && (renderCount === 0 || this.splatMesh.visibleRegionChanging ||
  10495. cameraChanged || this.renderMode === RenderMode.Always || this.dynamicMode === true || this.renderNextFrame);
  10496. if (this.camera) {
  10497. lastCameraPosition.copy(this.camera.position);
  10498. lastCameraOrientation.copy(this.camera.quaternion);
  10499. }
  10500. renderCount++;
  10501. return shouldRender;
  10502. };
  10503. }();
  10504. render = function() {
  10505. return function() {
  10506. if (!this.initialized || !this.splatRenderReady) return;
  10507. const hasRenderables = (threeScene) => {
  10508. for (let child of threeScene.children) {
  10509. if (child.visible) return true;
  10510. }
  10511. return false;
  10512. };
  10513. let oldLayer = this.camera.layers.mask
  10514. this.camera.layers.set(0)//xzw add
  10515. const savedAuoClear = this.renderer.autoClear;
  10516. if (hasRenderables(this.threeScene)) {
  10517. this.renderer.render(this.threeScene, this.camera);
  10518. this.renderer.autoClear = false;
  10519. }
  10520. this.renderer.render(this.splatMesh, this.camera);
  10521. this.renderer.autoClear = false;
  10522. if (this.sceneHelper.getFocusMarkerOpacity() > 0.0) this.renderer.render(this.sceneHelper.focusMarker, this.camera);
  10523. if (this.showControlPlane) this.renderer.render(this.sceneHelper.controlPlane, this.camera);
  10524. this.renderer.autoClear = savedAuoClear;
  10525. };
  10526. this.camera.layers.mask = oldLayer
  10527. }();
  10528. update(renderer, camera) {
  10529. if (this.dropInMode) this.updateForDropInMode(renderer, camera);
  10530. if (!this.initialized || !this.splatRenderReady) return;
  10531. if (this.controls) {
  10532. this.controls.update();
  10533. if (this.camera.isOrthographicCamera && !this.usingExternalCamera) {
  10534. Viewer.setCameraPositionFromZoom(this.camera, this.camera, this.controls);
  10535. }
  10536. }
  10537. this.runSplatSort();
  10538. this.updateForRendererSizeChanges();
  10539. this.updateSplatMesh();
  10540. this.updateMeshCursor();
  10541. this.updateFPS();
  10542. this.timingSensitiveUpdates();
  10543. this.updateInfoPanel();
  10544. this.updateControlPlane();
  10545. }
  10546. updateForDropInMode(renderer, camera) {
  10547. this.renderer = renderer;
  10548. if (this.splatMesh) this.splatMesh.setRenderer(this.renderer);
  10549. this.camera = camera;
  10550. if (this.controls) this.controls.object = camera;
  10551. this.init();
  10552. }
  10553. updateFPS = function() {
  10554. let lastCalcTime = getCurrentTime();
  10555. let frameCount = 0;
  10556. return function() {
  10557. if (this.consecutiveRenderFrames > CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION) {
  10558. const currentTime = getCurrentTime();
  10559. const calcDelta = currentTime - lastCalcTime;
  10560. if (calcDelta >= 1.0) {
  10561. this.currentFPS = frameCount;
  10562. frameCount = 0;
  10563. lastCalcTime = currentTime;
  10564. } else {
  10565. frameCount++;
  10566. }
  10567. } else {
  10568. this.currentFPS = null;
  10569. }
  10570. };
  10571. }();
  10572. updateForRendererSizeChanges = function() {
  10573. const lastRendererSize = new THREE.Vector2();
  10574. const currentRendererSize = new THREE.Vector2();
  10575. let lastCameraOrthographic;
  10576. return function() {
  10577. if (!this.usingExternalCamera) {
  10578. this.renderer.getSize(currentRendererSize);
  10579. if (lastCameraOrthographic === undefined || lastCameraOrthographic !== this.camera.isOrthographicCamera ||
  10580. currentRendererSize.x !== lastRendererSize.x || currentRendererSize.y !== lastRendererSize.y) {
  10581. if (this.camera.isOrthographicCamera) {
  10582. this.camera.left = -currentRendererSize.x / 2.0;
  10583. this.camera.right = currentRendererSize.x / 2.0;
  10584. this.camera.top = currentRendererSize.y / 2.0;
  10585. this.camera.bottom = -currentRendererSize.y / 2.0;
  10586. } else {
  10587. this.camera.aspect = currentRendererSize.x / currentRendererSize.y;
  10588. }
  10589. this.camera.updateProjectionMatrix();
  10590. lastRendererSize.copy(currentRendererSize);
  10591. lastCameraOrthographic = this.camera.isOrthographicCamera;
  10592. }
  10593. }
  10594. };
  10595. }();
  10596. timingSensitiveUpdates = function() {
  10597. let lastUpdateTime;
  10598. return function() {
  10599. const currentTime = getCurrentTime();
  10600. if (!lastUpdateTime) lastUpdateTime = currentTime;
  10601. const timeDelta = currentTime - lastUpdateTime;
  10602. this.updateCameraTransition(currentTime);
  10603. this.updateFocusMarker(timeDelta);
  10604. lastUpdateTime = currentTime;
  10605. };
  10606. }();
  10607. updateCameraTransition = function() {
  10608. let tempCameraTarget = new THREE.Vector3();
  10609. let toPreviousTarget = new THREE.Vector3();
  10610. let toNextTarget = new THREE.Vector3();
  10611. return function(currentTime) {
  10612. if (this.transitioningCameraTarget) {
  10613. toPreviousTarget.copy(this.previousCameraTarget).sub(this.camera.position).normalize();
  10614. toNextTarget.copy(this.nextCameraTarget).sub(this.camera.position).normalize();
  10615. const rotationAngle = Math.acos(toPreviousTarget.dot(toNextTarget));
  10616. const rotationSpeed = rotationAngle / (Math.PI / 3) * .65 + .3;
  10617. const t = (rotationSpeed / rotationAngle * (currentTime - this.transitioningCameraTargetStartTime));
  10618. tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget, t);
  10619. this.camera.lookAt(tempCameraTarget);
  10620. this.controls.target.copy(tempCameraTarget);
  10621. if (t >= 1.0) {
  10622. this.transitioningCameraTarget = false;
  10623. }
  10624. }
  10625. };
  10626. }();
  10627. updateFocusMarker = function() {
  10628. const renderDimensions = new THREE.Vector2();
  10629. let wasTransitioning = false;
  10630. return function(timeDelta) {
  10631. this.getRenderDimensions(renderDimensions);
  10632. if (this.transitioningCameraTarget) {
  10633. this.sceneHelper.setFocusMarkerVisibility(true);
  10634. const currentFocusMarkerOpacity = Math.max(this.sceneHelper.getFocusMarkerOpacity(), 0.0);
  10635. let newFocusMarkerOpacity = Math.min(currentFocusMarkerOpacity + FOCUS_MARKER_FADE_IN_SPEED * timeDelta, 1.0);
  10636. this.sceneHelper.setFocusMarkerOpacity(newFocusMarkerOpacity);
  10637. this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions);
  10638. wasTransitioning = true;
  10639. this.forceRenderNextFrame();
  10640. } else {
  10641. let currentFocusMarkerOpacity;
  10642. if (wasTransitioning) currentFocusMarkerOpacity = 1.0;
  10643. else currentFocusMarkerOpacity = Math.min(this.sceneHelper.getFocusMarkerOpacity(), 1.0);
  10644. if (currentFocusMarkerOpacity > 0) {
  10645. this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions);
  10646. let newFocusMarkerOpacity = Math.max(currentFocusMarkerOpacity - FOCUS_MARKER_FADE_OUT_SPEED * timeDelta, 0.0);
  10647. this.sceneHelper.setFocusMarkerOpacity(newFocusMarkerOpacity);
  10648. if (newFocusMarkerOpacity === 0.0) this.sceneHelper.setFocusMarkerVisibility(false);
  10649. }
  10650. if (currentFocusMarkerOpacity > 0.0) this.forceRenderNextFrame();
  10651. wasTransitioning = false;
  10652. }
  10653. };
  10654. }();
  10655. updateMeshCursor = function() {
  10656. const outHits = [];
  10657. const renderDimensions = new THREE.Vector2();
  10658. return function() {
  10659. if (this.showMeshCursor) {
  10660. this.forceRenderNextFrame();
  10661. this.getRenderDimensions(renderDimensions);
  10662. outHits.length = 0;
  10663. this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions);
  10664. this.raycaster.intersectSplatMesh(this.splatMesh, outHits);
  10665. if (outHits.length > 0) {
  10666. this.sceneHelper.setMeshCursorVisibility(true);
  10667. this.sceneHelper.positionAndOrientMeshCursor(outHits[0].origin, this.camera);
  10668. } else {
  10669. this.sceneHelper.setMeshCursorVisibility(false);
  10670. }
  10671. } else {
  10672. if (this.sceneHelper.getMeschCursorVisibility()) this.forceRenderNextFrame();
  10673. this.sceneHelper.setMeshCursorVisibility(false);
  10674. }
  10675. };
  10676. }();
  10677. updateInfoPanel = function() {
  10678. const renderDimensions = new THREE.Vector2();
  10679. return function() {
  10680. if (!this.showInfo) return;
  10681. const splatCount = this.splatMesh.getSplatCount();
  10682. this.getRenderDimensions(renderDimensions);
  10683. const cameraLookAtPosition = this.controls ? this.controls.target : null;
  10684. const meshCursorPosition = this.showMeshCursor ? this.sceneHelper.meshCursor.position : null;
  10685. const splatRenderCountPct = splatCount > 0 ? this.splatRenderCount / splatCount * 100 : 0;
  10686. this.infoPanel.update(renderDimensions, this.camera.position, cameraLookAtPosition,
  10687. this.camera.up, this.camera.isOrthographicCamera, meshCursorPosition,
  10688. this.currentFPS || 'N/A', splatCount, this.splatRenderCount, splatRenderCountPct,
  10689. this.lastSortTime, this.focalAdjustment, this.splatMesh.getSplatScale(),
  10690. this.splatMesh.getPointCloudModeEnabled());
  10691. };
  10692. }();
  10693. updateControlPlane() {
  10694. if (this.showControlPlane) {
  10695. this.sceneHelper.setControlPlaneVisibility(true);
  10696. this.sceneHelper.positionAndOrientControlPlane(this.controls.target, this.camera.up);
  10697. } else {
  10698. this.sceneHelper.setControlPlaneVisibility(false);
  10699. }
  10700. }
  10701. runSplatSort = function() {
  10702. const mvpMatrix = new THREE.Matrix4();
  10703. const cameraPositionArray = [];
  10704. const lastSortViewDir = new THREE.Vector3(0, 0, -1);
  10705. const sortViewDir = new THREE.Vector3(0, 0, -1);
  10706. const lastSortViewPos = new THREE.Vector3();
  10707. const sortViewOffset = new THREE.Vector3();
  10708. const queuedSorts = [];
  10709. const partialSorts = [
  10710. {
  10711. 'angleThreshold': 0.55,
  10712. 'sortFractions': [0.125, 0.33333, 0.75]
  10713. },
  10714. {
  10715. 'angleThreshold': 0.65,
  10716. 'sortFractions': [0.33333, 0.66667]
  10717. },
  10718. {
  10719. 'angleThreshold': 0.8,
  10720. 'sortFractions': [0.5]
  10721. }
  10722. ];
  10723. return function(force = false) {
  10724. if (!this.initialized) return Promise.resolve(false);
  10725. if (this.sortRunning) return Promise.resolve(true);
  10726. if (this.splatMesh.getSplatCount() <= 0) {
  10727. this.splatRenderCount = 0;
  10728. return false;
  10729. }
  10730. let angleDiff = 0;
  10731. let positionDiff = 0;
  10732. let needsRefreshForRotation = false;
  10733. let needsRefreshForPosition = false;
  10734. sortViewDir.set(0, 0, -1).applyQuaternion(this.camera.quaternion);
  10735. angleDiff = sortViewDir.dot(lastSortViewDir);
  10736. positionDiff = sortViewOffset.copy(this.camera.position).sub(lastSortViewPos).length();
  10737. if (!force) {
  10738. if (!this.splatMesh.dynamicMode && queuedSorts.length === 0) {
  10739. if (angleDiff <= 0.99) needsRefreshForRotation = true;
  10740. if (positionDiff >= 1.0) needsRefreshForPosition = true;
  10741. if (!needsRefreshForRotation && !needsRefreshForPosition) return Promise.resolve(false);
  10742. }
  10743. }
  10744. this.sortRunning = true;
  10745. const { splatRenderCount, shouldSortAll } = this.gatherSceneNodesForSort();
  10746. this.splatRenderCount = splatRenderCount;
  10747. mvpMatrix.copy(this.camera.matrixWorld).invert();
  10748. const mvpCamera = this.perspectiveCamera || this.camera;
  10749. mvpMatrix.premultiply(mvpCamera.projectionMatrix);
  10750. mvpMatrix.multiply(this.splatMesh.matrixWorld);
  10751. let gpuAcceleratedSortPromise = Promise.resolve();
  10752. if (this.gpuAcceleratedSort && (queuedSorts.length <= 1 || queuedSorts.length % 2 === 0)) {
  10753. gpuAcceleratedSortPromise = this.splatMesh.computeDistancesOnGPU(mvpMatrix, this.sortWorkerPrecomputedDistances);
  10754. }
  10755. gpuAcceleratedSortPromise.then(() => {
  10756. if (this.splatMesh.dynamicMode || shouldSortAll) {
  10757. queuedSorts.push(this.splatRenderCount);
  10758. } else {
  10759. if (queuedSorts.length === 0) {
  10760. for (let partialSort of partialSorts) {
  10761. if (angleDiff < partialSort.angleThreshold) {
  10762. for (let sortFraction of partialSort.sortFractions) {
  10763. queuedSorts.push(Math.floor(this.splatRenderCount * sortFraction));
  10764. }
  10765. break;
  10766. }
  10767. }
  10768. queuedSorts.push(this.splatRenderCount);
  10769. }
  10770. }
  10771. let sortCount = Math.min(queuedSorts.shift(), this.splatRenderCount);
  10772. cameraPositionArray[0] = this.camera.position.x;
  10773. cameraPositionArray[1] = this.camera.position.y;
  10774. cameraPositionArray[2] = this.camera.position.z;
  10775. const sortMessage = {
  10776. 'modelViewProj': mvpMatrix.elements,
  10777. 'cameraPosition': cameraPositionArray,
  10778. 'splatRenderCount': this.splatRenderCount,
  10779. 'splatSortCount': sortCount,
  10780. 'usePrecomputedDistances': this.gpuAcceleratedSort
  10781. };
  10782. if (this.splatMesh.dynamicMode) {
  10783. this.splatMesh.fillTransformsArray(this.sortWorkerTransforms);
  10784. }
  10785. if (!this.sharedMemoryForWorkers) {
  10786. sortMessage.indexesToSort = this.sortWorkerIndexesToSort;
  10787. sortMessage.transforms = this.sortWorkerTransforms;
  10788. if (this.gpuAcceleratedSort) {
  10789. sortMessage.precomputedDistances = this.sortWorkerPrecomputedDistances;
  10790. }
  10791. }
  10792. this.sortPromise = new Promise((resolve) => {
  10793. this.sortPromiseResolver = resolve;
  10794. });
  10795. this.sortWorker.postMessage({
  10796. 'sort': sortMessage
  10797. });
  10798. if (queuedSorts.length === 0) {
  10799. lastSortViewPos.copy(this.camera.position);
  10800. lastSortViewDir.copy(sortViewDir);
  10801. }
  10802. });
  10803. return gpuAcceleratedSortPromise;
  10804. };
  10805. }();
  10806. /**
  10807. * Determine which splats to render by checking which are inside or close to the view frustum
  10808. */
  10809. gatherSceneNodesForSort = function() {
  10810. const nodeRenderList = [];
  10811. let allSplatsSortBuffer = null;
  10812. const tempVectorYZ = new THREE.Vector3();
  10813. const tempVectorXZ = new THREE.Vector3();
  10814. const tempVector = new THREE.Vector3();
  10815. const modelView = new THREE.Matrix4();
  10816. const baseModelView = new THREE.Matrix4();
  10817. const sceneTransform = new THREE.Matrix4();
  10818. const renderDimensions = new THREE.Vector3();
  10819. const forward = new THREE.Vector3(0, 0, -1);
  10820. const tempMax = new THREE.Vector3();
  10821. const nodeSize = (node) => {
  10822. return tempMax.copy(node.max).sub(node.min).length();
  10823. };
  10824. return function(gatherAllNodes = false) {
  10825. this.getRenderDimensions(renderDimensions);
  10826. const cameraFocalLength = (renderDimensions.y / 2.0) / Math.tan(this.camera.fov / 2.0 * THREE.MathUtils.DEG2RAD);
  10827. const fovXOver2 = Math.atan(renderDimensions.x / 2.0 / cameraFocalLength);
  10828. const fovYOver2 = Math.atan(renderDimensions.y / 2.0 / cameraFocalLength);
  10829. const cosFovXOver2 = Math.cos(fovXOver2);
  10830. const cosFovYOver2 = Math.cos(fovYOver2);
  10831. const splatTree = this.splatMesh.getSplatTree();
  10832. if (splatTree) {
  10833. baseModelView.copy(this.camera.matrixWorld).invert();
  10834. baseModelView.multiply(this.splatMesh.matrixWorld);
  10835. let nodeRenderCount = 0;
  10836. let splatRenderCount = 0;
  10837. for (let s = 0; s < splatTree.subTrees.length; s++) {
  10838. const subTree = splatTree.subTrees[s];
  10839. modelView.copy(baseModelView);
  10840. if (this.splatMesh.dynamicMode) {
  10841. this.splatMesh.getSceneTransform(s, sceneTransform);
  10842. modelView.multiply(sceneTransform);
  10843. }
  10844. const nodeCount = subTree.nodesWithIndexes.length;
  10845. for (let i = 0; i < nodeCount; i++) {
  10846. const node = subTree.nodesWithIndexes[i];
  10847. if (!node.data || !node.data.indexes || node.data.indexes.length === 0) continue;
  10848. tempVector.copy(node.center).applyMatrix4(modelView);
  10849. const distanceToNode = tempVector.length();
  10850. tempVector.normalize();
  10851. tempVectorYZ.copy(tempVector).setX(0).normalize();
  10852. tempVectorXZ.copy(tempVector).setY(0).normalize();
  10853. const cameraAngleXZDot = forward.dot(tempVectorXZ);
  10854. const cameraAngleYZDot = forward.dot(tempVectorYZ);
  10855. const ns = nodeSize(node);
  10856. const outOfFovY = cameraAngleYZDot < (cosFovYOver2 - .6);
  10857. const outOfFovX = cameraAngleXZDot < (cosFovXOver2 - .6);
  10858. if (!gatherAllNodes && ((outOfFovX || outOfFovY) && distanceToNode > ns)) {
  10859. continue;
  10860. }
  10861. splatRenderCount += node.data.indexes.length;
  10862. nodeRenderList[nodeRenderCount] = node;
  10863. node.data.distanceToNode = distanceToNode;
  10864. nodeRenderCount++;
  10865. }
  10866. }
  10867. nodeRenderList.length = nodeRenderCount;
  10868. nodeRenderList.sort((a, b) => {
  10869. if (a.data.distanceToNode < b.data.distanceToNode) return -1;
  10870. else return 1;
  10871. });
  10872. let currentByteOffset = splatRenderCount * Constants.BytesPerInt;
  10873. for (let i = 0; i < nodeRenderCount; i++) {
  10874. const node = nodeRenderList[i];
  10875. const windowSizeInts = node.data.indexes.length;
  10876. const windowSizeBytes = windowSizeInts * Constants.BytesPerInt;
  10877. let destView = new Uint32Array(this.sortWorkerIndexesToSort.buffer,
  10878. currentByteOffset - windowSizeBytes, windowSizeInts);
  10879. destView.set(node.data.indexes);
  10880. currentByteOffset -= windowSizeBytes;
  10881. }
  10882. return {
  10883. 'splatRenderCount': splatRenderCount,
  10884. 'shouldSortAll': false
  10885. };
  10886. } else {
  10887. const totalSplatCount = this.splatMesh.getSplatCount();
  10888. if (!allSplatsSortBuffer || allSplatsSortBuffer.length !== totalSplatCount) {
  10889. allSplatsSortBuffer = new Uint32Array(totalSplatCount);
  10890. for (let i = 0; i < totalSplatCount; i++) {
  10891. allSplatsSortBuffer[i] = i;
  10892. }
  10893. }
  10894. this.sortWorkerIndexesToSort.set(allSplatsSortBuffer);
  10895. return {
  10896. 'splatRenderCount': totalSplatCount,
  10897. 'shouldSortAll': true
  10898. };
  10899. }
  10900. };
  10901. }();
  10902. getSplatMesh() {
  10903. return this.splatMesh;
  10904. }
  10905. /**
  10906. * Get a reference to a splat scene.
  10907. * @param {number} sceneIndex The index of the scene to which the reference will be returned
  10908. * @return {SplatScene}
  10909. */
  10910. getSplatScene(sceneIndex) {
  10911. return this.splatMesh.getScene(sceneIndex);
  10912. }
  10913. getSceneCount() {
  10914. return this.splatMesh.getSceneCount();
  10915. }
  10916. isMobile() {
  10917. return navigator.userAgent.includes('Mobi');
  10918. }
  10919. }
  10920. /**
  10921. * DropInViewer: Wrapper for a Viewer instance that enables it to be added to a Three.js scene like
  10922. * any other Three.js scene object (Mesh, Object3D, etc.)
  10923. */
  10924. class DropInViewer extends THREE.Group {
  10925. constructor(options = {}) {
  10926. super();
  10927. options.selfDrivenMode = false;
  10928. options.useBuiltInControls = false;
  10929. options.rootElement = null;
  10930. options.ignoreDevicePixelRatio = false;
  10931. options.dropInMode = true;
  10932. options.camera = undefined;
  10933. options.renderer = undefined;
  10934. this.viewer = new Viewer(options);
  10935. this.splatMesh = null;
  10936. this.updateSplatMesh();
  10937. this.callbackMesh = DropInViewer.createCallbackMesh();
  10938. this.add(this.callbackMesh);
  10939. this.callbackMesh.onBeforeRender = DropInViewer.onBeforeRender.bind(this, this.viewer);
  10940. this.viewer.onSplatMeshChanged(() => {
  10941. this.updateSplatMesh();
  10942. });
  10943. }
  10944. updateSplatMesh() {
  10945. if (this.splatMesh !== this.viewer.splatMesh) {
  10946. if (this.splatMesh) {
  10947. this.remove(this.splatMesh);
  10948. }
  10949. this.splatMesh = this.viewer.splatMesh;
  10950. this.add(this.viewer.splatMesh);
  10951. }
  10952. }
  10953. /**
  10954. * Add a single splat scene to the viewer.
  10955. * @param {string} path Path to splat scene to be loaded
  10956. * @param {object} options {
  10957. *
  10958. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  10959. * value (valid range: 0 - 255), defaults to 1
  10960. *
  10961. * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true
  10962. *
  10963. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  10964. *
  10965. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  10966. *
  10967. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  10968. *
  10969. * onProgress: Function to be called as file data are received
  10970. *
  10971. * }
  10972. * @return {AbortablePromise}
  10973. */
  10974. addSplatScene(path, options = {}) {
  10975. if (options.showLoadingUI !== false) options.showLoadingUI = true;
  10976. return this.viewer.addSplatScene(path, options);
  10977. }
  10978. /**
  10979. * Add multiple splat scenes to the viewer.
  10980. * @param {Array<object>} sceneOptions Array of per-scene options: {
  10981. *
  10982. * path: Path to splat scene to be loaded
  10983. *
  10984. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  10985. * value (valid range: 0 - 255), defaults to 1
  10986. *
  10987. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  10988. *
  10989. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  10990. *
  10991. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  10992. * }
  10993. * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true
  10994. * @return {AbortablePromise}
  10995. */
  10996. addSplatScenes(sceneOptions, showLoadingUI) {
  10997. if (showLoadingUI !== false) showLoadingUI = true;
  10998. return this.viewer.addSplatScenes(sceneOptions, showLoadingUI);
  10999. }
  11000. /**
  11001. * Get a reference to a splat scene.
  11002. * @param {number} sceneIndex The index of the scene to which the reference will be returned
  11003. * @return {SplatScene}
  11004. */
  11005. getSplatScene(sceneIndex) {
  11006. return this.viewer.getSplatScene(sceneIndex);
  11007. }
  11008. removeSplatScene(index, showLoadingUI = true) {
  11009. return this.viewer.removeSplatScene(index, showLoadingUI);
  11010. }
  11011. removeSplatScenes(indexes, showLoadingUI = true) {
  11012. return this.viewer.removeSplatScenes(indexes, showLoadingUI);
  11013. }
  11014. getSceneCount() {
  11015. return this.viewer.getSceneCount();
  11016. }
  11017. dispose() {
  11018. return this.viewer.dispose();
  11019. }
  11020. static onBeforeRender(viewer, renderer, threeScene, camera) {
  11021. viewer.update(renderer, camera);
  11022. }
  11023. static createCallbackMesh() {
  11024. const geometry = new THREE.SphereGeometry(1, 8, 8);
  11025. const material = new THREE.MeshBasicMaterial();
  11026. material.colorWrite = false;
  11027. material.depthWrite = false;
  11028. const mesh = new THREE.Mesh(geometry, material);
  11029. mesh.frustumCulled = false;
  11030. return mesh;
  11031. }
  11032. }
  11033. export { AbortablePromise, DropInViewer, KSplatLoader, Utils as LoaderUtils, LogLevel, OrbitControls, PlayCanvasCompressedPlyParser, PlyLoader, PlyParser, RenderMode, SceneFormat, SceneRevealMode, SplatBuffer, SplatBufferGenerator, SplatLoader, SplatParser, SplatPartitioner, SplatRenderMode, Viewer, WebXRMode
  11034. ,Raycaster //xzw add
  11035. }
  11036. //# sourceMappingURL=gaussian-splats-3d.module.js.map
  11037. /* 2024.9.18 修改如下(目的:修复移动模型后sh的光影错误的bug)
  11038. 如果dynamic为false,直接改变splatScene的position且updateMatrixWorld不会有变化。 也就是它的matrix transform没作用
  11039. viewer.splatMesh.children 变为 [], 没有变化。 所以猜测splatMesh.children无用,只不过是用到它的transform
  11040. 那么初始的位置是直接作用到splatCenter? 改变初始位置后splatTree里的bound变了! dynamic的话就不变
  11041. 如果dynamic为true , 移动scene 光影正确, 但 为什么所有0929的文件dynamic时都pick不到点?!!!! bound因最外层的marixW不对所以不对
  11042. 最后决定:
  11043. 改回用最外层,dynamic,在shader里弃用transform,改为直接用最外层的modelViewMatrix:mat4 transformModelViewMatrix = modelViewMatrix; 这样我就不需要改potree代码了。
  11044. vec3 worldViewDir = normalize(splatCenter - vec3(inverse(modelMatrix) * vec4(cameraPosition, 1.0)));
  11045. splatScene.updateTransform 将transfrom改为matrix, 或者直接单位矩阵。 for pick 和 node visible
  11046. 但0829还是pick不了,发现是castRayAtSplatTreeNode函数中tempScale.x为0,原因未知,只好把这段判断去除。
  11047. */